diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/eventstore/Program.cs b/eventstore/Program.cs new file mode 100644 index 0000000..5999ac1 --- /dev/null +++ b/eventstore/Program.cs @@ -0,0 +1,99 @@ +using EventSourcing.Demo; +using EventStore.ClientAPI.Exceptions; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/products/{sku}", async (HttpResponse response, string sku) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + //response.Headers.ETag = product.Version.ToString(); + + return new + { + Sku = product.Aggregate.Sku, + Quantity = product.Aggregate.GetQuantityOnHand(), + Version = product.Version, + Commands = new Command[] + { + new("InventoryAdjustment", $"/products/{sku}/{product.Version}/adjustment") + } + }; +}); + +app.MapPost("/products/{sku}/adjustment", async (HttpRequest request, HttpResponse response, [FromRoute]string sku, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + + var eTag = request.GetIfMatch(); + if (eTag != null) + { + try + { + await stream.Save(product.Aggregate, eTag.Value); + response.StatusCode = 204; + return; + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } + } + + response.StatusCode = 412; +}); + +app.MapPost("/products/{sku}/{version}/adjustment", + async (HttpResponse response, [FromRoute]string sku, [FromRoute]long version, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + try + { + await stream.Save(product.Aggregate, version); + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } +}); + +app.Run(); + +public class InventoryAdjustment +{ + public int Quantity { get; set; } + public string Reason { get; set; } +} + +public static class Extensions +{ + public static long? GetIfMatch(this HttpRequest request) + { + var headers = request.GetTypedHeaders(); + var eTag = headers.IfMatch.FirstOrDefault()?.Tag.Value.Replace("\"", ""); + if (eTag != null && long.TryParse(eTag, out var version)) + { + return version; + } + + return null; + } +} + +public class Command +{ + public Command(string action, string uri) + { + Action = action; + Uri = uri; + } + + public string Action { get; set; } + public string Uri { get; set; } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/eventstore/Program.cs b/eventstore/Program.cs new file mode 100644 index 0000000..5999ac1 --- /dev/null +++ b/eventstore/Program.cs @@ -0,0 +1,99 @@ +using EventSourcing.Demo; +using EventStore.ClientAPI.Exceptions; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/products/{sku}", async (HttpResponse response, string sku) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + //response.Headers.ETag = product.Version.ToString(); + + return new + { + Sku = product.Aggregate.Sku, + Quantity = product.Aggregate.GetQuantityOnHand(), + Version = product.Version, + Commands = new Command[] + { + new("InventoryAdjustment", $"/products/{sku}/{product.Version}/adjustment") + } + }; +}); + +app.MapPost("/products/{sku}/adjustment", async (HttpRequest request, HttpResponse response, [FromRoute]string sku, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + + var eTag = request.GetIfMatch(); + if (eTag != null) + { + try + { + await stream.Save(product.Aggregate, eTag.Value); + response.StatusCode = 204; + return; + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } + } + + response.StatusCode = 412; +}); + +app.MapPost("/products/{sku}/{version}/adjustment", + async (HttpResponse response, [FromRoute]string sku, [FromRoute]long version, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + try + { + await stream.Save(product.Aggregate, version); + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } +}); + +app.Run(); + +public class InventoryAdjustment +{ + public int Quantity { get; set; } + public string Reason { get; set; } +} + +public static class Extensions +{ + public static long? GetIfMatch(this HttpRequest request) + { + var headers = request.GetTypedHeaders(); + var eTag = headers.IfMatch.FirstOrDefault()?.Tag.Value.Replace("\"", ""); + if (eTag != null && long.TryParse(eTag, out var version)) + { + return version; + } + + return null; + } +} + +public class Command +{ + public Command(string action, string uri) + { + Action = action; + Uri = uri; + } + + public string Action { get; set; } + public string Uri { get; set; } +} diff --git a/eventstore/Properties/launchSettings.json b/eventstore/Properties/launchSettings.json new file mode 100644 index 0000000..98b2753 --- /dev/null +++ b/eventstore/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59639", + "sslPort": 44373 + } + }, + "profiles": { + "eventstore": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7145;http://localhost:5215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/eventstore/Program.cs b/eventstore/Program.cs new file mode 100644 index 0000000..5999ac1 --- /dev/null +++ b/eventstore/Program.cs @@ -0,0 +1,99 @@ +using EventSourcing.Demo; +using EventStore.ClientAPI.Exceptions; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/products/{sku}", async (HttpResponse response, string sku) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + //response.Headers.ETag = product.Version.ToString(); + + return new + { + Sku = product.Aggregate.Sku, + Quantity = product.Aggregate.GetQuantityOnHand(), + Version = product.Version, + Commands = new Command[] + { + new("InventoryAdjustment", $"/products/{sku}/{product.Version}/adjustment") + } + }; +}); + +app.MapPost("/products/{sku}/adjustment", async (HttpRequest request, HttpResponse response, [FromRoute]string sku, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + + var eTag = request.GetIfMatch(); + if (eTag != null) + { + try + { + await stream.Save(product.Aggregate, eTag.Value); + response.StatusCode = 204; + return; + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } + } + + response.StatusCode = 412; +}); + +app.MapPost("/products/{sku}/{version}/adjustment", + async (HttpResponse response, [FromRoute]string sku, [FromRoute]long version, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + try + { + await stream.Save(product.Aggregate, version); + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } +}); + +app.Run(); + +public class InventoryAdjustment +{ + public int Quantity { get; set; } + public string Reason { get; set; } +} + +public static class Extensions +{ + public static long? GetIfMatch(this HttpRequest request) + { + var headers = request.GetTypedHeaders(); + var eTag = headers.IfMatch.FirstOrDefault()?.Tag.Value.Replace("\"", ""); + if (eTag != null && long.TryParse(eTag, out var version)) + { + return version; + } + + return null; + } +} + +public class Command +{ + public Command(string action, string uri) + { + Action = action; + Uri = uri; + } + + public string Action { get; set; } + public string Uri { get; set; } +} diff --git a/eventstore/Properties/launchSettings.json b/eventstore/Properties/launchSettings.json new file mode 100644 index 0000000..98b2753 --- /dev/null +++ b/eventstore/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59639", + "sslPort": 44373 + } + }, + "profiles": { + "eventstore": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7145;http://localhost:5215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/eventstore/WarehouseProduct.cs b/eventstore/WarehouseProduct.cs new file mode 100644 index 0000000..44bd429 --- /dev/null +++ b/eventstore/WarehouseProduct.cs @@ -0,0 +1,122 @@ +namespace EventSourcing.Demo +{ + public class WarehouseProductState + { + public int QuantityOnHand { get; set; } + } + + public class WarehouseProduct + { + public string Sku { get; } + private readonly IList _allEvents = new List(); + private readonly IList _uncommittedEvents = new List(); + + // Projection (Current State) + private readonly WarehouseProductState _warehouseProductState; + + public WarehouseProduct(string sku, WarehouseProductState state) + { + Sku = sku; + _warehouseProductState = state; + } + + public WarehouseProductState GetState() + { + return _warehouseProductState; + } + + public void ShipProduct(int quantity) + { + if (quantity > _warehouseProductState.QuantityOnHand) + { + throw new InvalidDomainException("Ah... we don't have enough product to ship?"); + } + + AddEvent(new ProductShipped(Sku, quantity, DateTime.UtcNow)); + } + + public void ReceiveProduct(int quantity) + { + AddEvent(new ProductReceived(Sku, quantity, DateTime.UtcNow)); + } + + public void AdjustInventory(int quantity, string reason) + { + if (_warehouseProductState.QuantityOnHand + quantity < 0) + { + throw new InvalidDomainException("Cannot adjust to a negative quantity on hand."); + } + + AddEvent(new InventoryAdjusted(Sku, quantity, reason, DateTime.UtcNow)); + } + + private void Apply(ProductShipped evnt) + { + _warehouseProductState.QuantityOnHand -= evnt.Quantity; + } + + private void Apply(ProductReceived evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + private void Apply(InventoryAdjusted evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + public void ApplyEvent(IEvent evnt) + { + switch (evnt) + { + case ProductShipped shipProduct: + Apply(shipProduct); + break; + case ProductReceived receiveProduct: + Apply(receiveProduct); + break; + case InventoryAdjusted inventoryAdjusted: + Apply(inventoryAdjusted); + break; + default: + throw new InvalidOperationException("Unsupported Event."); + } + + _allEvents.Add(evnt); + } + + private void AddEvent(IEvent evnt) + { + ApplyEvent(evnt); + _uncommittedEvents.Add(evnt); + } + + public IList GetUncommittedEvents() + { + return new List(_uncommittedEvents); + } + + public IList GetAllEvents() + { + return new List(_allEvents); + } + + public void EventsCommitted() + { + _uncommittedEvents.Clear(); + } + + public int GetQuantityOnHand() + { + return _warehouseProductState.QuantityOnHand; + } + } + + public class InvalidDomainException : Exception + { + public InvalidDomainException(string message) : base(message) + { + + } + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/eventstore/Program.cs b/eventstore/Program.cs new file mode 100644 index 0000000..5999ac1 --- /dev/null +++ b/eventstore/Program.cs @@ -0,0 +1,99 @@ +using EventSourcing.Demo; +using EventStore.ClientAPI.Exceptions; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/products/{sku}", async (HttpResponse response, string sku) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + //response.Headers.ETag = product.Version.ToString(); + + return new + { + Sku = product.Aggregate.Sku, + Quantity = product.Aggregate.GetQuantityOnHand(), + Version = product.Version, + Commands = new Command[] + { + new("InventoryAdjustment", $"/products/{sku}/{product.Version}/adjustment") + } + }; +}); + +app.MapPost("/products/{sku}/adjustment", async (HttpRequest request, HttpResponse response, [FromRoute]string sku, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + + var eTag = request.GetIfMatch(); + if (eTag != null) + { + try + { + await stream.Save(product.Aggregate, eTag.Value); + response.StatusCode = 204; + return; + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } + } + + response.StatusCode = 412; +}); + +app.MapPost("/products/{sku}/{version}/adjustment", + async (HttpResponse response, [FromRoute]string sku, [FromRoute]long version, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + try + { + await stream.Save(product.Aggregate, version); + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } +}); + +app.Run(); + +public class InventoryAdjustment +{ + public int Quantity { get; set; } + public string Reason { get; set; } +} + +public static class Extensions +{ + public static long? GetIfMatch(this HttpRequest request) + { + var headers = request.GetTypedHeaders(); + var eTag = headers.IfMatch.FirstOrDefault()?.Tag.Value.Replace("\"", ""); + if (eTag != null && long.TryParse(eTag, out var version)) + { + return version; + } + + return null; + } +} + +public class Command +{ + public Command(string action, string uri) + { + Action = action; + Uri = uri; + } + + public string Action { get; set; } + public string Uri { get; set; } +} diff --git a/eventstore/Properties/launchSettings.json b/eventstore/Properties/launchSettings.json new file mode 100644 index 0000000..98b2753 --- /dev/null +++ b/eventstore/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59639", + "sslPort": 44373 + } + }, + "profiles": { + "eventstore": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7145;http://localhost:5215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/eventstore/WarehouseProduct.cs b/eventstore/WarehouseProduct.cs new file mode 100644 index 0000000..44bd429 --- /dev/null +++ b/eventstore/WarehouseProduct.cs @@ -0,0 +1,122 @@ +namespace EventSourcing.Demo +{ + public class WarehouseProductState + { + public int QuantityOnHand { get; set; } + } + + public class WarehouseProduct + { + public string Sku { get; } + private readonly IList _allEvents = new List(); + private readonly IList _uncommittedEvents = new List(); + + // Projection (Current State) + private readonly WarehouseProductState _warehouseProductState; + + public WarehouseProduct(string sku, WarehouseProductState state) + { + Sku = sku; + _warehouseProductState = state; + } + + public WarehouseProductState GetState() + { + return _warehouseProductState; + } + + public void ShipProduct(int quantity) + { + if (quantity > _warehouseProductState.QuantityOnHand) + { + throw new InvalidDomainException("Ah... we don't have enough product to ship?"); + } + + AddEvent(new ProductShipped(Sku, quantity, DateTime.UtcNow)); + } + + public void ReceiveProduct(int quantity) + { + AddEvent(new ProductReceived(Sku, quantity, DateTime.UtcNow)); + } + + public void AdjustInventory(int quantity, string reason) + { + if (_warehouseProductState.QuantityOnHand + quantity < 0) + { + throw new InvalidDomainException("Cannot adjust to a negative quantity on hand."); + } + + AddEvent(new InventoryAdjusted(Sku, quantity, reason, DateTime.UtcNow)); + } + + private void Apply(ProductShipped evnt) + { + _warehouseProductState.QuantityOnHand -= evnt.Quantity; + } + + private void Apply(ProductReceived evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + private void Apply(InventoryAdjusted evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + public void ApplyEvent(IEvent evnt) + { + switch (evnt) + { + case ProductShipped shipProduct: + Apply(shipProduct); + break; + case ProductReceived receiveProduct: + Apply(receiveProduct); + break; + case InventoryAdjusted inventoryAdjusted: + Apply(inventoryAdjusted); + break; + default: + throw new InvalidOperationException("Unsupported Event."); + } + + _allEvents.Add(evnt); + } + + private void AddEvent(IEvent evnt) + { + ApplyEvent(evnt); + _uncommittedEvents.Add(evnt); + } + + public IList GetUncommittedEvents() + { + return new List(_uncommittedEvents); + } + + public IList GetAllEvents() + { + return new List(_allEvents); + } + + public void EventsCommitted() + { + _uncommittedEvents.Clear(); + } + + public int GetQuantityOnHand() + { + return _warehouseProductState.QuantityOnHand; + } + } + + public class InvalidDomainException : Exception + { + public InvalidDomainException(string message) : base(message) + { + + } + } +} \ No newline at end of file diff --git a/eventstore/WarehouseProductEventStoreStream.cs b/eventstore/WarehouseProductEventStoreStream.cs new file mode 100644 index 0000000..8607aea --- /dev/null +++ b/eventstore/WarehouseProductEventStoreStream.cs @@ -0,0 +1,116 @@ +using System.Net; +using System.Text; +using EventStore.ClientAPI; +using EventStore.ClientAPI.SystemData; +using Newtonsoft.Json; + +namespace EventSourcing.Demo +{ + public class WarehouseProductEventStoreStream : IDisposable + { + private readonly IEventStoreConnection _connection; + + public static async Task Factory() + { + var connectionSettings = ConnectionSettings.Create() + .KeepReconnecting() + .KeepRetrying() + .SetHeartbeatTimeout(TimeSpan.FromMinutes(5)) + .SetHeartbeatInterval(TimeSpan.FromMinutes(1)) + .DisableTls() + .DisableServerCertificateValidation() + .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) + .Build(); + + var conn = EventStoreConnection.Create(connectionSettings, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113)); + await conn.ConnectAsync(); + + return new WarehouseProductEventStoreStream(conn); + } + + private WarehouseProductEventStoreStream(IEventStoreConnection connection) + { + _connection = connection; + } + + private string GetStreamName(string sku) + { + return $"WarehouseProduct-{sku}"; + } + + public async Task> Get(string sku) + { + var streamName = GetStreamName(sku); + + var warehouseProduct = new WarehouseProduct(sku, new WarehouseProductState()); + + StreamEventsSlice currentSlice; + long nextSliceStart = 0; + long lastVersion = -1; + do + { + currentSlice = await _connection.ReadStreamEventsForwardAsync( + streamName, + nextSliceStart, + 200, + false + ); + + nextSliceStart = currentSlice.NextEventNumber; + + foreach (var evnt in currentSlice.Events) + { + var eventObj = DeserializeEvent(evnt); + warehouseProduct.ApplyEvent(eventObj); + lastVersion = evnt.OriginalEventNumber; + } + } while (!currentSlice.IsEndOfStream); + + return new EventStreamAggregate(warehouseProduct, lastVersion); + } + + private IEvent DeserializeEvent(ResolvedEvent evnt) + { + var json = Encoding.UTF8.GetString(evnt.Event.Data); + return evnt.Event.EventType switch + { + "InventoryAdjusted" => JsonConvert.DeserializeObject(json), + "ProductShipped" => JsonConvert.DeserializeObject(json), + "ProductReceived" => JsonConvert.DeserializeObject(json), + _ => throw new InvalidOperationException($"Unknown Event: {evnt.Event.EventType}") + }; + } + + public async Task Save(WarehouseProduct warehouseProduct, long expectedVersion) + { + var streamName = GetStreamName(warehouseProduct.Sku); + + var newEvents = warehouseProduct.GetUncommittedEvents(); + foreach (var evnt in newEvents) + { + var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt)); + var metadata = Encoding.UTF8.GetBytes("{}"); + var evt = new EventData(Guid.NewGuid(), evnt.EventType, true, data, metadata); + var result = await _connection.AppendToStreamAsync(streamName, expectedVersion, evt); + expectedVersion = result.NextExpectedVersion; + } + } + + public void Dispose() + { + _connection?.Dispose(); + } + } + + public class EventStreamAggregate + { + public EventStreamAggregate(T aggregate, long version) + { + Aggregate = aggregate; + Version = version; + } + + public T Aggregate { get; private set; } + public long Version { get; private set; } + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/eventstore/Program.cs b/eventstore/Program.cs new file mode 100644 index 0000000..5999ac1 --- /dev/null +++ b/eventstore/Program.cs @@ -0,0 +1,99 @@ +using EventSourcing.Demo; +using EventStore.ClientAPI.Exceptions; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/products/{sku}", async (HttpResponse response, string sku) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + //response.Headers.ETag = product.Version.ToString(); + + return new + { + Sku = product.Aggregate.Sku, + Quantity = product.Aggregate.GetQuantityOnHand(), + Version = product.Version, + Commands = new Command[] + { + new("InventoryAdjustment", $"/products/{sku}/{product.Version}/adjustment") + } + }; +}); + +app.MapPost("/products/{sku}/adjustment", async (HttpRequest request, HttpResponse response, [FromRoute]string sku, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + + var eTag = request.GetIfMatch(); + if (eTag != null) + { + try + { + await stream.Save(product.Aggregate, eTag.Value); + response.StatusCode = 204; + return; + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } + } + + response.StatusCode = 412; +}); + +app.MapPost("/products/{sku}/{version}/adjustment", + async (HttpResponse response, [FromRoute]string sku, [FromRoute]long version, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + try + { + await stream.Save(product.Aggregate, version); + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } +}); + +app.Run(); + +public class InventoryAdjustment +{ + public int Quantity { get; set; } + public string Reason { get; set; } +} + +public static class Extensions +{ + public static long? GetIfMatch(this HttpRequest request) + { + var headers = request.GetTypedHeaders(); + var eTag = headers.IfMatch.FirstOrDefault()?.Tag.Value.Replace("\"", ""); + if (eTag != null && long.TryParse(eTag, out var version)) + { + return version; + } + + return null; + } +} + +public class Command +{ + public Command(string action, string uri) + { + Action = action; + Uri = uri; + } + + public string Action { get; set; } + public string Uri { get; set; } +} diff --git a/eventstore/Properties/launchSettings.json b/eventstore/Properties/launchSettings.json new file mode 100644 index 0000000..98b2753 --- /dev/null +++ b/eventstore/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59639", + "sslPort": 44373 + } + }, + "profiles": { + "eventstore": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7145;http://localhost:5215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/eventstore/WarehouseProduct.cs b/eventstore/WarehouseProduct.cs new file mode 100644 index 0000000..44bd429 --- /dev/null +++ b/eventstore/WarehouseProduct.cs @@ -0,0 +1,122 @@ +namespace EventSourcing.Demo +{ + public class WarehouseProductState + { + public int QuantityOnHand { get; set; } + } + + public class WarehouseProduct + { + public string Sku { get; } + private readonly IList _allEvents = new List(); + private readonly IList _uncommittedEvents = new List(); + + // Projection (Current State) + private readonly WarehouseProductState _warehouseProductState; + + public WarehouseProduct(string sku, WarehouseProductState state) + { + Sku = sku; + _warehouseProductState = state; + } + + public WarehouseProductState GetState() + { + return _warehouseProductState; + } + + public void ShipProduct(int quantity) + { + if (quantity > _warehouseProductState.QuantityOnHand) + { + throw new InvalidDomainException("Ah... we don't have enough product to ship?"); + } + + AddEvent(new ProductShipped(Sku, quantity, DateTime.UtcNow)); + } + + public void ReceiveProduct(int quantity) + { + AddEvent(new ProductReceived(Sku, quantity, DateTime.UtcNow)); + } + + public void AdjustInventory(int quantity, string reason) + { + if (_warehouseProductState.QuantityOnHand + quantity < 0) + { + throw new InvalidDomainException("Cannot adjust to a negative quantity on hand."); + } + + AddEvent(new InventoryAdjusted(Sku, quantity, reason, DateTime.UtcNow)); + } + + private void Apply(ProductShipped evnt) + { + _warehouseProductState.QuantityOnHand -= evnt.Quantity; + } + + private void Apply(ProductReceived evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + private void Apply(InventoryAdjusted evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + public void ApplyEvent(IEvent evnt) + { + switch (evnt) + { + case ProductShipped shipProduct: + Apply(shipProduct); + break; + case ProductReceived receiveProduct: + Apply(receiveProduct); + break; + case InventoryAdjusted inventoryAdjusted: + Apply(inventoryAdjusted); + break; + default: + throw new InvalidOperationException("Unsupported Event."); + } + + _allEvents.Add(evnt); + } + + private void AddEvent(IEvent evnt) + { + ApplyEvent(evnt); + _uncommittedEvents.Add(evnt); + } + + public IList GetUncommittedEvents() + { + return new List(_uncommittedEvents); + } + + public IList GetAllEvents() + { + return new List(_allEvents); + } + + public void EventsCommitted() + { + _uncommittedEvents.Clear(); + } + + public int GetQuantityOnHand() + { + return _warehouseProductState.QuantityOnHand; + } + } + + public class InvalidDomainException : Exception + { + public InvalidDomainException(string message) : base(message) + { + + } + } +} \ No newline at end of file diff --git a/eventstore/WarehouseProductEventStoreStream.cs b/eventstore/WarehouseProductEventStoreStream.cs new file mode 100644 index 0000000..8607aea --- /dev/null +++ b/eventstore/WarehouseProductEventStoreStream.cs @@ -0,0 +1,116 @@ +using System.Net; +using System.Text; +using EventStore.ClientAPI; +using EventStore.ClientAPI.SystemData; +using Newtonsoft.Json; + +namespace EventSourcing.Demo +{ + public class WarehouseProductEventStoreStream : IDisposable + { + private readonly IEventStoreConnection _connection; + + public static async Task Factory() + { + var connectionSettings = ConnectionSettings.Create() + .KeepReconnecting() + .KeepRetrying() + .SetHeartbeatTimeout(TimeSpan.FromMinutes(5)) + .SetHeartbeatInterval(TimeSpan.FromMinutes(1)) + .DisableTls() + .DisableServerCertificateValidation() + .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) + .Build(); + + var conn = EventStoreConnection.Create(connectionSettings, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113)); + await conn.ConnectAsync(); + + return new WarehouseProductEventStoreStream(conn); + } + + private WarehouseProductEventStoreStream(IEventStoreConnection connection) + { + _connection = connection; + } + + private string GetStreamName(string sku) + { + return $"WarehouseProduct-{sku}"; + } + + public async Task> Get(string sku) + { + var streamName = GetStreamName(sku); + + var warehouseProduct = new WarehouseProduct(sku, new WarehouseProductState()); + + StreamEventsSlice currentSlice; + long nextSliceStart = 0; + long lastVersion = -1; + do + { + currentSlice = await _connection.ReadStreamEventsForwardAsync( + streamName, + nextSliceStart, + 200, + false + ); + + nextSliceStart = currentSlice.NextEventNumber; + + foreach (var evnt in currentSlice.Events) + { + var eventObj = DeserializeEvent(evnt); + warehouseProduct.ApplyEvent(eventObj); + lastVersion = evnt.OriginalEventNumber; + } + } while (!currentSlice.IsEndOfStream); + + return new EventStreamAggregate(warehouseProduct, lastVersion); + } + + private IEvent DeserializeEvent(ResolvedEvent evnt) + { + var json = Encoding.UTF8.GetString(evnt.Event.Data); + return evnt.Event.EventType switch + { + "InventoryAdjusted" => JsonConvert.DeserializeObject(json), + "ProductShipped" => JsonConvert.DeserializeObject(json), + "ProductReceived" => JsonConvert.DeserializeObject(json), + _ => throw new InvalidOperationException($"Unknown Event: {evnt.Event.EventType}") + }; + } + + public async Task Save(WarehouseProduct warehouseProduct, long expectedVersion) + { + var streamName = GetStreamName(warehouseProduct.Sku); + + var newEvents = warehouseProduct.GetUncommittedEvents(); + foreach (var evnt in newEvents) + { + var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt)); + var metadata = Encoding.UTF8.GetBytes("{}"); + var evt = new EventData(Guid.NewGuid(), evnt.EventType, true, data, metadata); + var result = await _connection.AppendToStreamAsync(streamName, expectedVersion, evt); + expectedVersion = result.NextExpectedVersion; + } + } + + public void Dispose() + { + _connection?.Dispose(); + } + } + + public class EventStreamAggregate + { + public EventStreamAggregate(T aggregate, long version) + { + Aggregate = aggregate; + Version = version; + } + + public T Aggregate { get; private set; } + public long Version { get; private set; } + } +} \ No newline at end of file diff --git a/eventstore/appsettings.Development.json b/eventstore/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/eventstore/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/eventstore/Program.cs b/eventstore/Program.cs new file mode 100644 index 0000000..5999ac1 --- /dev/null +++ b/eventstore/Program.cs @@ -0,0 +1,99 @@ +using EventSourcing.Demo; +using EventStore.ClientAPI.Exceptions; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/products/{sku}", async (HttpResponse response, string sku) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + //response.Headers.ETag = product.Version.ToString(); + + return new + { + Sku = product.Aggregate.Sku, + Quantity = product.Aggregate.GetQuantityOnHand(), + Version = product.Version, + Commands = new Command[] + { + new("InventoryAdjustment", $"/products/{sku}/{product.Version}/adjustment") + } + }; +}); + +app.MapPost("/products/{sku}/adjustment", async (HttpRequest request, HttpResponse response, [FromRoute]string sku, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + + var eTag = request.GetIfMatch(); + if (eTag != null) + { + try + { + await stream.Save(product.Aggregate, eTag.Value); + response.StatusCode = 204; + return; + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } + } + + response.StatusCode = 412; +}); + +app.MapPost("/products/{sku}/{version}/adjustment", + async (HttpResponse response, [FromRoute]string sku, [FromRoute]long version, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + try + { + await stream.Save(product.Aggregate, version); + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } +}); + +app.Run(); + +public class InventoryAdjustment +{ + public int Quantity { get; set; } + public string Reason { get; set; } +} + +public static class Extensions +{ + public static long? GetIfMatch(this HttpRequest request) + { + var headers = request.GetTypedHeaders(); + var eTag = headers.IfMatch.FirstOrDefault()?.Tag.Value.Replace("\"", ""); + if (eTag != null && long.TryParse(eTag, out var version)) + { + return version; + } + + return null; + } +} + +public class Command +{ + public Command(string action, string uri) + { + Action = action; + Uri = uri; + } + + public string Action { get; set; } + public string Uri { get; set; } +} diff --git a/eventstore/Properties/launchSettings.json b/eventstore/Properties/launchSettings.json new file mode 100644 index 0000000..98b2753 --- /dev/null +++ b/eventstore/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59639", + "sslPort": 44373 + } + }, + "profiles": { + "eventstore": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7145;http://localhost:5215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/eventstore/WarehouseProduct.cs b/eventstore/WarehouseProduct.cs new file mode 100644 index 0000000..44bd429 --- /dev/null +++ b/eventstore/WarehouseProduct.cs @@ -0,0 +1,122 @@ +namespace EventSourcing.Demo +{ + public class WarehouseProductState + { + public int QuantityOnHand { get; set; } + } + + public class WarehouseProduct + { + public string Sku { get; } + private readonly IList _allEvents = new List(); + private readonly IList _uncommittedEvents = new List(); + + // Projection (Current State) + private readonly WarehouseProductState _warehouseProductState; + + public WarehouseProduct(string sku, WarehouseProductState state) + { + Sku = sku; + _warehouseProductState = state; + } + + public WarehouseProductState GetState() + { + return _warehouseProductState; + } + + public void ShipProduct(int quantity) + { + if (quantity > _warehouseProductState.QuantityOnHand) + { + throw new InvalidDomainException("Ah... we don't have enough product to ship?"); + } + + AddEvent(new ProductShipped(Sku, quantity, DateTime.UtcNow)); + } + + public void ReceiveProduct(int quantity) + { + AddEvent(new ProductReceived(Sku, quantity, DateTime.UtcNow)); + } + + public void AdjustInventory(int quantity, string reason) + { + if (_warehouseProductState.QuantityOnHand + quantity < 0) + { + throw new InvalidDomainException("Cannot adjust to a negative quantity on hand."); + } + + AddEvent(new InventoryAdjusted(Sku, quantity, reason, DateTime.UtcNow)); + } + + private void Apply(ProductShipped evnt) + { + _warehouseProductState.QuantityOnHand -= evnt.Quantity; + } + + private void Apply(ProductReceived evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + private void Apply(InventoryAdjusted evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + public void ApplyEvent(IEvent evnt) + { + switch (evnt) + { + case ProductShipped shipProduct: + Apply(shipProduct); + break; + case ProductReceived receiveProduct: + Apply(receiveProduct); + break; + case InventoryAdjusted inventoryAdjusted: + Apply(inventoryAdjusted); + break; + default: + throw new InvalidOperationException("Unsupported Event."); + } + + _allEvents.Add(evnt); + } + + private void AddEvent(IEvent evnt) + { + ApplyEvent(evnt); + _uncommittedEvents.Add(evnt); + } + + public IList GetUncommittedEvents() + { + return new List(_uncommittedEvents); + } + + public IList GetAllEvents() + { + return new List(_allEvents); + } + + public void EventsCommitted() + { + _uncommittedEvents.Clear(); + } + + public int GetQuantityOnHand() + { + return _warehouseProductState.QuantityOnHand; + } + } + + public class InvalidDomainException : Exception + { + public InvalidDomainException(string message) : base(message) + { + + } + } +} \ No newline at end of file diff --git a/eventstore/WarehouseProductEventStoreStream.cs b/eventstore/WarehouseProductEventStoreStream.cs new file mode 100644 index 0000000..8607aea --- /dev/null +++ b/eventstore/WarehouseProductEventStoreStream.cs @@ -0,0 +1,116 @@ +using System.Net; +using System.Text; +using EventStore.ClientAPI; +using EventStore.ClientAPI.SystemData; +using Newtonsoft.Json; + +namespace EventSourcing.Demo +{ + public class WarehouseProductEventStoreStream : IDisposable + { + private readonly IEventStoreConnection _connection; + + public static async Task Factory() + { + var connectionSettings = ConnectionSettings.Create() + .KeepReconnecting() + .KeepRetrying() + .SetHeartbeatTimeout(TimeSpan.FromMinutes(5)) + .SetHeartbeatInterval(TimeSpan.FromMinutes(1)) + .DisableTls() + .DisableServerCertificateValidation() + .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) + .Build(); + + var conn = EventStoreConnection.Create(connectionSettings, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113)); + await conn.ConnectAsync(); + + return new WarehouseProductEventStoreStream(conn); + } + + private WarehouseProductEventStoreStream(IEventStoreConnection connection) + { + _connection = connection; + } + + private string GetStreamName(string sku) + { + return $"WarehouseProduct-{sku}"; + } + + public async Task> Get(string sku) + { + var streamName = GetStreamName(sku); + + var warehouseProduct = new WarehouseProduct(sku, new WarehouseProductState()); + + StreamEventsSlice currentSlice; + long nextSliceStart = 0; + long lastVersion = -1; + do + { + currentSlice = await _connection.ReadStreamEventsForwardAsync( + streamName, + nextSliceStart, + 200, + false + ); + + nextSliceStart = currentSlice.NextEventNumber; + + foreach (var evnt in currentSlice.Events) + { + var eventObj = DeserializeEvent(evnt); + warehouseProduct.ApplyEvent(eventObj); + lastVersion = evnt.OriginalEventNumber; + } + } while (!currentSlice.IsEndOfStream); + + return new EventStreamAggregate(warehouseProduct, lastVersion); + } + + private IEvent DeserializeEvent(ResolvedEvent evnt) + { + var json = Encoding.UTF8.GetString(evnt.Event.Data); + return evnt.Event.EventType switch + { + "InventoryAdjusted" => JsonConvert.DeserializeObject(json), + "ProductShipped" => JsonConvert.DeserializeObject(json), + "ProductReceived" => JsonConvert.DeserializeObject(json), + _ => throw new InvalidOperationException($"Unknown Event: {evnt.Event.EventType}") + }; + } + + public async Task Save(WarehouseProduct warehouseProduct, long expectedVersion) + { + var streamName = GetStreamName(warehouseProduct.Sku); + + var newEvents = warehouseProduct.GetUncommittedEvents(); + foreach (var evnt in newEvents) + { + var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt)); + var metadata = Encoding.UTF8.GetBytes("{}"); + var evt = new EventData(Guid.NewGuid(), evnt.EventType, true, data, metadata); + var result = await _connection.AppendToStreamAsync(streamName, expectedVersion, evt); + expectedVersion = result.NextExpectedVersion; + } + } + + public void Dispose() + { + _connection?.Dispose(); + } + } + + public class EventStreamAggregate + { + public EventStreamAggregate(T aggregate, long version) + { + Aggregate = aggregate; + Version = version; + } + + public T Aggregate { get; private set; } + public long Version { get; private set; } + } +} \ No newline at end of file diff --git a/eventstore/appsettings.Development.json b/eventstore/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/eventstore/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/eventstore/appsettings.json b/eventstore/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/eventstore/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1148ecd --- /dev/null +++ b/.gitignore @@ -0,0 +1,259 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +**/wwwroot/lib/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml +pub/ +/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1 +/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1 +/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json + +#Ignore marker-file used to know which docker files we have. +.eshopdocker_* diff --git a/cosmos/Order.cs b/cosmos/Order.cs new file mode 100644 index 0000000..2cd9e61 --- /dev/null +++ b/cosmos/Order.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +public class Order +{ + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + [JsonProperty(PropertyName = "customerId")] + public string CustomerId { get; set; } + + [JsonProperty(PropertyName = "status")] + public OrderStatus Status { get; set; } = OrderStatus.Placed; +} + +public enum OrderStatus +{ + Placed, + Processing, + Cancelled, + Shipped, +} \ No newline at end of file diff --git a/cosmos/Program.cs b/cosmos/Program.cs new file mode 100644 index 0000000..d44225e --- /dev/null +++ b/cosmos/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Azure.Cosmos; + +using var client = new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); +var container = client.GetContainer("demo", "orders"); +var newOrder = new Order +{ + Id = Guid.NewGuid().ToString(), + CustomerId = "CodeOpinion" +}; + +await container.CreateItemAsync(newOrder, new PartitionKey(newOrder.Id)); + +var readOrder = await container.ReadItemAsync(newOrder.Id, new PartitionKey(newOrder.Id)); +readOrder.Resource.Status = OrderStatus.Processing; + +// Works because ETag is correct +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + +// Fails because ETag was changed when Upsert occured above. +await container.UpsertItemAsync(readOrder.Resource, new PartitionKey(readOrder.Resource.Id), new ItemRequestOptions +{ + IfMatchEtag = readOrder.ETag, +}); + diff --git a/cosmos/Properties/launchSettings.json b/cosmos/Properties/launchSettings.json new file mode 100644 index 0000000..8072997 --- /dev/null +++ b/cosmos/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13219", + "sslPort": 44347 + } + }, + "profiles": { + "cosmos": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7162;http://localhost:5153", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cosmos/appsettings.Development.json b/cosmos/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cosmos/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/cosmos/appsettings.json b/cosmos/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/cosmos/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/cosmos/cosmos.csproj b/cosmos/cosmos.csproj new file mode 100644 index 0000000..3fcccbd --- /dev/null +++ b/cosmos/cosmos.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/eventstore/Events.cs b/eventstore/Events.cs new file mode 100644 index 0000000..d1d4501 --- /dev/null +++ b/eventstore/Events.cs @@ -0,0 +1,22 @@ +namespace EventSourcing.Demo +{ + public interface IEvent + { + string EventType { get; } + } + + public record ProductShipped(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductShipped"; + } + + public record ProductReceived(string Sku, int Quantity, DateTime DateTime) : IEvent + { + public string EventType { get; } = "ProductReceived"; + } + + public record InventoryAdjusted(string Sku, int Quantity, string Reason, DateTime DateTime) : IEvent + { + public string EventType { get; } = "InventoryAdjusted"; + } +} \ No newline at end of file diff --git a/eventstore/Program.cs b/eventstore/Program.cs new file mode 100644 index 0000000..5999ac1 --- /dev/null +++ b/eventstore/Program.cs @@ -0,0 +1,99 @@ +using EventSourcing.Demo; +using EventStore.ClientAPI.Exceptions; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/products/{sku}", async (HttpResponse response, string sku) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + //response.Headers.ETag = product.Version.ToString(); + + return new + { + Sku = product.Aggregate.Sku, + Quantity = product.Aggregate.GetQuantityOnHand(), + Version = product.Version, + Commands = new Command[] + { + new("InventoryAdjustment", $"/products/{sku}/{product.Version}/adjustment") + } + }; +}); + +app.MapPost("/products/{sku}/adjustment", async (HttpRequest request, HttpResponse response, [FromRoute]string sku, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + + var eTag = request.GetIfMatch(); + if (eTag != null) + { + try + { + await stream.Save(product.Aggregate, eTag.Value); + response.StatusCode = 204; + return; + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } + } + + response.StatusCode = 412; +}); + +app.MapPost("/products/{sku}/{version}/adjustment", + async (HttpResponse response, [FromRoute]string sku, [FromRoute]long version, [FromBody]InventoryAdjustment inventoryAdjustment) => +{ + using var stream = await WarehouseProductEventStoreStream.Factory(); + var product = await stream.Get(sku); + product.Aggregate.AdjustInventory(inventoryAdjustment.Quantity, inventoryAdjustment.Reason); + try + { + await stream.Save(product.Aggregate, version); + } + catch (WrongExpectedVersionException) + { + response.StatusCode = 412; + } +}); + +app.Run(); + +public class InventoryAdjustment +{ + public int Quantity { get; set; } + public string Reason { get; set; } +} + +public static class Extensions +{ + public static long? GetIfMatch(this HttpRequest request) + { + var headers = request.GetTypedHeaders(); + var eTag = headers.IfMatch.FirstOrDefault()?.Tag.Value.Replace("\"", ""); + if (eTag != null && long.TryParse(eTag, out var version)) + { + return version; + } + + return null; + } +} + +public class Command +{ + public Command(string action, string uri) + { + Action = action; + Uri = uri; + } + + public string Action { get; set; } + public string Uri { get; set; } +} diff --git a/eventstore/Properties/launchSettings.json b/eventstore/Properties/launchSettings.json new file mode 100644 index 0000000..98b2753 --- /dev/null +++ b/eventstore/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59639", + "sslPort": 44373 + } + }, + "profiles": { + "eventstore": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7145;http://localhost:5215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/eventstore/WarehouseProduct.cs b/eventstore/WarehouseProduct.cs new file mode 100644 index 0000000..44bd429 --- /dev/null +++ b/eventstore/WarehouseProduct.cs @@ -0,0 +1,122 @@ +namespace EventSourcing.Demo +{ + public class WarehouseProductState + { + public int QuantityOnHand { get; set; } + } + + public class WarehouseProduct + { + public string Sku { get; } + private readonly IList _allEvents = new List(); + private readonly IList _uncommittedEvents = new List(); + + // Projection (Current State) + private readonly WarehouseProductState _warehouseProductState; + + public WarehouseProduct(string sku, WarehouseProductState state) + { + Sku = sku; + _warehouseProductState = state; + } + + public WarehouseProductState GetState() + { + return _warehouseProductState; + } + + public void ShipProduct(int quantity) + { + if (quantity > _warehouseProductState.QuantityOnHand) + { + throw new InvalidDomainException("Ah... we don't have enough product to ship?"); + } + + AddEvent(new ProductShipped(Sku, quantity, DateTime.UtcNow)); + } + + public void ReceiveProduct(int quantity) + { + AddEvent(new ProductReceived(Sku, quantity, DateTime.UtcNow)); + } + + public void AdjustInventory(int quantity, string reason) + { + if (_warehouseProductState.QuantityOnHand + quantity < 0) + { + throw new InvalidDomainException("Cannot adjust to a negative quantity on hand."); + } + + AddEvent(new InventoryAdjusted(Sku, quantity, reason, DateTime.UtcNow)); + } + + private void Apply(ProductShipped evnt) + { + _warehouseProductState.QuantityOnHand -= evnt.Quantity; + } + + private void Apply(ProductReceived evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + private void Apply(InventoryAdjusted evnt) + { + _warehouseProductState.QuantityOnHand += evnt.Quantity; + } + + public void ApplyEvent(IEvent evnt) + { + switch (evnt) + { + case ProductShipped shipProduct: + Apply(shipProduct); + break; + case ProductReceived receiveProduct: + Apply(receiveProduct); + break; + case InventoryAdjusted inventoryAdjusted: + Apply(inventoryAdjusted); + break; + default: + throw new InvalidOperationException("Unsupported Event."); + } + + _allEvents.Add(evnt); + } + + private void AddEvent(IEvent evnt) + { + ApplyEvent(evnt); + _uncommittedEvents.Add(evnt); + } + + public IList GetUncommittedEvents() + { + return new List(_uncommittedEvents); + } + + public IList GetAllEvents() + { + return new List(_allEvents); + } + + public void EventsCommitted() + { + _uncommittedEvents.Clear(); + } + + public int GetQuantityOnHand() + { + return _warehouseProductState.QuantityOnHand; + } + } + + public class InvalidDomainException : Exception + { + public InvalidDomainException(string message) : base(message) + { + + } + } +} \ No newline at end of file diff --git a/eventstore/WarehouseProductEventStoreStream.cs b/eventstore/WarehouseProductEventStoreStream.cs new file mode 100644 index 0000000..8607aea --- /dev/null +++ b/eventstore/WarehouseProductEventStoreStream.cs @@ -0,0 +1,116 @@ +using System.Net; +using System.Text; +using EventStore.ClientAPI; +using EventStore.ClientAPI.SystemData; +using Newtonsoft.Json; + +namespace EventSourcing.Demo +{ + public class WarehouseProductEventStoreStream : IDisposable + { + private readonly IEventStoreConnection _connection; + + public static async Task Factory() + { + var connectionSettings = ConnectionSettings.Create() + .KeepReconnecting() + .KeepRetrying() + .SetHeartbeatTimeout(TimeSpan.FromMinutes(5)) + .SetHeartbeatInterval(TimeSpan.FromMinutes(1)) + .DisableTls() + .DisableServerCertificateValidation() + .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) + .Build(); + + var conn = EventStoreConnection.Create(connectionSettings, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113)); + await conn.ConnectAsync(); + + return new WarehouseProductEventStoreStream(conn); + } + + private WarehouseProductEventStoreStream(IEventStoreConnection connection) + { + _connection = connection; + } + + private string GetStreamName(string sku) + { + return $"WarehouseProduct-{sku}"; + } + + public async Task> Get(string sku) + { + var streamName = GetStreamName(sku); + + var warehouseProduct = new WarehouseProduct(sku, new WarehouseProductState()); + + StreamEventsSlice currentSlice; + long nextSliceStart = 0; + long lastVersion = -1; + do + { + currentSlice = await _connection.ReadStreamEventsForwardAsync( + streamName, + nextSliceStart, + 200, + false + ); + + nextSliceStart = currentSlice.NextEventNumber; + + foreach (var evnt in currentSlice.Events) + { + var eventObj = DeserializeEvent(evnt); + warehouseProduct.ApplyEvent(eventObj); + lastVersion = evnt.OriginalEventNumber; + } + } while (!currentSlice.IsEndOfStream); + + return new EventStreamAggregate(warehouseProduct, lastVersion); + } + + private IEvent DeserializeEvent(ResolvedEvent evnt) + { + var json = Encoding.UTF8.GetString(evnt.Event.Data); + return evnt.Event.EventType switch + { + "InventoryAdjusted" => JsonConvert.DeserializeObject(json), + "ProductShipped" => JsonConvert.DeserializeObject(json), + "ProductReceived" => JsonConvert.DeserializeObject(json), + _ => throw new InvalidOperationException($"Unknown Event: {evnt.Event.EventType}") + }; + } + + public async Task Save(WarehouseProduct warehouseProduct, long expectedVersion) + { + var streamName = GetStreamName(warehouseProduct.Sku); + + var newEvents = warehouseProduct.GetUncommittedEvents(); + foreach (var evnt in newEvents) + { + var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt)); + var metadata = Encoding.UTF8.GetBytes("{}"); + var evt = new EventData(Guid.NewGuid(), evnt.EventType, true, data, metadata); + var result = await _connection.AppendToStreamAsync(streamName, expectedVersion, evt); + expectedVersion = result.NextExpectedVersion; + } + } + + public void Dispose() + { + _connection?.Dispose(); + } + } + + public class EventStreamAggregate + { + public EventStreamAggregate(T aggregate, long version) + { + Aggregate = aggregate; + Version = version; + } + + public T Aggregate { get; private set; } + public long Version { get; private set; } + } +} \ No newline at end of file diff --git a/eventstore/appsettings.Development.json b/eventstore/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/eventstore/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/eventstore/appsettings.json b/eventstore/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/eventstore/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/eventstore/eventstore.csproj b/eventstore/eventstore.csproj new file mode 100644 index 0000000..fcea299 --- /dev/null +++ b/eventstore/eventstore.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + +