├── .dockerignore ├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── deploy.yml ├── .gitignore ├── Azure ├── container_app.bicep ├── container_app_no_ingress.bicep ├── environment.bicep └── main.bicep ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Frontend ├── App.razor ├── Dockerfile ├── Frontend.csproj ├── Frontend.sln ├── Pages │ ├── Counter.razor │ ├── Error.cshtml │ ├── Error.cshtml.cs │ ├── Index.razor │ ├── _Host.cshtml │ └── _Layout.cshtml ├── Program.cs ├── Properties │ └── launchSettings.json ├── Shared │ ├── MainLayout.razor │ └── NavMenu.razor ├── _Imports.razor ├── appsettings.Development.json ├── appsettings.json └── wwwroot │ └── favicon.ico ├── LICENSE.md ├── Monitoring ├── ApplicationMapNodeNameInitializer.cs └── Monitoring.csproj ├── README.md ├── SensorApp.sln ├── SensorService ├── Dockerfile ├── Program.cs ├── Properties │ └── launchSettings.json ├── Protos │ └── sensor.proto ├── SensorService.csproj ├── Services │ └── SensorTwinService.cs ├── appsettings.Development.json └── appsettings.json ├── SensorWorker ├── Dockerfile ├── Program.cs ├── Properties │ └── launchSettings.json ├── SensorWorker.csproj ├── Worker.cs ├── appsettings.Development.json └── appsettings.json └── docs └── media ├── app-front-end.png ├── appmap.png ├── create-the-deployment-branch.png ├── deployed-to-azure.png ├── deployment-phases.png ├── deployment-started.png ├── deployment-success.png ├── edit-the-deploy-file.png ├── front-end.png ├── logs.png ├── new-revision.png ├── new-sensor-workers.png ├── revision-management.png ├── secrets.png └── toplogy.png /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] feature request 11 | - [ ] documentation issue or request 12 | - [ ] regression (a behavior that used to work and stopped in a new release) 13 | ``` 14 | 15 | ### Minimal steps to reproduce 16 | > 17 | 18 | ### Any log messages given by the failure 19 | > 20 | 21 | ### Expected/desired behavior 22 | > 23 | 24 | ### OS and Version? 25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) 26 | 27 | ### Versions 28 | > 29 | 30 | ### Mention any other details that might be useful 31 | 32 | > --------------------------------------------------------------- 33 | > Thanks! We'll be in touch soon. 34 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Build and deploy .NET application to Container App silo 2 | 3 | on: 4 | push: 5 | branches: 6 | - deploy 7 | 8 | env: 9 | 10 | # alphanumeric string under 14 characters 11 | RESOURCE_GROUP_NAME: grpconaca 12 | 13 | # specify your preferred region 14 | REGION: eastus 15 | 16 | FRONTEND_DOCKER: Frontend/Dockerfile 17 | FRONTEND_IMAGE: frontend 18 | 19 | WORKER_DOCKER: SensorWorker/Dockerfile 20 | WORKER_IMAGE: worker 21 | 22 | SERVICE_DOCKER: SensorService/Dockerfile 23 | SERVICE_IMAGE: service 24 | 25 | jobs: 26 | provision: 27 | runs-on: ubuntu-latest 28 | 29 | steps: 30 | 31 | - name: Checkout to the branch 32 | uses: actions/checkout@v2 33 | 34 | - name: Azure Login 35 | uses: azure/login@v1 36 | with: 37 | creds: ${{ secrets.AzureSPN }} 38 | 39 | - name: Create resource group 40 | uses: azure/CLI@v1 41 | with: 42 | inlineScript: > 43 | echo "Creating resource group in Azure" 44 | echo "Executing 'az group create -l ${{ env.REGION }} -n ${{ env.RESOURCE_GROUP_NAME }}'" 45 | 46 | az group create -l ${{ env.REGION }} -n ${{ env.RESOURCE_GROUP_NAME }} 47 | 48 | - name: Creating resources 49 | uses: azure/CLI@v1 50 | with: 51 | inlineScript: > 52 | echo "Creating resources" 53 | 54 | az deployment group create --resource-group ${{ env.RESOURCE_GROUP_NAME }} --template-file '/github/workspace/Azure/main.bicep' --debug 55 | 56 | build: 57 | runs-on: ubuntu-latest 58 | needs: provision 59 | 60 | steps: 61 | 62 | - name: Checkout to the branch 63 | uses: actions/checkout@v2 64 | 65 | - name: Azure Login 66 | uses: azure/login@v1 67 | with: 68 | creds: ${{ secrets.AzureSPN }} 69 | 70 | - name: Set up Docker Buildx 71 | uses: docker/setup-buildx-action@v1 72 | 73 | - name: Login to ACR 74 | run: | 75 | set -euo pipefail 76 | access_token=$(az account get-access-token --query accessToken -o tsv) 77 | refresh_token=$(curl https://${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/oauth2/exchange -v -d "grant_type=access_token&service=${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io&access_token=$access_token" | jq -r .refresh_token) 78 | docker login -u 00000000-0000-0000-0000-000000000000 --password-stdin ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io <<< "$refresh_token" 79 | 80 | - name: Build the service image and push it to ACR 81 | uses: docker/build-push-action@v2 82 | with: 83 | push: true 84 | tags: ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/${{ env.SERVICE_IMAGE }}:${{ github.sha }} 85 | file: ${{ env.SERVICE_DOCKER }} 86 | 87 | - name: Build the front end image and push it to ACR 88 | uses: docker/build-push-action@v2 89 | with: 90 | push: true 91 | tags: ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/${{ env.FRONTEND_IMAGE }}:${{ github.sha }} 92 | file: ${{ env.FRONTEND_DOCKER }} 93 | 94 | - name: Build the worker image and push it to ACR 95 | uses: docker/build-push-action@v2 96 | with: 97 | push: true 98 | tags: ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/${{ env.WORKER_IMAGE }}:${{ github.sha }} 99 | file: ${{ env.WORKER_DOCKER }} 100 | 101 | deploy: 102 | runs-on: ubuntu-latest 103 | needs: build 104 | 105 | steps: 106 | 107 | - name: Checkout to the branch 108 | uses: actions/checkout@v2 109 | 110 | - name: Azure Login 111 | uses: azure/login@v1 112 | with: 113 | creds: ${{ secrets.AzureSPN }} 114 | 115 | - name: Installing Container Apps extension 116 | uses: azure/CLI@v1 117 | with: 118 | inlineScript: > 119 | az config set extension.use_dynamic_install=yes_without_prompt 120 | 121 | az extension add --name containerapp --yes 122 | 123 | - name: Login to ACR 124 | run: | 125 | set -euo pipefail 126 | access_token=$(az account get-access-token --query accessToken -o tsv) 127 | refresh_token=$(curl https://${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/oauth2/exchange -v -d "grant_type=access_token&service=${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io&access_token=$access_token" | jq -r .refresh_token) 128 | docker login -u 00000000-0000-0000-0000-000000000000 --password-stdin ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io <<< "$refresh_token" 129 | 130 | - name: Deploy Container Apps 131 | uses: azure/CLI@v1 132 | with: 133 | inlineScript: > 134 | az containerapp registry set -n service -g ${{ env.RESOURCE_GROUP_NAME }} --server ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io 135 | 136 | az containerapp update -n service -g ${{ env.RESOURCE_GROUP_NAME }} -i ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/${{ env.SERVICE_IMAGE }}:${{ github.sha }} 137 | 138 | az containerapp registry set -n frontend -g ${{ env.RESOURCE_GROUP_NAME }} --server ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io 139 | 140 | az containerapp update -n frontend -g ${{ env.RESOURCE_GROUP_NAME }} -i ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/${{ env.FRONTEND_IMAGE }}:${{ github.sha }} 141 | 142 | az containerapp registry set -n worker -g ${{ env.RESOURCE_GROUP_NAME }} --server ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io 143 | 144 | az containerapp update -n worker -g ${{ env.RESOURCE_GROUP_NAME }} -i ${{ env.RESOURCE_GROUP_NAME }}acr.azurecr.io/${{ env.WORKER_IMAGE }}:${{ github.sha }} 145 | 146 | - name: logout 147 | run: > 148 | az logout 149 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /Azure/container_app.bicep: -------------------------------------------------------------------------------- 1 | param name string 2 | param location string = resourceGroup().location 3 | param containerAppEnvironmentId string 4 | param repositoryImage string = 'mcr.microsoft.com/azuredocs/containerapps-helloworld:latest' 5 | param envVars array = [] 6 | param registry string 7 | param minReplicas int = 1 8 | param maxReplicas int = 1 9 | param port int = 80 10 | param externalIngress bool = false 11 | param allowInsecure bool = true 12 | param transport string = 'http' 13 | param registryUsername string 14 | @secure() 15 | param registryPassword string 16 | 17 | resource containerApp 'Microsoft.App/containerApps@2022-01-01-preview' ={ 18 | name: name 19 | location: location 20 | properties:{ 21 | managedEnvironmentId: containerAppEnvironmentId 22 | configuration: { 23 | activeRevisionsMode: 'single' 24 | secrets: [ 25 | { 26 | name: 'container-registry-password' 27 | value: registryPassword 28 | } 29 | ] 30 | registries: [ 31 | { 32 | server: registry 33 | username: registryUsername 34 | passwordSecretRef: 'container-registry-password' 35 | } 36 | ] 37 | ingress: { 38 | external: externalIngress 39 | targetPort: port 40 | transport: transport 41 | allowInsecure: allowInsecure 42 | } 43 | } 44 | template: { 45 | containers: [ 46 | { 47 | image: repositoryImage 48 | name: name 49 | env: envVars 50 | } 51 | ] 52 | scale: { 53 | minReplicas: minReplicas 54 | maxReplicas: maxReplicas 55 | } 56 | } 57 | } 58 | } 59 | 60 | output fqdn string = containerApp.properties.configuration.ingress.fqdn 61 | -------------------------------------------------------------------------------- /Azure/container_app_no_ingress.bicep: -------------------------------------------------------------------------------- 1 | param name string 2 | param location string = resourceGroup().location 3 | param containerAppEnvironmentId string 4 | param repositoryImage string = 'mcr.microsoft.com/azuredocs/containerapps-helloworld:latest' 5 | param envVars array = [] 6 | param registry string 7 | param minReplicas int = 1 8 | param maxReplicas int = 1 9 | param registryUsername string 10 | @secure() 11 | param registryPassword string 12 | 13 | resource containerApp 'Microsoft.App/containerApps@2022-01-01-preview' ={ 14 | name: name 15 | location: location 16 | properties:{ 17 | managedEnvironmentId: containerAppEnvironmentId 18 | configuration: { 19 | activeRevisionsMode: 'multiple' 20 | secrets: [ 21 | { 22 | name: 'container-registry-password' 23 | value: registryPassword 24 | } 25 | ] 26 | registries: [ 27 | { 28 | server: registry 29 | username: registryUsername 30 | passwordSecretRef: 'container-registry-password' 31 | } 32 | ] 33 | } 34 | template: { 35 | containers: [ 36 | { 37 | image: repositoryImage 38 | name: name 39 | env: envVars 40 | } 41 | ] 42 | scale: { 43 | minReplicas: minReplicas 44 | maxReplicas: maxReplicas 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Azure/environment.bicep: -------------------------------------------------------------------------------- 1 | param baseName string = resourceGroup().name 2 | param location string = resourceGroup().location 3 | 4 | resource logs 'Microsoft.OperationalInsights/workspaces@2021-06-01' = { 5 | name: '${baseName}logs' 6 | location: location 7 | properties: any({ 8 | retentionInDays: 30 9 | features: { 10 | searchVersion: 1 11 | } 12 | sku: { 13 | name: 'PerGB2018' 14 | } 15 | }) 16 | } 17 | 18 | resource appInsights 'Microsoft.Insights/components@2020-02-02' = { 19 | name: '${baseName}ai' 20 | location: location 21 | kind: 'web' 22 | properties: { 23 | Application_Type: 'web' 24 | WorkspaceResourceId: logs.id 25 | } 26 | } 27 | 28 | resource env 'Microsoft.App/managedEnvironments@2022-01-01-preview' = { 29 | name: '${baseName}env' 30 | location: location 31 | properties: { 32 | appLogsConfiguration: { 33 | destination: 'log-analytics' 34 | logAnalyticsConfiguration: { 35 | customerId: logs.properties.customerId 36 | sharedKey: logs.listKeys().primarySharedKey 37 | } 38 | } 39 | } 40 | } 41 | 42 | output id string = env.id 43 | output appInsightsInstrumentationKey string = appInsights.properties.InstrumentationKey 44 | output appInsightsConnectionString string = appInsights.properties.ConnectionString 45 | -------------------------------------------------------------------------------- /Azure/main.bicep: -------------------------------------------------------------------------------- 1 | param location string = resourceGroup().location 2 | 3 | // create the azure container registry 4 | resource acr 'Microsoft.ContainerRegistry/registries@2021-09-01' = { 5 | name: toLower('${resourceGroup().name}acr') 6 | location: location 7 | sku: { 8 | name: 'Basic' 9 | } 10 | properties: { 11 | adminUserEnabled: true 12 | } 13 | } 14 | 15 | // create the aca environment 16 | module env 'environment.bicep' = { 17 | name: 'containerAppEnvironment' 18 | params: { 19 | location: location 20 | } 21 | } 22 | 23 | // create the various config pairs 24 | var shared_config = [ 25 | { 26 | name: 'ASPNETCORE_ENVIRONMENT' 27 | value: 'Development' 28 | } 29 | { 30 | name: 'APPINSIGHTS_INSTRUMENTATIONKEY' 31 | value: env.outputs.appInsightsInstrumentationKey 32 | } 33 | { 34 | name: 'APPLICATIONINSIGHTS_CONNECTION_STRING' 35 | value: env.outputs.appInsightsConnectionString 36 | } 37 | ] 38 | 39 | // create the client config pairs 40 | var client_config = [ 41 | { 42 | name: 'SERVICE_ENDPOINT' 43 | value: 'http://${service.outputs.fqdn}' 44 | } 45 | ] 46 | 47 | // create the service container app 48 | module service 'container_app.bicep' = { 49 | name: 'service' 50 | params: { 51 | name: 'service' 52 | location: location 53 | registryPassword: acr.listCredentials().passwords[0].value 54 | registryUsername: acr.listCredentials().username 55 | containerAppEnvironmentId: env.outputs.id 56 | registry: acr.name 57 | envVars: shared_config 58 | externalIngress: false 59 | transport: 'http2' 60 | } 61 | } 62 | 63 | // create the worker container app 64 | module worker 'container_app_no_ingress.bicep' = { 65 | name: 'worker' 66 | params: { 67 | name: 'worker' 68 | location: location 69 | registryPassword: acr.listCredentials().passwords[0].value 70 | registryUsername: acr.listCredentials().username 71 | containerAppEnvironmentId: env.outputs.id 72 | registry: acr.name 73 | envVars: union(shared_config, client_config) 74 | } 75 | } 76 | 77 | // create the frontend container app 78 | module frontend 'container_app.bicep' = { 79 | name: 'frontend' 80 | params: { 81 | name: 'frontend' 82 | location: location 83 | registryPassword: acr.listCredentials().passwords[0].value 84 | registryUsername: acr.listCredentials().username 85 | containerAppEnvironmentId: env.outputs.id 86 | registry: acr.name 87 | envVars: union(shared_config, client_config) 88 | externalIngress: true 89 | } 90 | } 91 | 92 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [project-title] Changelog 2 | 3 | 4 | # x.y.z (yyyy-mm-dd) 5 | 6 | *Features* 7 | * ... 8 | 9 | *Bug Fixes* 10 | * ... 11 | 12 | *Breaking Changes* 13 | * ... 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [project-title] 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 5 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. 6 | 7 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide 8 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 9 | provided by the bot. You will only need to do this once across all repos using our CLA. 10 | 11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 14 | 15 | - [Code of Conduct](#coc) 16 | - [Issues and Bugs](#issue) 17 | - [Feature Requests](#feature) 18 | - [Submission Guidelines](#submit) 19 | 20 | ## Code of Conduct 21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 22 | 23 | ## Found an Issue? 24 | If you find a bug in the source code or a mistake in the documentation, you can help us by 25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can 26 | [submit a Pull Request](#submit-pr) with a fix. 27 | 28 | ## Want a Feature? 29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub 30 | Repository. If you would like to *implement* a new feature, please submit an issue with 31 | a proposal for your work first, to be sure that we can use it. 32 | 33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). 34 | 35 | ## Submission Guidelines 36 | 37 | ### Submitting an Issue 38 | Before you submit an issue, search the archive, maybe your question was already answered. 39 | 40 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 41 | Help us to maximize the effort we can spend fixing issues and adding new 42 | features, by not reporting duplicate issues. Providing the following information will increase the 43 | chances of your issue being dealt with quickly: 44 | 45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps 46 | * **Version** - what version is affected (e.g. 0.1.2) 47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you 48 | * **Browsers and Operating System** - is this a problem with all browsers? 49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps 50 | * **Related Issues** - has a similar issue been reported before? 51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be 52 | causing the problem (line of code or commit) 53 | 54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. 55 | 56 | ### Submitting a Pull Request (PR) 57 | Before you submit your Pull Request (PR) consider the following guidelines: 58 | 59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR 60 | that relates to your submission. You don't want to duplicate effort. 61 | 62 | * Make your changes in a new git fork: 63 | 64 | * Commit your changes using a descriptive commit message 65 | * Push your fork to GitHub: 66 | * In GitHub, create a pull request 67 | * If we suggest changes then: 68 | * Make the required updates. 69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): 70 | 71 | ```shell 72 | git rebase master -i 73 | git push -f 74 | ``` 75 | 76 | That's it! Thank you for your contribution! 77 | -------------------------------------------------------------------------------- /Frontend/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | Not found 7 | 8 |

Sorry, there's nothing at this address.

9 |
10 |
11 |
-------------------------------------------------------------------------------- /Frontend/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | EXPOSE 443 7 | 8 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 9 | WORKDIR /src 10 | COPY ["Frontend/Frontend.csproj", "Frontend/"] 11 | COPY ["Monitoring/Monitoring.csproj", "Monitoring/"] 12 | RUN dotnet restore "Frontend/Frontend.csproj" 13 | COPY . . 14 | WORKDIR "/src/Frontend" 15 | RUN dotnet build "Frontend.csproj" -c Release -o /app/build 16 | 17 | FROM build AS publish 18 | RUN dotnet publish "Frontend.csproj" -c Release -o /app/publish 19 | 20 | FROM base AS final 21 | WORKDIR /app 22 | COPY --from=publish /app/publish . 23 | ENTRYPOINT ["dotnet", "Frontend.dll"] -------------------------------------------------------------------------------- /Frontend/Frontend.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | e9487957-8907-4473-9313-362f29e99775 8 | Linux 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Protos\sensor.proto 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Frontend/Frontend.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31717.71 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Frontend", "Frontend.csproj", "{8AB17BA2-9AA8-495E-8663-B5A51CE2F0D4}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {8AB17BA2-9AA8-495E-8663-B5A51CE2F0D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8AB17BA2-9AA8-495E-8663-B5A51CE2F0D4}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8AB17BA2-9AA8-495E-8663-B5A51CE2F0D4}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8AB17BA2-9AA8-495E-8663-B5A51CE2F0D4}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {CC35D6B1-28DD-44F8-BF4B-D3A7718F810D} 24 | EndGlobalSection 25 | EndGlobal -------------------------------------------------------------------------------- /Frontend/Pages/Counter.razor: -------------------------------------------------------------------------------- 1 | @page "/counter" 2 | 3 | Counter 4 | 5 | Counter 6 | Current count: @currentCount 7 | Click me 8 | 9 | 10 | @code { 11 | private int currentCount = 0; 12 | 13 | private void IncrementCount() 14 | { 15 | currentCount++; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Frontend/Pages/Error.cshtml: -------------------------------------------------------------------------------- 1 | @page 2 | @model Frontend.Pages.ErrorModel 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Error 11 | 12 | 13 | 14 | 15 | 16 |
17 |
18 |

Error.

19 |

An error occurred while processing your request.

20 | 21 | @if (Model.ShowRequestId) 22 | { 23 |

24 | Request ID: @Model.RequestId 25 |

26 | } 27 | 28 |

Development Mode

29 |

30 | Swapping to the Development environment displays detailed information about the error that occurred. 31 |

32 |

33 | The Development environment shouldn't be enabled for deployed applications. 34 | It can result in displaying sensitive information from exceptions to end users. 35 | For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development 36 | and restarting the app. 37 |

38 |
39 |
40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Frontend/Pages/Error.cshtml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.RazorPages; 3 | using System.Diagnostics; 4 | 5 | namespace Frontend.Pages 6 | { 7 | [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 8 | [IgnoreAntiforgeryToken] 9 | public class ErrorModel : PageModel 10 | { 11 | public string? RequestId { get; set; } 12 | 13 | public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); 14 | 15 | private readonly ILogger _logger; 16 | 17 | public ErrorModel(ILogger logger) 18 | { 19 | _logger = logger; 20 | } 21 | 22 | public void OnGet() 23 | { 24 | RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Frontend/Pages/Index.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | @using Google.Protobuf.WellKnownTypes 3 | @using Grpc.Core 4 | @using Sensors 5 | @inject IConfiguration Configuration; 6 | 7 | Index 8 | 9 | 10 | @foreach (var sensorValue in SensorValues) 11 | { 12 | if (sensorValue.Series.First().Data.Length > 4) 13 | { 14 | 15 | 16 | 17 | } 18 | } 19 | 20 | 21 | @code 22 | { 23 | private ChartOptions options = new ChartOptions(); 24 | 25 | public record SensorValue(string Sensor) 26 | { 27 | public List Values { get; set; } = new List(); 28 | public List Series = new List(); 29 | } 30 | 31 | private List SensorValues { get; set; } = new List(); 32 | 33 | protected override void OnInitialized() 34 | { 35 | options.InterpolationOption = InterpolationOption.NaturalSpline; 36 | } 37 | 38 | protected override async Task OnAfterRenderAsync(bool firstRender) 39 | { 40 | if (firstRender) 41 | { 42 | var sensorTwinClient = new Sensors.SensorTwin.SensorTwinClient(Grpc.Net.Client.GrpcChannel.ForAddress(Configuration.GetValue("SERVICE_ENDPOINT"))); 43 | using var streamingResults = sensorTwinClient.GetDeviceTwinStream(new Empty()); 44 | try 45 | { 46 | await foreach (var result in streamingResults.ResponseStream.ReadAllAsync()) 47 | { 48 | if (SensorValues.Any(x => x.Sensor == result.Sensor)) 49 | { 50 | var values = SensorValues.First(x => x.Sensor == result.Sensor).Values; 51 | if (values.Count >= 100) 52 | { 53 | values.RemoveAt(0); 54 | } 55 | SensorValues.First(x => x.Sensor == result.Sensor).Values.Add(result.Value); 56 | SensorValues.First(x => x.Sensor == result.Sensor).Series.First(x => x.Name == result.Sensor).Data = 57 | SensorValues.First(x => x.Sensor == result.Sensor).Values.ToArray(); 58 | } 59 | else 60 | { 61 | var newSensor = new SensorValue(result.Sensor); 62 | newSensor.Values.Add(result.Value); 63 | newSensor.Series.Add(new ChartSeries 64 | { 65 | Name = result.Sensor, 66 | Data = newSensor.Values.ToArray() 67 | }); 68 | SensorValues.Add(newSensor); 69 | } 70 | 71 | StateHasChanged(); 72 | } 73 | } 74 | catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled) 75 | { 76 | Console.WriteLine("Stream cancelled."); 77 | } 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /Frontend/Pages/_Host.cshtml: -------------------------------------------------------------------------------- 1 | @page "/" 2 | @namespace Frontend.Pages 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | @{ 5 | Layout = "_Layout"; 6 | } 7 | 8 | -------------------------------------------------------------------------------- /Frontend/Pages/_Layout.cshtml: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Components.Web 2 | @namespace Frontend.Pages 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | @RenderBody() 17 | 18 |
19 | 20 | An error has occurred. This application may no longer respond until reloaded. 21 | 22 | 23 | An unhandled exception has occurred. See browser dev tools for details. 24 | 25 | Reload 26 | 🗙 27 |
28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Frontend/Program.cs: -------------------------------------------------------------------------------- 1 | using MudBlazor.Services; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | builder.Services.AddRazorPages(); 7 | builder.Services.AddServerSideBlazor(); 8 | builder.Services.AddMudServices(); 9 | builder.Services.AddWebApplicationMonitoring(); 10 | 11 | var app = builder.Build(); 12 | 13 | // Configure the HTTP request pipeline. 14 | if (!app.Environment.IsDevelopment()) 15 | { 16 | app.UseExceptionHandler("/Error"); 17 | app.UseHsts(); 18 | } 19 | 20 | app.UseHttpsRedirection(); 21 | app.UseStaticFiles(); 22 | app.UseRouting(); 23 | app.MapBlazorHub(); 24 | app.MapFallbackToPage("/_Host"); 25 | 26 | app.Run(); -------------------------------------------------------------------------------- /Frontend/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:61949", 7 | "sslPort": 44393 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "Frontend": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "environmentVariables": { 22 | "ASPNETCORE_ENVIRONMENT": "Development" 23 | }, 24 | "applicationUrl": "http://localhost:5002;https://localhost:5003", 25 | "dotnetRunMessages": true 26 | }, 27 | "Docker": { 28 | "commandName": "Docker", 29 | "launchBrowser": true, 30 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", 31 | "publishAllPorts": true, 32 | "useSSL": true 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Frontend/Shared/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Sensor Readings 10 | 11 | 12 | 13 | 14 | @Body 15 | 16 | 17 | 18 | 19 | @code { 20 | bool _drawerOpen = true; 21 | 22 | void DrawerToggle() 23 | { 24 | _drawerOpen = !_drawerOpen; 25 | } 26 | } -------------------------------------------------------------------------------- /Frontend/Shared/NavMenu.razor: -------------------------------------------------------------------------------- 1 |  2 | Home 3 | -------------------------------------------------------------------------------- /Frontend/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using Microsoft.AspNetCore.Authorization 3 | @using Microsoft.AspNetCore.Components.Authorization 4 | @using Microsoft.AspNetCore.Components.Forms 5 | @using Microsoft.AspNetCore.Components.Routing 6 | @using Microsoft.AspNetCore.Components.Web 7 | @using Microsoft.AspNetCore.Components.Web.Virtualization 8 | @using Microsoft.JSInterop 9 | @using MudBlazor 10 | @using Frontend 11 | @using Frontend.Shared 12 | -------------------------------------------------------------------------------- /Frontend/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "DetailedErrors": true, 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Information", 6 | "Microsoft": "Warning", 7 | "Microsoft.Hosting.Lifetime": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Frontend/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Console": { 3 | "DisableColors": true 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft": "Warning", 9 | "Microsoft.Hosting.Lifetime": "Information" 10 | } 11 | }, 12 | "AllowedHosts": "*", 13 | "ApplicationMapNodeName": "Frontend", 14 | "SERVICE_ENDPOINT": "http://localhost:5000" 15 | } 16 | -------------------------------------------------------------------------------- /Frontend/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/Frontend/wwwroot/favicon.ico -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE -------------------------------------------------------------------------------- /Monitoring/ApplicationMapNodeNameInitializer.cs: -------------------------------------------------------------------------------- 1 | namespace Monitoring 2 | { 3 | using Microsoft.ApplicationInsights.Channel; 4 | using Microsoft.ApplicationInsights.Extensibility; 5 | using Microsoft.Extensions.Configuration; 6 | 7 | public class ApplicationMapNodeNameInitializer : ITelemetryInitializer 8 | { 9 | public ApplicationMapNodeNameInitializer(IConfiguration configuration) 10 | { 11 | Name = configuration["ApplicationMapNodeName"]; 12 | } 13 | 14 | public string Name { get; set; } 15 | 16 | public void Initialize(ITelemetry telemetry) 17 | { 18 | telemetry.Context.Cloud.RoleName = Name; 19 | } 20 | } 21 | } 22 | 23 | namespace Microsoft.Extensions.DependencyInjection 24 | { 25 | using Microsoft.ApplicationInsights.Extensibility; 26 | using Monitoring; 27 | 28 | public static class ServiceCollectionExtensions 29 | { 30 | public static void AddWebApplicationMonitoring(this IServiceCollection services) 31 | { 32 | services.AddApplicationInsightsTelemetry(); 33 | services.AddSingleton(); 34 | } 35 | 36 | public static void AddWorkerApplicationMonitoring(this IServiceCollection services) 37 | { 38 | services.AddApplicationInsightsTelemetryWorkerService(); 39 | services.AddSingleton(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Monitoring/Monitoring.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ASP.NET gRPC backend + Worker + Web Frontend on Azure Container Apps 2 | 3 | This repository contains a simple scenario built to demonstrate how ASP.NET Core 6.0 can be used to build a cloud-native application hosted in Azure Container Apps. The repository consists of the following projects and folders: 4 | 5 | * **Frontend** - A front-end web app written using ASP.NET Core Blazor Server. This web app opens a connection to a gRPC service that streams data to it continuously. 6 | * **Monitoring** - A shared project that makes it simple to configure a .NET project with Application Insights monitoring. 7 | * **SensorService** - A .NET gRPC service that has two features - it receives data from the workers via individual gRPC request/response communication, but also streams data to the frontend Blazor app. 8 | * **SensorWorker** - A .NET Worker Service project that continuously sends data to the `sensorservicegRPC` service inside the cluster. Think of each instance of the `SensorWorker` project as a physical device twin, like a thermometer. 9 | * You'll also see a series of Azure Bicep templates and a GitHub Actions workflow file in the **Azure** and **.github** folders, respectively. 10 | 11 | ## What you'll learn 12 | 13 | This exercise will introduce you to a variety of concepts, with links to supporting documentation throughout the tutorial. 14 | 15 | * [Azure Container Apps](https://docs.microsoft.com/azure/container-apps/overview) 16 | * [GitHub Actions](https://github.com/features/actions) 17 | * [Azure Container Registry](https://docs.microsoft.com/azure/container-registry/) 18 | * [Azure Bicep](https://docs.microsoft.com/azure/azure-resource-manager/bicep/overview?tabs=**bicep**) 19 | * [gRPC](https://grpc.io/) and building [gRPC apps using ASP.NET Core](https://docs.microsoft.com/aspnet/core/grpc/?view=aspnetcore-6.0) 20 | 21 | ## Prerequisites 22 | 23 | You'll need an Azure subscription and a very small set of tools and skills to get started: 24 | 25 | 1. An Azure subscription. Sign up [for free](https://azure.microsoft.com/free/). 26 | 2. A GitHub account, with access to GitHub Actions. 27 | 3. Either the [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli) installed locally, or, access to [GitHub Codespaces](https://github.com/features/codespaces), which would enable you to do develop in your browser. 28 | 29 | ## Topology diagram 30 | 31 | This app is represented by 1 (or more) background worker apps that make repetitive requests via gRPC to a gRPC host container. That host container aggregates the data into a stream after storing it temporarily in Memory Cache. A final container, hosting a frontend Blazor Server application, has a streaming connection to the gRPC service. 32 | 33 | ![Sample topology once deployed.](docs/media/toplogy.png) 34 | 35 | 36 | 37 | As the gRPC service receives data payloads from the individual worker instances, it streams that data constantly to the frontend web app, which displays a graph showing the data being received over time. The app demonstrates how a series of backend services can communicate internally within the Azure Container Apps environment using HTTP2 and gRPC. 38 | 39 | ## Setup 40 | 41 | By the end of this section you'll have a 3-node app running in Azure. This setup process consists of two steps, and should take you around 15 minutes. 42 | 43 | 1. Use the Azure CLI to create an Azure Service Principal, then store that principal's JSON output to a GitHub secret so the GitHub Actions CI/CD process can log into your Azure subscription and deploy the code. 44 | 2. Edit the ` deploy.yml` workflow file and push the changes into a new `deploy` branch, triggering GitHub Actions to build the .NET projects into containers and push those containers into a new Azure Container Apps Environment. 45 | 46 | ## Authenticate to Azure and configure the repository with a secret 47 | 48 | 1. Fork this repository to your own GitHub organization. 49 | 2. Create an Azure Service Principal using the Azure CLI. 50 | 51 | ```bash 52 | $subscriptionId=$(az account show --query id --output tsv) 53 | az ad sp create-for-rbac --sdk-auth --name gRPCAcaSample --role contributor --scopes /subscriptions/$subscriptionId 54 | ``` 55 | 56 | 3. Copy the JSON written to the screen to your clipboard. 57 | 58 | ```json 59 | { 60 | "clientId": "", 61 | "clientSecret": "", 62 | "subscriptionId": "", 63 | "tenantId": "", 64 | "activeDirectoryEndpointUrl": "https://login.microsoftonline.com/", 65 | "resourceManagerEndpointUrl": "https://brazilus.management.azure.com", 66 | "activeDirectoryGraphResourceId": "https://graph.windows.net/", 67 | "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/", 68 | "galleryEndpointUrl": "https://gallery.azure.com", 69 | "managementEndpointUrl": "https://management.core.windows.net" 70 | } 71 | ``` 72 | 73 | 4. Create a new GitHub secret in your fork of this repository named `AzureSPN`. Paste the JSON returned from the Azure CLI into this new secret. Once you've done this you'll see the secret in your fork of the repository. 74 | 75 | ![The AzureSPN secret in GitHub](docs/media/secrets.png) 76 | 77 | > Note: Never save the JSON to disk, for it will enable anyone who obtains this JSON code to create or edit resources in your Azure subscription. 78 | 79 | ## Deploy the code using GitHub Actions 80 | 81 | The easiest way to deploy the code is to make a commit directly to the `deploy` branch. Do this by navigating to the `deploy.yml` file in your browser and clicking the `Edit` button. 82 | 83 | ![Edit the deployment file](docs/media/edit-the-deploy-file.png) 84 | 85 | Provide a custom resource group name for the app, and then commit the change to a new branch named `deploy`. 86 | 87 | ![Create the deployment branch.](docs/media/create-the-deployment-branch.png) 88 | 89 | Once you click the `Propose changes` button, you'll be in "create a pull request" mode. Don't worry about creating the pull request yet, just click on the `Actions` tab, and you'll see that the deployment CI/CD process has already started. 90 | 91 | ![Deployment started.](docs/media/deployment-started.png) 92 | 93 | When you click into the workflow, you'll see that there are 3 phases the CI/CD will run through: 94 | 95 | 1. provision - the Azure resources will be created that eventually house your app. 96 | 2. build - the various .NET projects are build into containers and published into the Azure Container Registry instance created during provision. 97 | 3. deploy - once `build` completes, the images are in ACR, so the Azure Container Apps are updated to host the newly-published container images. 98 | 99 | ![CI/CD phases.](docs/media/deployment-phases.png) 100 | 101 | After a few minutes, all three steps in the workflow will be completed, and each box in the workflow diagram will reflect success. If anything fails, you can click into the individual process step to see the detailed log output. 102 | 103 | > Note: if you do see any failures or issues, please submit an Issue so we can update the sample. Likewise, if you have ideas that could make it better, feel free to submit a pull request. 104 | 105 | ![Deployment succeeded](docs/media/deployment-success.png) 106 | 107 | With the projects deployed to Azure, you can now test the app to make sure it works. 108 | 109 | ## Try the app in Azure 110 | 111 | The `deploy` CI/CD process creates a series of resources in your Azure subscription. These are used primarily for hosting the project code, but there's also a few additional resources that aid with monitoring and observing how the app is running in the deployed environment. 112 | | Resource | Resource Type | Purpose | 113 | | ---------------- | ------------------------- | ------------------------------------------------------------ | 114 | | `prefix`grpcai | Application Insights | This provides telemetry about the application's execution, and stores traces, logs, and exception data captured by the Application Insights SDK. | 115 | | frontend | Container App | Hosts the container with the code for the frontend Blazor server application that receives streaming data from the gRPC service. | 116 | | service | Container App | Hosts the container with the code for the gRPC service that both receives requests from the individual Worker services and provides streaming data about the status of the individual workers. | 117 | | worker | Container App | Hosts the container(s) with the code for the Worker Service that sends messages representing sensor data pings (like temperature sensors or light sensors). | 118 | | `prefix`grpcenv | Container App Environment | The Azure Container App Environment, in which all of the container apps running can communicate with one another relatively openly. | 119 | | `prefix`grpcacr | Azure Container Registry | The container registry into which all of my application's microservices are published and stored prior to their being deployed as Azure Container Apps. | 120 | | `prefix`grpclogs | Log Analytics | A Log Analytics account, which provides container logs for all of the container app running in my container app environment. This is where you'll look for most `ILogger` log output using [Kusto](https://docs.microsoft.com/azure/data-explorer/kusto/query/). | 121 | 122 | The resources are shown here in the Azure portal: 123 | 124 | ![The app deployed to Azure.](docs/media/deployed-to-azure.png) 125 | 126 | Click on the `frontend` container app to open it up in the Azure portal. In the `Overview` tab you'll see a URL. 127 | 128 | ![Front end.](docs/media/front-end.png) 129 | 130 | Clicking that URL will open the app's frontend up in the browser. When it opens, you'll see a line chart that fluctuates as it receives data from the streaming gRPC API. 131 | 132 | ![App frontend.](docs/media/app-front-end.png) 133 | 134 | ## Scale the Worker 135 | 136 | Now, you can scale out the `worker` container app to simulate multiple clients feeding into the gRPC service. To do this, go into the Revision management tool in the Azure portal, and you'll see the revision(s) currently active. You may see 2 revisions even though only one of the revisions is running your code, since the original deployment housed the Azure Container Apps welcome image, and the *second* deployment (the one performed during the `deploy` CI/CD step, since `provision` creates the Azure Container App with the default welcome image). 137 | 138 | ![Revision management tab.](docs/media/revision-management.png) 139 | 140 | Click the Create new revision button, and set the Scale slider to be anything more than 1. 141 | 142 | ![Creating a new Azure Container Apps revision with +1 scale.](docs/media/new-revision.png) 143 | 144 | Once the new revision is provisioned, you should see additional charts appear in the `frontend` web app. Each time a new `worker` starts up, it represents 1 device twin feeding data to the centralized gRPC `service` container app. 145 | 146 | ![New sensor workers coming online.](docs/media/new-sensor-workers.png) 147 | 148 | ## Monitoring 149 | 150 | The application is instrumented with Azure Application Insights, and the Azure Container Apps environment has a Log Analytics dependency, so you can easily deep-dive into the logs from the application. 151 | 152 | ![Application logs in Log Analytics.](docs/media/logs.png) 153 | 154 | You can also use the Application Insights Application Map to see a high-level overview of all the nodes and containers in the application, and to see how messages are being transmitted between each container through the Azure Container Apps environment. 155 | 156 | ![Application Map for the workers and gRPC service.](docs/media/appmap.png) 157 | 158 | ## Summary 159 | 160 | This sample walks you through the creation of a distributed cloud-native app running in Azure Container Apps, which makes use of gRPC in both request/response and streaming APIs. You've also seen how to monitor and view the application's logs. Take some time and explore Azure Container Apps and what you can do with it as a solid host for your cloud-native .NET apps. 161 | -------------------------------------------------------------------------------- /SensorApp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32324.85 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Frontend", "Frontend\Frontend.csproj", "{472EA4A9-0AD2-44BC-A3E8-CFA380EB4D2D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SensorService", "SensorService\SensorService.csproj", "{1A8526A6-FAD7-46A8-92C9-FD0A8BA31DEF}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SensorWorker", "SensorWorker\SensorWorker.csproj", "{42906AF7-6522-40A4-9B14-AD470DE22BBD}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Monitoring", "Monitoring\Monitoring.csproj", "{BBA38D1D-E411-426F-8F59-A71E65F921AD}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {472EA4A9-0AD2-44BC-A3E8-CFA380EB4D2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {472EA4A9-0AD2-44BC-A3E8-CFA380EB4D2D}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {472EA4A9-0AD2-44BC-A3E8-CFA380EB4D2D}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {472EA4A9-0AD2-44BC-A3E8-CFA380EB4D2D}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {1A8526A6-FAD7-46A8-92C9-FD0A8BA31DEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {1A8526A6-FAD7-46A8-92C9-FD0A8BA31DEF}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {1A8526A6-FAD7-46A8-92C9-FD0A8BA31DEF}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {1A8526A6-FAD7-46A8-92C9-FD0A8BA31DEF}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {42906AF7-6522-40A4-9B14-AD470DE22BBD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {42906AF7-6522-40A4-9B14-AD470DE22BBD}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {42906AF7-6522-40A4-9B14-AD470DE22BBD}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {42906AF7-6522-40A4-9B14-AD470DE22BBD}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {BBA38D1D-E411-426F-8F59-A71E65F921AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {BBA38D1D-E411-426F-8F59-A71E65F921AD}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {BBA38D1D-E411-426F-8F59-A71E65F921AD}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {BBA38D1D-E411-426F-8F59-A71E65F921AD}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {F89CC252-4DCF-4E7A-AEA9-F225B2F6A485} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /SensorService/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | EXPOSE 443 7 | 8 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 9 | WORKDIR /src 10 | COPY ["SensorService/SensorService.csproj", "SensorService/"] 11 | COPY ["Monitoring/Monitoring.csproj", "Monitoring/"] 12 | RUN dotnet restore "SensorService/SensorService.csproj" 13 | COPY . . 14 | WORKDIR "/src/SensorService" 15 | RUN dotnet build "SensorService.csproj" -c Release -o /app/build 16 | 17 | FROM build AS publish 18 | RUN dotnet publish "SensorService.csproj" -c Release -o /app/publish 19 | 20 | FROM base AS final 21 | WORKDIR /app 22 | COPY --from=publish /app/publish . 23 | ENTRYPOINT ["dotnet", "SensorService.dll"] -------------------------------------------------------------------------------- /SensorService/Program.cs: -------------------------------------------------------------------------------- 1 | using SensorService.Services; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | builder.Services.AddGrpc(); 7 | builder.Services.AddMemoryCache(); 8 | builder.Services.AddWebApplicationMonitoring(); 9 | 10 | var app = builder.Build(); 11 | 12 | // Configure the HTTP request pipeline. 13 | app.MapGrpcService(); 14 | app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); 15 | 16 | app.Run(); 17 | -------------------------------------------------------------------------------- /SensorService/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "SensorService": { 4 | "commandName": "Project", 5 | "environmentVariables": { 6 | "ASPNETCORE_ENVIRONMENT": "Development" 7 | }, 8 | "applicationUrl": "http://localhost:5000;https://localhost:5001", 9 | "dotnetRunMessages": true 10 | }, 11 | "Docker": { 12 | "commandName": "Docker", 13 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", 14 | "publishAllPorts": true, 15 | "useSSL": true 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /SensorService/Protos/sensor.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | import "google/protobuf/empty.proto"; 3 | 4 | option csharp_namespace = "Sensors"; 5 | 6 | package sensor; 7 | 8 | service SensorTwin { 9 | rpc ReceiveValueFromTwin (ReceiveValueFromTwinRequest) returns (ReceivedValueFromTwinReply); 10 | rpc GetDeviceTwinStream (google.protobuf.Empty) returns (stream ReceivedValueFromTwinReply); 11 | } 12 | 13 | message ReceiveValueFromTwinRequest { 14 | string sensor = 1; 15 | double value = 2; 16 | } 17 | 18 | message ReceivedValueFromTwinReply { 19 | string message = 1; 20 | string sensor = 2; 21 | double value = 3; 22 | } 23 | -------------------------------------------------------------------------------- /SensorService/SensorService.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 3d9bc2a5-7a6e-42ae-83f3-39aa1a0282c7 8 | Linux 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /SensorService/Services/SensorTwinService.cs: -------------------------------------------------------------------------------- 1 | using Google.Protobuf.WellKnownTypes; 2 | using Grpc.Core; 3 | using Microsoft.Extensions.Caching.Memory; 4 | using Sensors; 5 | 6 | namespace SensorService.Services 7 | { 8 | public class SensorTwinService : Sensors.SensorTwin.SensorTwinBase 9 | { 10 | const string CACHE_KEY = "READINGS_"; 11 | public IMemoryCache MemoryCache { get; set; } 12 | 13 | public SensorTwinService(IMemoryCache memoryCache) 14 | { 15 | MemoryCache = memoryCache; 16 | } 17 | 18 | private void SetRecentReadings(Dictionary> input) => MemoryCache.Set>>(CACHE_KEY, input); 19 | 20 | private Dictionary> GetRecentReadings() 21 | { 22 | var tmp = new Dictionary>(); 23 | if (!MemoryCache.TryGetValue>>(CACHE_KEY, out tmp)) 24 | { 25 | tmp = new Dictionary>(); 26 | SetRecentReadings(tmp); 27 | } 28 | 29 | return tmp; 30 | } 31 | 32 | public override async Task GetDeviceTwinStream(Empty request, IServerStreamWriter responseStream, ServerCallContext context) 33 | { 34 | while (!context.CancellationToken.IsCancellationRequested) 35 | { 36 | var readings = GetRecentReadings(); 37 | SetRecentReadings(new Dictionary>()); 38 | 39 | foreach (var item in readings) 40 | { 41 | foreach (var value in item.Value) 42 | { 43 | await responseStream.WriteAsync(new ReceivedValueFromTwinReply 44 | { 45 | Message = $"Received {value} from sensor {item.Key}.", 46 | Value = value, 47 | Sensor = item.Key 48 | }); 49 | } 50 | } 51 | 52 | await Task.Delay(100); 53 | } 54 | } 55 | 56 | public override Task ReceiveValueFromTwin(ReceiveValueFromTwinRequest request, ServerCallContext context) 57 | { 58 | var readings = GetRecentReadings(); 59 | 60 | lock(readings) 61 | { 62 | if (!readings.Any(x => x.Key == request.Sensor)) 63 | readings.Add(request.Sensor, new List()); 64 | 65 | if (readings[request.Sensor].Count >= 100) 66 | readings[request.Sensor].RemoveAt(0); 67 | 68 | readings[request.Sensor].Add(request.Value); 69 | SetRecentReadings(readings); 70 | 71 | return Task.FromResult(new ReceivedValueFromTwinReply 72 | { 73 | Message = $"Received {request.Value} from {request.Sensor}.", 74 | Sensor = request.Sensor, 75 | Value = request.Value 76 | }); 77 | } 78 | 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /SensorService/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /SensorService/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Console": { 3 | "DisableColors": true 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft.AspNetCore": "Warning" 9 | } 10 | }, 11 | "AllowedHosts": "*", 12 | "Kestrel": { 13 | "EndpointDefaults": { 14 | "Protocols": "Http2" 15 | } 16 | }, 17 | "ApplicationMapNodeName": "Sensor Service" 18 | } 19 | -------------------------------------------------------------------------------- /SensorWorker/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base 4 | WORKDIR /app 5 | 6 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 7 | WORKDIR /src 8 | COPY ["SensorWorker/SensorWorker.csproj", "SensorWorker/"] 9 | COPY ["Monitoring/Monitoring.csproj", "Monitoring/"] 10 | RUN dotnet restore "SensorWorker/SensorWorker.csproj" 11 | COPY . . 12 | WORKDIR "/src/SensorWorker" 13 | RUN dotnet build "SensorWorker.csproj" -c Release -o /app/build 14 | 15 | FROM build AS publish 16 | RUN dotnet publish "SensorWorker.csproj" -c Release -o /app/publish 17 | 18 | FROM base AS final 19 | WORKDIR /app 20 | COPY --from=publish /app/publish . 21 | ENTRYPOINT ["dotnet", "SensorWorker.dll"] -------------------------------------------------------------------------------- /SensorWorker/Program.cs: -------------------------------------------------------------------------------- 1 | using SensorWorker; 2 | 3 | IHost host = Host.CreateDefaultBuilder(args) 4 | .ConfigureServices(services => 5 | { 6 | services.AddHostedService(); 7 | services.AddWorkerApplicationMonitoring(); 8 | }) 9 | .Build(); 10 | 11 | await host.RunAsync(); 12 | -------------------------------------------------------------------------------- /SensorWorker/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "SensorWorker": { 4 | "commandName": "Project", 5 | "environmentVariables": { 6 | "DOTNET_ENVIRONMENT": "Development" 7 | }, 8 | "dotnetRunMessages": true 9 | }, 10 | "Docker": { 11 | "commandName": "Docker" 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /SensorWorker/SensorWorker.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | dotnet-SensorWorker-87575C4C-7753-4C1D-A0E9-617DA49F171B 8 | Linux 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | Protos\sensor.proto 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /SensorWorker/Worker.cs: -------------------------------------------------------------------------------- 1 | using Sensors; 2 | using System.Diagnostics; 3 | 4 | namespace SensorWorker 5 | { 6 | public class Worker : BackgroundService 7 | { 8 | private readonly ILogger _logger; 9 | private readonly IConfiguration _configuration; 10 | private readonly SensorTwin.SensorTwinClient _sensorTwinClient; 11 | private Random _random = new Random(); 12 | private double _phaseStartTemp; 13 | private double _phaseEndTemp; 14 | private double _currentValue; 15 | private double _phaseDurationSeconds; 16 | private const double MinVal = 50; 17 | private const double MaxVal = 85; 18 | private const int MinPhaseDuration = 5; 19 | private const int MaxPhaseDuration = 30; 20 | private Random _rnd = new Random(); 21 | private Stopwatch _totalTime = Stopwatch.StartNew(); 22 | 23 | public Worker(ILogger logger, IConfiguration configuration) 24 | { 25 | _logger = logger; 26 | _configuration = configuration; 27 | _sensorTwinClient = new Sensors.SensorTwin.SensorTwinClient(Grpc.Net.Client.GrpcChannel.ForAddress(configuration.GetValue("SERVICE_ENDPOINT"))); 28 | 29 | StartNewPhase(); 30 | } 31 | 32 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) 33 | { 34 | var randomSensorName = new Random().Next(1000, 9999); 35 | 36 | while (!stoppingToken.IsCancellationRequested) 37 | { 38 | _logger.LogInformation($"Sending sensor reading: {_currentValue}"); 39 | 40 | UpdateTemperatureReading(); 41 | var result = await _sensorTwinClient.ReceiveValueFromTwinAsync(new ReceiveValueFromTwinRequest 42 | { 43 | Sensor = $"{Environment.MachineName}-{randomSensorName}", 44 | Value = Math.Round(_currentValue, 2) 45 | }); 46 | 47 | _logger.LogInformation($"Sensor worker received: {result.Message}."); 48 | 49 | await Task.Delay(100, stoppingToken); 50 | } 51 | } 52 | 53 | public void UpdateTemperatureReading() 54 | { 55 | double startRads; 56 | double endRads; 57 | double offset; 58 | if (_phaseStartTemp >= _phaseEndTemp) 59 | { 60 | // Cooling phase, that means moving from PI/2 to 3*PI/2 61 | startRads = Math.PI / 2; 62 | endRads = 3 * Math.PI / 2; 63 | offset = -1; 64 | } 65 | else 66 | { 67 | // Heading phase, that means moving from 3*PI/2 to 5*PI/2 68 | startRads = 3 * Math.PI / 2; 69 | endRads = 5 * Math.PI / 2; 70 | offset = 1; 71 | } 72 | 73 | var currentSeconds = _totalTime.Elapsed.TotalSeconds; 74 | var currentRads = startRads + (currentSeconds * Math.PI / _phaseDurationSeconds); 75 | 76 | _currentValue = _phaseStartTemp + ((offset + Math.Sin(currentRads)) / 2) * Math.Abs(_phaseStartTemp - _phaseEndTemp); 77 | 78 | if (currentRads >= endRads) 79 | { 80 | StartNewPhase(); 81 | } 82 | } 83 | 84 | private void StartNewPhase() 85 | { 86 | _phaseStartTemp = _currentValue; 87 | _phaseEndTemp = MinVal + _rnd.NextDouble() * (MaxVal - MinVal); 88 | _phaseDurationSeconds = _rnd.Next(MinPhaseDuration, MaxPhaseDuration); 89 | _totalTime.Restart(); 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /SensorWorker/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.Hosting.Lifetime": "Information" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /SensorWorker/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "Console": { 4 | "DisableColors": true 5 | }, 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft.Hosting.Lifetime": "Information" 9 | } 10 | }, 11 | "SERVICE_ENDPOINT": "http://localhost:5000", 12 | "ApplicationMapNodeName": "Sensor Worker" 13 | } 14 | -------------------------------------------------------------------------------- /docs/media/app-front-end.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/app-front-end.png -------------------------------------------------------------------------------- /docs/media/appmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/appmap.png -------------------------------------------------------------------------------- /docs/media/create-the-deployment-branch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/create-the-deployment-branch.png -------------------------------------------------------------------------------- /docs/media/deployed-to-azure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/deployed-to-azure.png -------------------------------------------------------------------------------- /docs/media/deployment-phases.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/deployment-phases.png -------------------------------------------------------------------------------- /docs/media/deployment-started.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/deployment-started.png -------------------------------------------------------------------------------- /docs/media/deployment-success.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/deployment-success.png -------------------------------------------------------------------------------- /docs/media/edit-the-deploy-file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/edit-the-deploy-file.png -------------------------------------------------------------------------------- /docs/media/front-end.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/front-end.png -------------------------------------------------------------------------------- /docs/media/logs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/logs.png -------------------------------------------------------------------------------- /docs/media/new-revision.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/new-revision.png -------------------------------------------------------------------------------- /docs/media/new-sensor-workers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/new-sensor-workers.png -------------------------------------------------------------------------------- /docs/media/revision-management.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/revision-management.png -------------------------------------------------------------------------------- /docs/media/secrets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/secrets.png -------------------------------------------------------------------------------- /docs/media/toplogy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/dotNET-Workers-with-gRPC-messaging-on-Azure-Container-Apps/28d4092dafb1bd2543a73f7fd2f932bc2ddfa1d6/docs/media/toplogy.png --------------------------------------------------------------------------------