├── .gitignore
├── .vscode
├── launch.json
└── tasks.json
├── CommandsService
├── .vscode
│ ├── launch.json
│ └── tasks.json
├── AsyncDataServices
│ └── MessageBusSubscriber.cs
├── CommandsService.csproj
├── Controllers
│ ├── CommandsController.cs
│ └── PlatformsController.cs
├── Data
│ ├── AppDbContext.cs
│ ├── CommandRepo.cs
│ ├── ICommandRepo.cs
│ └── PrepDb.cs
├── Dockerfile
├── Dtos
│ ├── CommandCreateDto.cs
│ ├── CommandReadDto.cs
│ ├── GenericEventDto.cs
│ ├── PlatformPublishedDto.cs
│ └── PlatformReadDto.cs
├── EventProcessing
│ ├── EventProcessor.cs
│ └── IEventProcessor.cs
├── Models
│ ├── Command.cs
│ └── Platform.cs
├── Profiles
│ └── CommandsProfile.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Protos
│ └── platforms.proto
├── Startup.cs
├── SyncDataServices
│ └── Grpc
│ │ ├── IPlatformDataClient.cs
│ │ └── PlatformDataClient.cs
├── appsettings.Development.json
├── appsettings.Production.json
└── appsettings.json
├── K8S
├── commands-depl.yaml
├── ingress-srv.yaml
├── local-pvc.yaml
├── mssql-plat-depl.yaml
├── platforms-depl.yaml
├── platforms-np-srv.yaml
└── rabbitmq-depl.yaml
└── PlatformService
├── .vscode
├── launch.json
└── tasks.json
├── AsyncDataServices
├── IMessageBusClient.cs
└── MessageBusClient.cs
├── Controllers
└── PlatformsController.cs
├── Data
├── AppDbContext.cs
├── IPlatformRepo.cs
├── PlatformRepo.cs
└── PrepDb.cs
├── Dockerfile
├── Dtos
├── PlatformCreateDto.cs
├── PlatformPublishedDto.cs
└── PlatformReadDto.cs
├── Migrations
├── 20210811091426_initialmigration.Designer.cs
├── 20210811091426_initialmigration.cs
└── AppDbContextModelSnapshot.cs
├── Models
└── Platform.cs
├── PlatformService.csproj
├── Profiles
└── PlatformsProfile.cs
├── Program.cs
├── Properties
└── launchSettings.json
├── Protos
└── platforms.proto
├── Startup.cs
├── SyncDataServices
├── Grpc
│ └── GrpcPlatformService.cs
└── Http
│ ├── HttpCommandDataClient.cs
│ └── ICommandDataClient.cs
├── appsettings.Development.json
└── appsettings.Production.json
/.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/
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/PlatformService/bin/Debug/net5.0/PlatformService.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}/PlatformService",
16 | "stopAtEntry": false,
17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18 | "serverReadyAction": {
19 | "action": "openExternally",
20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21 | },
22 | "env": {
23 | "ASPNETCORE_ENVIRONMENT": "Development"
24 | },
25 | "sourceFileMap": {
26 | "/Views": "${workspaceFolder}/Views"
27 | }
28 | },
29 | {
30 | "name": ".NET Core Attach",
31 | "type": "coreclr",
32 | "request": "attach"
33 | }
34 | ]
35 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/PlatformService/PlatformService.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/PlatformService/PlatformService.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/PlatformService/PlatformService.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/CommandsService/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/bin/Debug/net5.0/CommandsService.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}",
16 | "stopAtEntry": false,
17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18 | "serverReadyAction": {
19 | "action": "openExternally",
20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21 | },
22 | "env": {
23 | "ASPNETCORE_ENVIRONMENT": "Development"
24 | },
25 | "sourceFileMap": {
26 | "/Views": "${workspaceFolder}/Views"
27 | }
28 | },
29 | {
30 | "name": ".NET Core Attach",
31 | "type": "coreclr",
32 | "request": "attach"
33 | }
34 | ]
35 | }
--------------------------------------------------------------------------------
/CommandsService/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/CommandsService.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/CommandsService.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/CommandsService.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/CommandsService/AsyncDataServices/MessageBusSubscriber.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 | using CommandsService.EventProcessing;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.Hosting;
8 | using RabbitMQ.Client;
9 | using RabbitMQ.Client.Events;
10 |
11 | namespace CommandsService.AsyncDataServices
12 | {
13 | public class MessageBusSubscriber : BackgroundService
14 | {
15 | private readonly IConfiguration _configuration;
16 | private readonly IEventProcessor _eventProcessor;
17 | private IConnection _connection;
18 | private IModel _channel;
19 | private string _queueName;
20 |
21 | public MessageBusSubscriber(
22 | IConfiguration configuration,
23 | IEventProcessor eventProcessor)
24 | {
25 | _configuration = configuration;
26 | _eventProcessor = eventProcessor;
27 |
28 | InitializeRabbitMQ();
29 | }
30 |
31 | private void InitializeRabbitMQ()
32 | {
33 | var factory = new ConnectionFactory() { HostName = _configuration["RabbitMQHost"], Port = int.Parse(_configuration["RabbitMQPort"])};
34 |
35 | _connection = factory.CreateConnection();
36 | _channel = _connection.CreateModel();
37 | _channel.ExchangeDeclare(exchange: "trigger", type: ExchangeType.Fanout);
38 | _queueName = _channel.QueueDeclare().QueueName;
39 | _channel.QueueBind(queue: _queueName,
40 | exchange: "trigger",
41 | routingKey: "");
42 |
43 | Console.WriteLine("--> Listenting on the Message Bus...");
44 |
45 | _connection.ConnectionShutdown += RabbitMQ_ConnectionShitdown;
46 | }
47 |
48 | protected override Task ExecuteAsync(CancellationToken stoppingToken)
49 | {
50 | stoppingToken.ThrowIfCancellationRequested();
51 |
52 | var consumer = new EventingBasicConsumer(_channel);
53 |
54 | consumer.Received += (ModuleHandle, ea) =>
55 | {
56 | Console.WriteLine("--> Event Received!");
57 |
58 | var body = ea.Body;
59 | var notificationMessage = Encoding.UTF8.GetString(body.ToArray());
60 |
61 | _eventProcessor.ProcessEvent(notificationMessage);
62 | };
63 |
64 | _channel.BasicConsume(queue: _queueName, autoAck: true, consumer: consumer);
65 |
66 | return Task.CompletedTask;
67 | }
68 |
69 | private void RabbitMQ_ConnectionShitdown(object sender, ShutdownEventArgs e)
70 | {
71 | Console.WriteLine("--> Connection Shutdown");
72 | }
73 |
74 | public override void Dispose()
75 | {
76 | if(_channel.IsOpen)
77 | {
78 | _channel.Close();
79 | _connection.Close();
80 | }
81 |
82 | base.Dispose();
83 | }
84 | }
85 | }
--------------------------------------------------------------------------------
/CommandsService/CommandsService.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | runtime; build; native; contentfiles; analyzers; buildtransitive
13 | all
14 |
15 |
16 |
17 | runtime; build; native; contentfiles; analyzers; buildtransitive
18 | all
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/CommandsService/Controllers/CommandsController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using AutoMapper;
4 | using CommandsService.Data;
5 | using CommandsService.Dtos;
6 | using CommandsService.Models;
7 | using Microsoft.AspNetCore.Mvc;
8 |
9 | namespace CommandsService.Controllers
10 | {
11 | [Route("api/c/platforms/{platformId}/[controller]")]
12 | [ApiController]
13 | public class CommandsController : ControllerBase
14 | {
15 | private readonly ICommandRepo _repository;
16 | private readonly IMapper _mapper;
17 |
18 | public CommandsController(ICommandRepo repository, IMapper mapper)
19 | {
20 | _repository = repository;
21 | _mapper = mapper;
22 | }
23 |
24 | [HttpGet]
25 | public ActionResult> GetCommandsForPlatform(int platformId)
26 | {
27 | Console.WriteLine($"--> Hit GetCommandsForPlatform: {platformId}");
28 |
29 | if (!_repository.PlaformExits(platformId))
30 | {
31 | return NotFound();
32 | }
33 |
34 | var commands = _repository.GetCommandsForPlatform(platformId);
35 |
36 | return Ok(_mapper.Map>(commands));
37 | }
38 |
39 | [HttpGet("{commandId}", Name = "GetCommandForPlatform")]
40 | public ActionResult GetCommandForPlatform(int platformId, int commandId)
41 | {
42 | Console.WriteLine($"--> Hit GetCommandForPlatform: {platformId} / {commandId}");
43 |
44 | if (!_repository.PlaformExits(platformId))
45 | {
46 | return NotFound();
47 | }
48 |
49 | var command = _repository.GetCommand(platformId, commandId);
50 |
51 | if(command == null)
52 | {
53 | return NotFound();
54 | }
55 |
56 | return Ok(_mapper.Map(command));
57 | }
58 |
59 | [HttpPost]
60 | public ActionResult CreateCommandForPlatform(int platformId, CommandCreateDto commandDto)
61 | {
62 | Console.WriteLine($"--> Hit CreateCommandForPlatform: {platformId}");
63 |
64 | if (!_repository.PlaformExits(platformId))
65 | {
66 | return NotFound();
67 | }
68 |
69 | var command = _mapper.Map(commandDto);
70 |
71 | _repository.CreateCommand(platformId, command);
72 | _repository.SaveChanges();
73 |
74 | var commandReadDto = _mapper.Map(command);
75 |
76 | return CreatedAtRoute(nameof(GetCommandForPlatform),
77 | new {platformId = platformId, commandId = commandReadDto.Id}, commandReadDto);
78 | }
79 |
80 | }
81 | }
--------------------------------------------------------------------------------
/CommandsService/Controllers/PlatformsController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using AutoMapper;
4 | using CommandsService.Data;
5 | using CommandsService.Dtos;
6 | using Microsoft.AspNetCore.Mvc;
7 |
8 | namespace CommandsService.Controllers
9 | {
10 | [Route("api/c/[controller]")]
11 | [ApiController]
12 | public class PlatformsController : ControllerBase
13 | {
14 | private readonly ICommandRepo _repository;
15 | private readonly IMapper _mapper;
16 |
17 | public PlatformsController(ICommandRepo repository, IMapper mapper)
18 | {
19 | _repository = repository;
20 | _mapper = mapper;
21 | }
22 |
23 | [HttpGet]
24 | public ActionResult> GetPlatforms()
25 | {
26 | Console.WriteLine("--> Getting Platforms from CommandsService");
27 |
28 | var platformItems = _repository.GetAllPlatforms();
29 |
30 | return Ok(_mapper.Map>(platformItems));
31 | }
32 |
33 | [HttpPost]
34 | public ActionResult TestInboundConnection()
35 | {
36 | Console.WriteLine("--> Inbound POST # Command Service");
37 |
38 | return Ok("Inbound test of from Platforms Controler");
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/CommandsService/Data/AppDbContext.cs:
--------------------------------------------------------------------------------
1 | using CommandsService.Models;
2 | using Microsoft.EntityFrameworkCore;
3 |
4 | namespace CommandsService.Data
5 | {
6 | public class AppDbContext : DbContext
7 | {
8 | public AppDbContext(DbContextOptions opt ) : base(opt)
9 | {
10 |
11 | }
12 |
13 | public DbSet Platforms { get; set; }
14 | public DbSet Commands { get; set; }
15 |
16 | protected override void OnModelCreating(ModelBuilder modelBuilder)
17 | {
18 | modelBuilder
19 | .Entity()
20 | .HasMany(p => p.Commands)
21 | .WithOne(p=> p.Platform!)
22 | .HasForeignKey(p => p.PlatformId);
23 |
24 | modelBuilder
25 | .Entity()
26 | .HasOne(p => p.Platform)
27 | .WithMany(p => p.Commands)
28 | .HasForeignKey(p =>p.PlatformId);
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/CommandsService/Data/CommandRepo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using CommandsService.Models;
5 |
6 | namespace CommandsService.Data
7 | {
8 | public class CommandRepo : ICommandRepo
9 | {
10 | private readonly AppDbContext _context;
11 |
12 | public CommandRepo(AppDbContext context)
13 | {
14 | _context = context;
15 | }
16 |
17 | public void CreateCommand(int platformId, Command command)
18 | {
19 | if (command == null)
20 | {
21 | throw new ArgumentNullException(nameof(command));
22 | }
23 |
24 | command.PlatformId = platformId;
25 | _context.Commands.Add(command);
26 | }
27 |
28 | public void CreatePlatform(Platform plat)
29 | {
30 | if(plat == null)
31 | {
32 | throw new ArgumentNullException(nameof(plat));
33 | }
34 | _context.Platforms.Add(plat);
35 | }
36 |
37 | public bool ExternalPlatformExists(int externalPlatformId)
38 | {
39 | return _context.Platforms.Any(p => p.ExternalID == externalPlatformId);
40 | }
41 |
42 | public IEnumerable GetAllPlatforms()
43 | {
44 | return _context.Platforms.ToList();
45 | }
46 |
47 | public Command GetCommand(int platformId, int commandId)
48 | {
49 | return _context.Commands
50 | .Where(c => c.PlatformId == platformId && c.Id == commandId).FirstOrDefault();
51 | }
52 |
53 | public IEnumerable GetCommandsForPlatform(int platformId)
54 | {
55 | return _context.Commands
56 | .Where(c => c.PlatformId == platformId)
57 | .OrderBy(c => c.Platform.Name);
58 | }
59 |
60 | public bool PlaformExits(int platformId)
61 | {
62 | return _context.Platforms.Any(p => p.Id == platformId);
63 | }
64 |
65 | public bool SaveChanges()
66 | {
67 | return (_context.SaveChanges() >= 0);
68 | }
69 | }
70 | }
--------------------------------------------------------------------------------
/CommandsService/Data/ICommandRepo.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using CommandsService.Models;
3 |
4 | namespace CommandsService.Data
5 | {
6 | public interface ICommandRepo
7 | {
8 | bool SaveChanges();
9 |
10 | // Platforms
11 | IEnumerable GetAllPlatforms();
12 | void CreatePlatform(Platform plat);
13 | bool PlaformExits(int platformId);
14 | bool ExternalPlatformExists(int externalPlatformId);
15 |
16 | // Commands
17 | IEnumerable GetCommandsForPlatform(int platformId);
18 | Command GetCommand(int platformId, int commandId);
19 | void CreateCommand(int platformId, Command command);
20 | }
21 | }
--------------------------------------------------------------------------------
/CommandsService/Data/PrepDb.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using CommandsService.Models;
4 | using CommandsService.SyncDataServices.Grpc;
5 | using Microsoft.AspNetCore.Builder;
6 | using Microsoft.Extensions.DependencyInjection;
7 |
8 | namespace CommandsService.Data
9 | {
10 | public static class PrepDb
11 | {
12 | public static void PrepPopulation(IApplicationBuilder applicationBuilder)
13 | {
14 | using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
15 | {
16 | var grpcClient = serviceScope.ServiceProvider.GetService();
17 |
18 | var platforms = grpcClient.ReturnAllPlatforms();
19 |
20 | SeedData(serviceScope.ServiceProvider.GetService(), platforms);
21 | }
22 | }
23 |
24 | private static void SeedData(ICommandRepo repo, IEnumerable platforms)
25 | {
26 | Console.WriteLine("Seeding new platforms...");
27 |
28 | foreach (var plat in platforms)
29 | {
30 | if(!repo.ExternalPlatformExists(plat.ExternalID))
31 | {
32 | repo.CreatePlatform(plat);
33 | }
34 | repo.SaveChanges();
35 | }
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/CommandsService/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build-env
2 | WORKDIR /app
3 |
4 | COPY *.csproj ./
5 | RUN dotnet restore
6 |
7 | COPY . ./
8 | RUN dotnet publish -c Release -o out
9 |
10 | FROM mcr.microsoft.com/dotnet/aspnet:5.0
11 | WORKDIR /app
12 | COPY --from=build-env /app/out .
13 | ENTRYPOINT [ "dotnet", "CommandsService.dll" ]
--------------------------------------------------------------------------------
/CommandsService/Dtos/CommandCreateDto.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel.DataAnnotations;
2 |
3 | namespace CommandsService.Dtos
4 | {
5 | public class CommandCreateDto
6 | {
7 | [Required]
8 | public string HowTo { get; set; }
9 |
10 | [Required]
11 | public string CommandLine { get; set; }
12 | }
13 | }
--------------------------------------------------------------------------------
/CommandsService/Dtos/CommandReadDto.cs:
--------------------------------------------------------------------------------
1 | namespace CommandsService.Dtos
2 | {
3 | public class CommandReadDto
4 | {
5 | public int Id { get; set; }
6 | public string HowTo { get; set; }
7 | public string CommandLine { get; set; }
8 | public int PlatformId { get; set; }
9 | }
10 | }
--------------------------------------------------------------------------------
/CommandsService/Dtos/GenericEventDto.cs:
--------------------------------------------------------------------------------
1 | namespace CommandsService.Dtos
2 | {
3 | public class GenericEventDto
4 | {
5 | public string Event { get; set; }
6 | }
7 | }
--------------------------------------------------------------------------------
/CommandsService/Dtos/PlatformPublishedDto.cs:
--------------------------------------------------------------------------------
1 | namespace CommandsService.Dtos
2 | {
3 | public class PlatformPublishedDto
4 | {
5 | public int Id { get; set; }
6 | public string Name { get; set; }
7 | public string Event { get; set; }
8 | }
9 | }
--------------------------------------------------------------------------------
/CommandsService/Dtos/PlatformReadDto.cs:
--------------------------------------------------------------------------------
1 | namespace CommandsService.Dtos
2 | {
3 | public class PlatformreadDto
4 | {
5 | public int Id { get; set; }
6 | public string Name { get; set; }
7 | }
8 | }
--------------------------------------------------------------------------------
/CommandsService/EventProcessing/EventProcessor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text.Json;
3 | using AutoMapper;
4 | using CommandsService.Data;
5 | using CommandsService.Dtos;
6 | using CommandsService.Models;
7 | using Microsoft.Extensions.DependencyInjection;
8 |
9 | namespace CommandsService.EventProcessing
10 | {
11 | public class EventProcessor : IEventProcessor
12 | {
13 | private readonly IServiceScopeFactory _scopeFactory;
14 | private readonly IMapper _mapper;
15 |
16 | public EventProcessor(IServiceScopeFactory scopeFactory, AutoMapper.IMapper mapper)
17 | {
18 | _scopeFactory = scopeFactory;
19 | _mapper = mapper;
20 | }
21 |
22 | public void ProcessEvent(string message)
23 | {
24 | var eventType = DetermineEvent(message);
25 |
26 | switch (eventType)
27 | {
28 | case EventType.PlatformPublished:
29 | addPlatform(message);
30 | break;
31 | default:
32 | break;
33 | }
34 | }
35 |
36 | private EventType DetermineEvent(string notifcationMessage)
37 | {
38 | Console.WriteLine("--> Determining Event");
39 |
40 | var eventType = JsonSerializer.Deserialize(notifcationMessage);
41 |
42 | switch(eventType.Event)
43 | {
44 | case "Platform_Published":
45 | Console.WriteLine("--> Platform Published Event Detected");
46 | return EventType.PlatformPublished;
47 | default:
48 | Console.WriteLine("--> Could not determine the event type");
49 | return EventType.Undetermined;
50 | }
51 | }
52 |
53 | private void addPlatform(string platformPublishedMessage)
54 | {
55 | using (var scope = _scopeFactory.CreateScope())
56 | {
57 | var repo = scope.ServiceProvider.GetRequiredService();
58 |
59 | var platformPublishedDto = JsonSerializer.Deserialize(platformPublishedMessage);
60 |
61 | try
62 | {
63 | var plat = _mapper.Map(platformPublishedDto);
64 | if(!repo.ExternalPlatformExists(plat.ExternalID))
65 | {
66 | repo.CreatePlatform(plat);
67 | repo.SaveChanges();
68 | Console.WriteLine("--> Platform added!");
69 | }
70 | else
71 | {
72 | Console.WriteLine("--> Platform already exisits...");
73 | }
74 |
75 | }
76 | catch (Exception ex)
77 | {
78 | Console.WriteLine($"--> Could not add Platform to DB {ex.Message}");
79 | }
80 | }
81 | }
82 | }
83 |
84 | enum EventType
85 | {
86 | PlatformPublished,
87 | Undetermined
88 | }
89 | }
--------------------------------------------------------------------------------
/CommandsService/EventProcessing/IEventProcessor.cs:
--------------------------------------------------------------------------------
1 | namespace CommandsService.EventProcessing
2 | {
3 | public interface IEventProcessor
4 | {
5 | void ProcessEvent(string message);
6 | }
7 | }
--------------------------------------------------------------------------------
/CommandsService/Models/Command.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel.DataAnnotations;
2 |
3 | namespace CommandsService.Models
4 | {
5 | public class Command
6 | {
7 | [Key]
8 | [Required]
9 | public int Id { get; set; }
10 |
11 | [Required]
12 | public string HowTo { get; set; }
13 |
14 | [Required]
15 | public string CommandLine { get; set; }
16 |
17 | [Required]
18 | public int PlatformId { get; set; }
19 |
20 | public Platform Platform {get; set;}
21 | }
22 | }
--------------------------------------------------------------------------------
/CommandsService/Models/Platform.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.ComponentModel.DataAnnotations;
3 |
4 | namespace CommandsService.Models
5 | {
6 | public class Platform
7 | {
8 | [Key]
9 | [Required]
10 | public int Id { get; set; }
11 |
12 | [Required]
13 | public int ExternalID { get; set; }
14 |
15 | [Required]
16 | public string Name { get; set; }
17 |
18 | public ICollection Commands { get; set; } = new List();
19 | }
20 | }
--------------------------------------------------------------------------------
/CommandsService/Profiles/CommandsProfile.cs:
--------------------------------------------------------------------------------
1 | using AutoMapper;
2 | using CommandsService.Dtos;
3 | using CommandsService.Models;
4 | using PlatformService;
5 |
6 | namespace CommandsService.Profiles
7 | {
8 | public class CommandsProfile : Profile
9 | {
10 | public CommandsProfile()
11 | {
12 | // Source -> Target
13 | CreateMap();
14 | CreateMap();
15 | CreateMap();
16 | CreateMap()
17 | .ForMember(dest => dest.ExternalID, opt => opt.MapFrom(src => src.Id));
18 | CreateMap()
19 | .ForMember(dest => dest.ExternalID, opt => opt.MapFrom(src => src.PlatformId))
20 | .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
21 | .ForMember(dest => dest.Commands, opt => opt.Ignore());
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/CommandsService/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Hosting;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.Hosting;
8 | using Microsoft.Extensions.Logging;
9 |
10 | namespace CommandsService
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/CommandsService/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:53729",
8 | "sslPort": 44345
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "CommandsService": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:6001;http://localhost:6000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/CommandsService/Protos/platforms.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | option csharp_namespace = "PlatformService";
4 |
5 | service GrpcPlatform {
6 | rpc GetAllPlatforms (GetAllRequest) returns (PlatformResponse);
7 | }
8 |
9 | message GetAllRequest {}
10 |
11 | message GrpcPlatformModel{
12 | int32 platformId = 1;
13 | string name = 2;
14 | string publisher = 3;
15 | }
16 |
17 | message PlatformResponse {
18 | repeated GrpcPlatformModel platform = 1;
19 | }
--------------------------------------------------------------------------------
/CommandsService/Startup.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using CommandsService.AsyncDataServices;
6 | using CommandsService.Data;
7 | using CommandsService.EventProcessing;
8 | using CommandsService.SyncDataServices.Grpc;
9 | using Microsoft.AspNetCore.Builder;
10 | using Microsoft.AspNetCore.Hosting;
11 | using Microsoft.AspNetCore.HttpsPolicy;
12 | using Microsoft.AspNetCore.Mvc;
13 | using Microsoft.EntityFrameworkCore;
14 | using Microsoft.Extensions.Configuration;
15 | using Microsoft.Extensions.DependencyInjection;
16 | using Microsoft.Extensions.Hosting;
17 | using Microsoft.Extensions.Logging;
18 | using Microsoft.OpenApi.Models;
19 |
20 | namespace CommandsService
21 | {
22 | public class Startup
23 | {
24 | public Startup(IConfiguration configuration)
25 | {
26 | Configuration = configuration;
27 | }
28 |
29 | public IConfiguration Configuration { get; }
30 |
31 |
32 | public void ConfigureServices(IServiceCollection services)
33 | {
34 | services.AddDbContext(opt => opt.UseInMemoryDatabase("InMen"));
35 | services.AddScoped();
36 | services.AddControllers();
37 |
38 | services.AddHostedService();
39 |
40 | services.AddSingleton();
41 | services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
42 | services.AddScoped();
43 | services.AddSwaggerGen(c =>
44 | {
45 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "CommandsService", Version = "v1" });
46 | });
47 | }
48 |
49 |
50 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
51 | {
52 | if (env.IsDevelopment())
53 | {
54 | app.UseDeveloperExceptionPage();
55 | app.UseSwagger();
56 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CommandsService v1"));
57 | }
58 |
59 | //app.UseHttpsRedirection();
60 |
61 | app.UseRouting();
62 |
63 | app.UseAuthorization();
64 |
65 | app.UseEndpoints(endpoints =>
66 | {
67 | endpoints.MapControllers();
68 | });
69 |
70 | PrepDb.PrepPopulation(app);
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/CommandsService/SyncDataServices/Grpc/IPlatformDataClient.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using CommandsService.Models;
3 |
4 | namespace CommandsService.SyncDataServices.Grpc
5 | {
6 | public interface IPlatformDataClient
7 | {
8 | IEnumerable ReturnAllPlatforms();
9 | }
10 | }
--------------------------------------------------------------------------------
/CommandsService/SyncDataServices/Grpc/PlatformDataClient.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using AutoMapper;
4 | using CommandsService.Models;
5 | using Grpc.Net.Client;
6 | using Microsoft.Extensions.Configuration;
7 | using PlatformService;
8 |
9 | namespace CommandsService.SyncDataServices.Grpc
10 | {
11 | public class PlatformDataClient : IPlatformDataClient
12 | {
13 | private readonly IConfiguration _configuration;
14 | private readonly IMapper _mapper;
15 |
16 | public PlatformDataClient(IConfiguration configuration, IMapper mapper)
17 | {
18 | _configuration = configuration;
19 | _mapper = mapper;
20 | }
21 |
22 | public IEnumerable ReturnAllPlatforms()
23 | {
24 | Console.WriteLine($"--> Calling GRPC Service {_configuration["GrpcPlatform"]}");
25 | var channel = GrpcChannel.ForAddress(_configuration["GrpcPlatform"]);
26 | var client = new GrpcPlatform.GrpcPlatformClient(channel);
27 | var request = new GetAllRequest();
28 |
29 | try
30 | {
31 | var reply = client.GetAllPlatforms(request);
32 | return _mapper.Map>(reply.Platform);
33 | }
34 | catch (Exception ex)
35 | {
36 | Console.WriteLine($"--> Couldnot call GRPC Server {ex.Message}");
37 | return null;
38 | }
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/CommandsService/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "RabbitMQHost": "localhost",
10 | "RabbitMQPort": "5672",
11 | "GrpcPlatform" : "https://localhost:5001"
12 | }
--------------------------------------------------------------------------------
/CommandsService/appsettings.Production.json:
--------------------------------------------------------------------------------
1 | {
2 | "RabbitMQHost": "rabbitmq-clusterip-srv",
3 | "RabbitMQPort": "5672",
4 | "GrpcPlatform" : "http://platforms-clusterip-srv:666"
5 | }
--------------------------------------------------------------------------------
/CommandsService/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/K8S/commands-depl.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | name: commands-depl
5 | spec:
6 | replicas: 1
7 | selector:
8 | matchLabels:
9 | app: commandservice
10 | template:
11 | metadata:
12 | labels:
13 | app: commandservice
14 | spec:
15 | containers:
16 | - name: commandservice
17 | image: binarythistle/commandservice:latest
18 | ---
19 | apiVersion: v1
20 | kind: Service
21 | metadata:
22 | name: commands-clusterip-srv
23 | spec:
24 | type: ClusterIP
25 | selector:
26 | app: commandservice
27 | ports:
28 | - name: commandservice
29 | protocol: TCP
30 | port: 80
31 | targetPort: 80
--------------------------------------------------------------------------------
/K8S/ingress-srv.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: networking.k8s.io/v1
2 | kind: Ingress
3 | metadata:
4 | name: ingress-srv
5 | annotations:
6 | kubernetes.io/ingress.class: nginx
7 | nginx.ingress.kubernetes.io/use-regex: 'true'
8 | spec:
9 | rules:
10 | - host: acme.com
11 | http:
12 | paths:
13 | - path: /api/platforms
14 | pathType: Prefix
15 | backend:
16 | service:
17 | name: platforms-clusterip-srv
18 | port:
19 | number: 80
20 | - path: /api/c/platforms
21 | pathType: Prefix
22 | backend:
23 | service:
24 | name: commands-clusterip-srv
25 | port:
26 | number: 80
27 |
28 |
--------------------------------------------------------------------------------
/K8S/local-pvc.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: PersistentVolumeClaim
3 | metadata:
4 | name: mssql-claim
5 | spec:
6 | accessModes:
7 | - ReadWriteMany
8 | resources:
9 | requests:
10 | storage: 200Mi
11 |
12 |
--------------------------------------------------------------------------------
/K8S/mssql-plat-depl.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | name: mssql-depl
5 | spec:
6 | replicas: 1
7 | selector:
8 | matchLabels:
9 | app: mssql
10 | template:
11 | metadata:
12 | labels:
13 | app: mssql
14 | spec:
15 | containers:
16 | - name: mssql
17 | image: mcr.microsoft.com/mssql/server:2017-latest
18 | ports:
19 | - containerPort: 1433
20 | env:
21 | - name: MSSQL_PID
22 | value: "Express"
23 | - name: ACCEPT_EULA
24 | value: "Y"
25 | - name: SA_PASSWORD
26 | valueFrom:
27 | secretKeyRef:
28 | name: mssql
29 | key: SA_PASSWORD
30 | volumeMounts:
31 | - mountPath: /var/opt/mssql/data
32 | name: mssqldb
33 | volumes:
34 | - name: mssqldb
35 | persistentVolumeClaim:
36 | claimName: mssql-claim
37 | ---
38 | apiVersion: v1
39 | kind: Service
40 | metadata:
41 | name: mssql-clusterip-srv
42 | spec:
43 | type: ClusterIP
44 | selector:
45 | app: mssql
46 | ports:
47 | - name: mssql
48 | protocol: TCP
49 | port: 1433
50 | targetPort: 1433
51 | ---
52 | apiVersion: v1
53 | kind: Service
54 | metadata:
55 | name: mssql-loadbalancer
56 | spec:
57 | type: LoadBalancer
58 | selector:
59 | app: mssql
60 | ports:
61 | - protocol: TCP
62 | port: 1433
63 | targetPort: 1433
--------------------------------------------------------------------------------
/K8S/platforms-depl.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | name: platforms-depl
5 | spec:
6 | replicas: 1
7 | selector:
8 | matchLabels:
9 | app: platformservice
10 | template:
11 | metadata:
12 | labels:
13 | app: platformservice
14 | spec:
15 | containers:
16 | - name: platformservice
17 | image: binarythistle/platformservice:latest
18 | ---
19 | apiVersion: v1
20 | kind: Service
21 | metadata:
22 | name: platforms-clusterip-srv
23 | spec:
24 | type: ClusterIP
25 | selector:
26 | app: platformservice
27 | ports:
28 | - name: platformservice
29 | protocol: TCP
30 | port: 80
31 | targetPort: 80
32 | - name: plafromgrpc
33 | protocol: TCP
34 | port: 666
35 | targetPort: 666
--------------------------------------------------------------------------------
/K8S/platforms-np-srv.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Service
3 | metadata:
4 | name: platformnpservice-srv
5 | spec:
6 | type: NodePort
7 | selector:
8 | app: platformservice
9 | ports:
10 | - name: platformservice
11 | protocol: TCP
12 | port: 80
13 | targetPort: 80
--------------------------------------------------------------------------------
/K8S/rabbitmq-depl.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | name: rabbitmq-depl
5 | spec:
6 | replicas: 1
7 | selector:
8 | matchLabels:
9 | app: rabbitmq
10 | template:
11 | metadata:
12 | labels:
13 | app: rabbitmq
14 | spec:
15 | containers:
16 | - name: rabbitmq
17 | image: rabbitmq:3-management
18 | ports:
19 | - containerPort: 15672
20 | name: rbmq-mgmt-port
21 | - containerPort: 5672
22 | name: rbmq-msg-port
23 | ---
24 | apiVersion: v1
25 | kind: Service
26 | metadata:
27 | name: rabbitmq-clusterip-srv
28 | spec:
29 | type: ClusterIP
30 | selector:
31 | app: rabbitmq
32 | ports:
33 | - name: rbmq-mgmt-port
34 | protocol: TCP
35 | port: 15672
36 | targetPort: 15672
37 | - name: rbmq-msg-port
38 | protocol: TCP
39 | port: 5672
40 | targetPort: 5672
41 | ---
42 | apiVersion: v1
43 | kind: Service
44 | metadata:
45 | name: rabbitmq-loadbalancer
46 | spec:
47 | type: LoadBalancer
48 | selector:
49 | app: rabbitmq
50 | ports:
51 | - name: rbmq-mgmt-port
52 | protocol: TCP
53 | port: 15672
54 | targetPort: 15672
55 | - name: rbmq-msg-port
56 | protocol: TCP
57 | port: 5672
58 | targetPort: 5672
--------------------------------------------------------------------------------
/PlatformService/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/bin/Debug/net5.0/PlatformService.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}",
16 | "stopAtEntry": false,
17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18 | "serverReadyAction": {
19 | "action": "openExternally",
20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21 | },
22 | "env": {
23 | "ASPNETCORE_ENVIRONMENT": "Development"
24 | },
25 | "sourceFileMap": {
26 | "/Views": "${workspaceFolder}/Views"
27 | }
28 | },
29 | {
30 | "name": ".NET Core Attach",
31 | "type": "coreclr",
32 | "request": "attach"
33 | }
34 | ]
35 | }
--------------------------------------------------------------------------------
/PlatformService/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/PlatformService.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/PlatformService.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/PlatformService.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/PlatformService/AsyncDataServices/IMessageBusClient.cs:
--------------------------------------------------------------------------------
1 | using PlatformService.Dtos;
2 |
3 | namespace PlatformService.AsyncDataServices
4 | {
5 | public interface IMessageBusClient
6 | {
7 | void PublishNewPlatform(PlatformPublishedDto platformPublishedDto);
8 | }
9 | }
--------------------------------------------------------------------------------
/PlatformService/AsyncDataServices/MessageBusClient.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 | using System.Text.Json;
4 | using Microsoft.Extensions.Configuration;
5 | using PlatformService.Dtos;
6 | using RabbitMQ.Client;
7 |
8 | namespace PlatformService.AsyncDataServices
9 | {
10 | public class MessageBusClient : IMessageBusClient
11 | {
12 | private readonly IConfiguration _configuration;
13 | private readonly IConnection _connection;
14 | private readonly IModel _channel;
15 |
16 | public MessageBusClient(IConfiguration configuration)
17 | {
18 | _configuration = configuration;
19 | var factory = new ConnectionFactory()
20 | {
21 | HostName = _configuration["RabbitMQHost"],
22 | Port = int.Parse(_configuration["RabbitMQPort"])
23 | };
24 | try
25 | {
26 | _connection = factory.CreateConnection();
27 | _channel = _connection.CreateModel();
28 |
29 | _channel.ExchangeDeclare(exchange: "trigger", type: ExchangeType.Fanout);
30 |
31 | _connection.ConnectionShutdown += RabbitMQ_ConnectionShutdown;
32 |
33 | Console.WriteLine("--> Connected to MessageBus");
34 |
35 | }
36 | catch (Exception ex)
37 | {
38 | Console.WriteLine($"--> Could not connect to the Message Bus: {ex.Message}");
39 | }
40 | }
41 |
42 | public void PublishNewPlatform(PlatformPublishedDto platformPublishedDto)
43 | {
44 | var message = JsonSerializer.Serialize(platformPublishedDto);
45 |
46 | if (_connection.IsOpen)
47 | {
48 | Console.WriteLine("--> RabbitMQ Connection Open, sending message...");
49 | SendMessage(message);
50 | }
51 | else
52 | {
53 | Console.WriteLine("--> RabbitMQ connectionis closed, not sending");
54 | }
55 | }
56 |
57 | private void SendMessage(string message)
58 | {
59 | var body = Encoding.UTF8.GetBytes(message);
60 |
61 | _channel.BasicPublish(exchange: "trigger",
62 | routingKey: "",
63 | basicProperties: null,
64 | body: body);
65 | Console.WriteLine($"--> We have sent {message}");
66 | }
67 |
68 | public void Dispose()
69 | {
70 | Console.WriteLine("MessageBus Disposed");
71 | if (_channel.IsOpen)
72 | {
73 | _channel.Close();
74 | _connection.Close();
75 | }
76 | }
77 |
78 | private void RabbitMQ_ConnectionShutdown(object sender, ShutdownEventArgs e)
79 | {
80 | Console.WriteLine("--> RabbitMQ Connection Shutdown");
81 | }
82 | }
83 | }
--------------------------------------------------------------------------------
/PlatformService/Controllers/PlatformsController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading.Tasks;
4 | using AutoMapper;
5 | using Microsoft.AspNetCore.Mvc;
6 | using PlatformService.AsyncDataServices;
7 | using PlatformService.Data;
8 | using PlatformService.Dtos;
9 | using PlatformService.Models;
10 | using PlatformService.SyncDataServices.Http;
11 |
12 | namespace PlatformService.Controllers
13 | {
14 | [Route("api/[controller]")]
15 | [ApiController]
16 | public class PlatformsController : ControllerBase
17 | {
18 | private readonly IPlatformRepo _repository;
19 | private readonly IMapper _mapper;
20 | private readonly ICommandDataClient _commandDataClient;
21 | private readonly IMessageBusClient _messageBusClient;
22 |
23 | public PlatformsController(
24 | IPlatformRepo repository,
25 | IMapper mapper,
26 | ICommandDataClient commandDataClient,
27 | IMessageBusClient messageBusClient)
28 | {
29 | _repository = repository;
30 | _mapper = mapper;
31 | _commandDataClient = commandDataClient;
32 | _messageBusClient = messageBusClient;
33 | }
34 |
35 | [HttpGet]
36 | public ActionResult> GetPlatforms()
37 | {
38 | Console.WriteLine("--> Getting Platforms....");
39 |
40 | var platformItem = _repository.GetAllPlatforms();
41 |
42 | return Ok(_mapper.Map>(platformItem));
43 | }
44 |
45 | [HttpGet("{id}", Name = "GetPlatformById")]
46 | public ActionResult GetPlatformById(int id)
47 | {
48 | var platformItem = _repository.GetPlatformById(id);
49 | if (platformItem != null)
50 | {
51 | return Ok(_mapper.Map(platformItem));
52 | }
53 |
54 | return NotFound();
55 | }
56 |
57 | [HttpPost]
58 | public async Task> CreatePlatform(PlatformCreateDto platformCreateDto)
59 | {
60 | var platformModel = _mapper.Map(platformCreateDto);
61 | _repository.CreatePlatform(platformModel);
62 | _repository.SaveChanges();
63 |
64 | var platformReadDto = _mapper.Map(platformModel);
65 |
66 | // Send Sync Message
67 | try
68 | {
69 | await _commandDataClient.SendPlatformToCommand(platformReadDto);
70 | }
71 | catch(Exception ex)
72 | {
73 | Console.WriteLine($"--> Could not send synchronously: {ex.Message}");
74 | }
75 |
76 | //Send Async Message
77 | try
78 | {
79 | var platformPublishedDto = _mapper.Map(platformReadDto);
80 | platformPublishedDto.Event = "Platform_Published";
81 | _messageBusClient.PublishNewPlatform(platformPublishedDto);
82 | }
83 | catch (Exception ex)
84 | {
85 | Console.WriteLine($"--> Could not send asynchronously: {ex.Message}");
86 | }
87 |
88 | return CreatedAtRoute(nameof(GetPlatformById), new { Id = platformReadDto.Id}, platformReadDto);
89 | }
90 | }
91 | }
--------------------------------------------------------------------------------
/PlatformService/Data/AppDbContext.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore;
2 | using PlatformService.Models;
3 |
4 | namespace PlatformService.Data
5 | {
6 | public class AppDbContext : DbContext
7 | {
8 | public AppDbContext(DbContextOptions opt) : base(opt)
9 | {
10 |
11 | }
12 |
13 | public DbSet Platforms { get; set; }
14 | }
15 | }
--------------------------------------------------------------------------------
/PlatformService/Data/IPlatformRepo.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using PlatformService.Models;
3 |
4 | namespace PlatformService.Data
5 | {
6 | public interface IPlatformRepo
7 | {
8 | bool SaveChanges();
9 |
10 | IEnumerable GetAllPlatforms();
11 | Platform GetPlatformById(int id);
12 | void CreatePlatform(Platform plat);
13 | }
14 | }
--------------------------------------------------------------------------------
/PlatformService/Data/PlatformRepo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using PlatformService.Models;
5 |
6 | namespace PlatformService.Data
7 | {
8 | public class PlatformRepo : IPlatformRepo
9 | {
10 | private readonly AppDbContext _context;
11 |
12 | public PlatformRepo(AppDbContext context)
13 | {
14 | _context = context;
15 | }
16 |
17 | public void CreatePlatform(Platform plat)
18 | {
19 | if(plat == null)
20 | {
21 | throw new ArgumentNullException(nameof(plat));
22 | }
23 |
24 | _context.Platforms.Add(plat);
25 | }
26 |
27 | public IEnumerable GetAllPlatforms()
28 | {
29 | return _context.Platforms.ToList();
30 | }
31 |
32 | public Platform GetPlatformById(int id)
33 | {
34 | return _context.Platforms.FirstOrDefault(p => p.Id == id);
35 | }
36 |
37 | public bool SaveChanges()
38 | {
39 | return (_context.SaveChanges() >= 0);
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/PlatformService/Data/PrepDb.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using Microsoft.AspNetCore.Builder;
4 | using Microsoft.EntityFrameworkCore;
5 | using Microsoft.Extensions.DependencyInjection;
6 | using PlatformService.Models;
7 |
8 | namespace PlatformService.Data
9 | {
10 | public static class PrepDb
11 | {
12 | public static void PrepPopulation(IApplicationBuilder app, bool isProd)
13 | {
14 | using( var serviceScope = app.ApplicationServices.CreateScope())
15 | {
16 | SeedData(serviceScope.ServiceProvider.GetService(), isProd);
17 | }
18 | }
19 |
20 | private static void SeedData(AppDbContext context, bool isProd)
21 | {
22 | if(isProd)
23 | {
24 | Console.WriteLine("--> Attempting to apply migrations...");
25 | try
26 | {
27 | context.Database.Migrate();
28 | }
29 | catch(Exception ex)
30 | {
31 | Console.WriteLine($"--> Could not run migrations: {ex.Message}");
32 | }
33 | }
34 |
35 | if(!context.Platforms.Any())
36 | {
37 | Console.WriteLine("--> Seeding Data...");
38 |
39 | context.Platforms.AddRange(
40 | new Platform() {Name="Dot Net", Publisher="Microsoft", Cost="Free"},
41 | new Platform() {Name="SQL Server Express", Publisher="Microsoft", Cost="Free"},
42 | new Platform() {Name="Kubernetes", Publisher="Cloud Native Computing Foundation", Cost="Free"}
43 | );
44 |
45 | context.SaveChanges();
46 | }
47 | else
48 | {
49 | Console.WriteLine("--> We already have data");
50 | }
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/PlatformService/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build-env
2 | WORKDIR /app
3 |
4 | COPY *.csproj ./
5 | RUN dotnet restore
6 |
7 | COPY . ./
8 | RUN dotnet publish -c Release -o out
9 |
10 | FROM mcr.microsoft.com/dotnet/aspnet:5.0
11 | WORKDIR /app
12 | COPY --from=build-env /app/out .
13 | ENTRYPOINT [ "dotnet", "PlatformService.dll" ]
--------------------------------------------------------------------------------
/PlatformService/Dtos/PlatformCreateDto.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel.DataAnnotations;
2 |
3 | namespace PlatformService.Dtos
4 | {
5 | public class PlatformCreateDto
6 | {
7 | [Required]
8 | public string Name { get; set; }
9 |
10 | [Required]
11 | public string Publisher { get; set; }
12 |
13 | [Required]
14 | public string Cost { get; set; }
15 | }
16 | }
--------------------------------------------------------------------------------
/PlatformService/Dtos/PlatformPublishedDto.cs:
--------------------------------------------------------------------------------
1 | namespace PlatformService.Dtos
2 | {
3 | public class PlatformPublishedDto
4 | {
5 | public int Id { get; set; }
6 | public string Name { get; set; }
7 | public string Event { get; set; }
8 | }
9 | }
--------------------------------------------------------------------------------
/PlatformService/Dtos/PlatformReadDto.cs:
--------------------------------------------------------------------------------
1 | namespace PlatformService.Dtos
2 | {
3 | public class PlatformReadDto
4 | {
5 | public int Id { get; set; }
6 |
7 | public string Name { get; set; }
8 |
9 | public string Publisher { get; set; }
10 |
11 | public string Cost { get; set; }
12 | }
13 | }
--------------------------------------------------------------------------------
/PlatformService/Migrations/20210811091426_initialmigration.Designer.cs:
--------------------------------------------------------------------------------
1 | //
2 | using Microsoft.EntityFrameworkCore;
3 | using Microsoft.EntityFrameworkCore.Infrastructure;
4 | using Microsoft.EntityFrameworkCore.Metadata;
5 | using Microsoft.EntityFrameworkCore.Migrations;
6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
7 | using PlatformService.Data;
8 |
9 | namespace PlatformService.Migrations
10 | {
11 | [DbContext(typeof(AppDbContext))]
12 | [Migration("20210811091426_initialmigration")]
13 | partial class initialmigration
14 | {
15 | protected override void BuildTargetModel(ModelBuilder modelBuilder)
16 | {
17 | #pragma warning disable 612, 618
18 | modelBuilder
19 | .HasAnnotation("Relational:MaxIdentifierLength", 128)
20 | .HasAnnotation("ProductVersion", "5.0.8")
21 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
22 |
23 | modelBuilder.Entity("PlatformService.Models.Platform", b =>
24 | {
25 | b.Property("Id")
26 | .ValueGeneratedOnAdd()
27 | .HasColumnType("int")
28 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
29 |
30 | b.Property("Cost")
31 | .IsRequired()
32 | .HasColumnType("nvarchar(max)");
33 |
34 | b.Property("Name")
35 | .IsRequired()
36 | .HasColumnType("nvarchar(max)");
37 |
38 | b.Property("Publisher")
39 | .IsRequired()
40 | .HasColumnType("nvarchar(max)");
41 |
42 | b.HasKey("Id");
43 |
44 | b.ToTable("Platforms");
45 | });
46 | #pragma warning restore 612, 618
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/PlatformService/Migrations/20210811091426_initialmigration.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore.Migrations;
2 |
3 | namespace PlatformService.Migrations
4 | {
5 | public partial class initialmigration : Migration
6 | {
7 | protected override void Up(MigrationBuilder migrationBuilder)
8 | {
9 | migrationBuilder.CreateTable(
10 | name: "Platforms",
11 | columns: table => new
12 | {
13 | Id = table.Column(type: "int", nullable: false)
14 | .Annotation("SqlServer:Identity", "1, 1"),
15 | Name = table.Column(type: "nvarchar(max)", nullable: false),
16 | Publisher = table.Column(type: "nvarchar(max)", nullable: false),
17 | Cost = table.Column(type: "nvarchar(max)", nullable: false)
18 | },
19 | constraints: table =>
20 | {
21 | table.PrimaryKey("PK_Platforms", x => x.Id);
22 | });
23 | }
24 |
25 | protected override void Down(MigrationBuilder migrationBuilder)
26 | {
27 | migrationBuilder.DropTable(
28 | name: "Platforms");
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/PlatformService/Migrations/AppDbContextModelSnapshot.cs:
--------------------------------------------------------------------------------
1 | //
2 | using Microsoft.EntityFrameworkCore;
3 | using Microsoft.EntityFrameworkCore.Infrastructure;
4 | using Microsoft.EntityFrameworkCore.Metadata;
5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
6 | using PlatformService.Data;
7 |
8 | namespace PlatformService.Migrations
9 | {
10 | [DbContext(typeof(AppDbContext))]
11 | partial class AppDbContextModelSnapshot : ModelSnapshot
12 | {
13 | protected override void BuildModel(ModelBuilder modelBuilder)
14 | {
15 | #pragma warning disable 612, 618
16 | modelBuilder
17 | .HasAnnotation("Relational:MaxIdentifierLength", 128)
18 | .HasAnnotation("ProductVersion", "5.0.8")
19 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
20 |
21 | modelBuilder.Entity("PlatformService.Models.Platform", b =>
22 | {
23 | b.Property("Id")
24 | .ValueGeneratedOnAdd()
25 | .HasColumnType("int")
26 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
27 |
28 | b.Property("Cost")
29 | .IsRequired()
30 | .HasColumnType("nvarchar(max)");
31 |
32 | b.Property("Name")
33 | .IsRequired()
34 | .HasColumnType("nvarchar(max)");
35 |
36 | b.Property("Publisher")
37 | .IsRequired()
38 | .HasColumnType("nvarchar(max)");
39 |
40 | b.HasKey("Id");
41 |
42 | b.ToTable("Platforms");
43 | });
44 | #pragma warning restore 612, 618
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/PlatformService/Models/Platform.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel.DataAnnotations;
2 |
3 | namespace PlatformService.Models
4 | {
5 | public class Platform
6 | {
7 | [Key]
8 | [Required]
9 | public int Id { get; set; }
10 |
11 | [Required]
12 | public string Name { get; set; }
13 |
14 | [Required]
15 | public string Publisher { get; set; }
16 |
17 | [Required]
18 | public string Cost { get; set; }
19 | }
20 | }
--------------------------------------------------------------------------------
/PlatformService/PlatformService.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | runtime; build; native; contentfiles; analyzers; buildtransitive
13 | all
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/PlatformService/Profiles/PlatformsProfile.cs:
--------------------------------------------------------------------------------
1 | using AutoMapper;
2 | using PlatformService.Dtos;
3 | using PlatformService.Models;
4 |
5 | namespace PlatformService.Profiles
6 | {
7 | public class PlatformsProfile : Profile
8 | {
9 | public PlatformsProfile()
10 | {
11 | // Source -> Target
12 | CreateMap();
13 | CreateMap();
14 | CreateMap();
15 | CreateMap()
16 | .ForMember(dest => dest.PlatformId, opt => opt.MapFrom(src =>src.Id))
17 | .ForMember(dest => dest.Name, opt => opt.MapFrom(src =>src.Name))
18 | .ForMember(dest => dest.Publisher, opt => opt.MapFrom(src =>src.Publisher));
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/PlatformService/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Hosting;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.Hosting;
8 | using Microsoft.Extensions.Logging;
9 |
10 | namespace PlatformService
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/PlatformService/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:42320",
8 | "sslPort": 44316
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "PlatformService": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/PlatformService/Protos/platforms.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | option csharp_namespace = "PlatformService";
4 |
5 | service GrpcPlatform {
6 | rpc GetAllPlatforms (GetAllRequest) returns (PlatformResponse);
7 | }
8 |
9 | message GetAllRequest {}
10 |
11 | message GrpcPlatformModel{
12 | int32 platformId = 1;
13 | string name = 2;
14 | string publisher = 3;
15 | }
16 |
17 | message PlatformResponse {
18 | repeated GrpcPlatformModel platform = 1;
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/PlatformService/Startup.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 | using Microsoft.AspNetCore.Builder;
7 | using Microsoft.AspNetCore.Hosting;
8 | using Microsoft.AspNetCore.Http;
9 | using Microsoft.AspNetCore.HttpsPolicy;
10 | using Microsoft.AspNetCore.Mvc;
11 | using Microsoft.EntityFrameworkCore;
12 | using Microsoft.Extensions.Configuration;
13 | using Microsoft.Extensions.DependencyInjection;
14 | using Microsoft.Extensions.Hosting;
15 | using Microsoft.Extensions.Logging;
16 | using Microsoft.OpenApi.Models;
17 | using PlatformService.AsyncDataServices;
18 | using PlatformService.Data;
19 | using PlatformService.SyncDataServices.Grpc;
20 | using PlatformService.SyncDataServices.Http;
21 |
22 | namespace PlatformService
23 | {
24 | public class Startup
25 | {
26 | public IConfiguration Configuration { get; }
27 | private readonly IWebHostEnvironment _env;
28 |
29 | public Startup(IConfiguration configuration, IWebHostEnvironment env)
30 | {
31 | Configuration = configuration;
32 | _env = env;
33 | }
34 |
35 |
36 | public void ConfigureServices(IServiceCollection services)
37 | {
38 | if (_env.IsProduction())
39 | {
40 | Console.WriteLine("--> Using SqlServer Db");
41 | services.AddDbContext(opt =>
42 | opt.UseSqlServer(Configuration.GetConnectionString("PlatformsConn")));
43 | }
44 | else
45 | {
46 | Console.WriteLine("--> Using InMem Db");
47 | services.AddDbContext(opt =>
48 | opt.UseInMemoryDatabase("InMem"));
49 | }
50 |
51 | services.AddScoped();
52 |
53 | services.AddHttpClient();
54 | services.AddSingleton();
55 | services.AddGrpc();
56 | services.AddControllers();
57 | services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
58 | services.AddSwaggerGen(c =>
59 | {
60 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "PlatformService", Version = "v1" });
61 | });
62 |
63 | Console.WriteLine($"--> CommandService Endpoint {Configuration["CommandService"]}");
64 |
65 | }
66 |
67 |
68 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
69 | {
70 | if (env.IsDevelopment())
71 | {
72 | app.UseDeveloperExceptionPage();
73 | app.UseSwagger();
74 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PlatformService v1"));
75 | }
76 |
77 | //app.UseHttpsRedirection();
78 |
79 | app.UseRouting();
80 |
81 | app.UseAuthorization();
82 |
83 | app.UseEndpoints(endpoints =>
84 | {
85 | endpoints.MapControllers();
86 | endpoints.MapGrpcService();
87 |
88 | endpoints.MapGet("/protos/platforms.proto", async context =>
89 | {
90 | await context.Response.WriteAsync(File.ReadAllText("Protos/platforms.proto"));
91 | });
92 | });
93 |
94 |
95 | PrepDb.PrepPopulation(app, env.IsProduction());
96 |
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/PlatformService/SyncDataServices/Grpc/GrpcPlatformService.cs:
--------------------------------------------------------------------------------
1 | using System.Threading.Tasks;
2 | using AutoMapper;
3 | using Grpc.Core;
4 | using PlatformService.Data;
5 |
6 | namespace PlatformService.SyncDataServices.Grpc
7 | {
8 | public class GrpcPlatformService : GrpcPlatform.GrpcPlatformBase
9 | {
10 | private readonly IPlatformRepo _repository;
11 | private readonly IMapper _mapper;
12 |
13 | public GrpcPlatformService(IPlatformRepo repository, IMapper mapper)
14 | {
15 | _repository = repository;
16 | _mapper = mapper;
17 | }
18 |
19 | public override Task GetAllPlatforms(GetAllRequest request, ServerCallContext context)
20 | {
21 | var response = new PlatformResponse();
22 | var platforms = _repository.GetAllPlatforms();
23 |
24 | foreach(var plat in platforms)
25 | {
26 | response.Platform.Add(_mapper.Map(plat));
27 | }
28 |
29 | return Task.FromResult(response);
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/PlatformService/SyncDataServices/Http/HttpCommandDataClient.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.Http;
3 | using System.Text;
4 | using System.Text.Json;
5 | using System.Threading.Tasks;
6 | using Microsoft.Extensions.Configuration;
7 | using PlatformService.Dtos;
8 |
9 | namespace PlatformService.SyncDataServices.Http
10 | {
11 | public class HttpCommandDataClient : ICommandDataClient
12 | {
13 | private readonly HttpClient _httpClient;
14 | private readonly IConfiguration _configuration;
15 |
16 | public HttpCommandDataClient(HttpClient httpClient, IConfiguration configuration)
17 | {
18 | _httpClient = httpClient;
19 | _configuration = configuration;
20 | }
21 |
22 |
23 | public async Task SendPlatformToCommand(PlatformReadDto plat)
24 | {
25 | var httpContent = new StringContent(
26 | JsonSerializer.Serialize(plat),
27 | Encoding.UTF8,
28 | "application/json");
29 |
30 | var response = await _httpClient.PostAsync($"{_configuration["CommandService"]}", httpContent);
31 |
32 | if(response.IsSuccessStatusCode)
33 | {
34 | Console.WriteLine("--> Sync POST to CommandService was OK!");
35 | }
36 | else
37 | {
38 | Console.WriteLine("--> Sync POST to CommandService was NOT OK!");
39 | }
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/PlatformService/SyncDataServices/Http/ICommandDataClient.cs:
--------------------------------------------------------------------------------
1 | using System.Threading.Tasks;
2 | using PlatformService.Dtos;
3 |
4 | namespace PlatformService.SyncDataServices.Http
5 | {
6 | public interface ICommandDataClient
7 | {
8 | Task SendPlatformToCommand(PlatformReadDto plat);
9 | }
10 | }
--------------------------------------------------------------------------------
/PlatformService/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "CommandService": "http://localhost:6000/api/c/platforms/",
10 | "ConnectionStrings": {
11 | "PlatformsConn": "Server=localhost,1433;Initial Catalog=platformsdb;User ID=sa;Password=pa55w0rd;"
12 | },
13 | "RabbitMQHost": "localhost",
14 | "RabbitMQPort": "5672"
15 | }
--------------------------------------------------------------------------------
/PlatformService/appsettings.Production.json:
--------------------------------------------------------------------------------
1 | {
2 | "CommandService": "http://commands-clusterip-srv:80/api/c/platforms/",
3 | "ConnectionStrings": {
4 | "PlatformsConn": "Server=mssql-clusterip-srv,1433;Initial Catalog=platformsdb;User ID=sa;Password=pa55w0rd!;"
5 | },
6 | "RabbitMQHost": "rabbitmq-clusterip-srv",
7 | "RabbitMQPort": "5672",
8 | "Kestrel": {
9 | "Endpoints": {
10 | "Grpc": {
11 | "Protocols": "Http2",
12 | "Url": "http://platforms-clusterip-srv:666"
13 | },
14 | "webApi": {
15 | "Protocols": "Http1",
16 | "Url": "http://platforms-clusterip-srv:80"
17 | }
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------