diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..1ff0c42
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..9491a2f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,363 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Oo]ut/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
\ No newline at end of file
diff --git a/ApiGateways/ZeroFramework.ReverseProxy/Program.cs b/ApiGateways/ZeroFramework.ReverseProxy/Program.cs
new file mode 100644
index 0000000..1d593e8
--- /dev/null
+++ b/ApiGateways/ZeroFramework.ReverseProxy/Program.cs
@@ -0,0 +1,6 @@
+var builder = WebApplication.CreateBuilder(args);
+builder.Services.AddReverseProxy()
+.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
+var app = builder.Build();
+app.MapReverseProxy();
+app.Run();
\ No newline at end of file
diff --git a/ApiGateways/ZeroFramework.ReverseProxy/Properties/launchSettings.json b/ApiGateways/ZeroFramework.ReverseProxy/Properties/launchSettings.json
new file mode 100644
index 0000000..707a06e
--- /dev/null
+++ b/ApiGateways/ZeroFramework.ReverseProxy/Properties/launchSettings.json
@@ -0,0 +1,28 @@
+{
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:26394",
+ "sslPort": 44338
+ }
+ },
+ "profiles": {
+ "ZeroFramework.ReverseProxy": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7117;http://localhost:5117",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/ApiGateways/ZeroFramework.ReverseProxy/ZeroFramework.ReverseProxy.csproj b/ApiGateways/ZeroFramework.ReverseProxy/ZeroFramework.ReverseProxy.csproj
new file mode 100644
index 0000000..cca003e
--- /dev/null
+++ b/ApiGateways/ZeroFramework.ReverseProxy/ZeroFramework.ReverseProxy.csproj
@@ -0,0 +1,10 @@
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
\ No newline at end of file
diff --git a/ApiGateways/ZeroFramework.ReverseProxy/appsettings.Development.json b/ApiGateways/ZeroFramework.ReverseProxy/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/ApiGateways/ZeroFramework.ReverseProxy/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/ApiGateways/ZeroFramework.ReverseProxy/appsettings.json b/ApiGateways/ZeroFramework.ReverseProxy/appsettings.json
new file mode 100644
index 0000000..4ba8f72
--- /dev/null
+++ b/ApiGateways/ZeroFramework.ReverseProxy/appsettings.json
@@ -0,0 +1,49 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*",
+ "ReverseProxy": {
+ "Routes": {
+ "identityServer": {
+ "ClusterId": "identityServer",
+ "Match": {
+ "Path": "api/identity/{**remainder}"
+ },
+ "Transforms": [
+ { "PathPattern": "api/{**remainder}" }
+ ]
+ },
+ "deviceCenter": {
+ "ClusterId": "deviceCenter",
+ "Match": {
+ "Path": "api/device/{**remainder}"
+ },
+ "Transforms": [
+ { "PathPattern": "api/{**remainder}" }
+ ]
+ }
+ },
+ "Clusters": {
+ "identityServer": {
+ "LoadBalancingPolicy": "Random",
+ "Destinations": {
+ "identityServer.server1": {
+ "Address": "https://localhost:5001"
+ }
+ }
+ },
+ "deviceCenter": {
+ "LoadBalancingPolicy": "Random",
+ "Destinations": {
+ "deviceCenter.server1": {
+ "Address": "https://localhost:6001"
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus.MemoryQueue/InMemoryEventBus.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus.MemoryQueue/InMemoryEventBus.cs
new file mode 100644
index 0000000..34caa65
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus.MemoryQueue/InMemoryEventBus.cs
@@ -0,0 +1,80 @@
+using System.Dynamic;
+using System.Text.Json;
+using ZeroFramework.EventBus.Abstractions;
+using ZeroFramework.EventBus.Events;
+
+namespace ZeroFramework.EventBus.MemoryQueue
+{
+ public class InMemoryEventBus(IEventBusSubscriptionsManager subsManager, IServiceProvider serviceProvider) : IEventBus
+ {
+ private readonly IEventBusSubscriptionsManager _subsManager = subsManager;
+
+ private readonly IServiceProvider _serviceProvider = serviceProvider;
+
+ public async Task PublishAsync(IntegrationEvent @event, CancellationToken cancellationToken = default)
+ {
+ string eventName = @event.GetType().Name;
+ string message = JsonSerializer.Serialize(@event, @event.GetType());
+ await ProcessEvent(eventName, message);
+ }
+
+ public void Subscribe() where T : IntegrationEvent where TH : IIntegrationEventHandler
+ {
+ _subsManager.AddSubscription();
+ }
+
+ public void SubscribeDynamic(string eventName) where TH : IDynamicIntegrationEventHandler
+ {
+ _subsManager.AddDynamicSubscription | (eventName);
+ }
+
+ public void Unsubscribe() where T : IntegrationEvent where TH : IIntegrationEventHandler
+ {
+ _subsManager.RemoveSubscription();
+ }
+
+ public void UnsubscribeDynamic(string eventName) where TH : IDynamicIntegrationEventHandler
+ {
+ _subsManager.RemoveDynamicSubscription | (eventName);
+ }
+
+ private async Task ProcessEvent(string eventName, string message)
+ {
+ if (_subsManager.HasSubscriptionsForEvent(eventName))
+ {
+ var subscriptions = _subsManager.GetHandlersForEvent(eventName);
+
+ foreach (var subscription in subscriptions)
+ {
+ if (subscription.IsDynamic)
+ {
+ if (_serviceProvider.GetService(subscription.HandlerType) is IDynamicIntegrationEventHandler handler)
+ {
+ dynamic? eventData = JsonSerializer.Deserialize(message);
+ await handler.HandleAsync(eventData);
+ }
+ }
+ else
+ {
+ var handler = _serviceProvider.GetService(subscription.HandlerType);
+
+ if (handler is not null)
+ {
+ var eventType = _subsManager.GetEventTypeByName(eventName);
+ object? integrationEvent = JsonSerializer.Deserialize(message, eventType);
+ var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
+
+ if (integrationEvent is not null)
+ {
+ Task? task = concreteType.GetMethod("HandleAsync")?.Invoke(handler, new object[] { integrationEvent }) as Task;
+ task ??= Task.CompletedTask;
+ await task;
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+}
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus.MemoryQueue/ZeroFramework.EventBus.MemoryQueue.csproj b/BuildingBlocks/EventBus/ZeroFramework.EventBus.MemoryQueue/ZeroFramework.EventBus.MemoryQueue.csproj
new file mode 100644
index 0000000..f4b7f33
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus.MemoryQueue/ZeroFramework.EventBus.MemoryQueue.csproj
@@ -0,0 +1,10 @@
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/DefaultRabbitMQPersistentConnection.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/DefaultRabbitMQPersistentConnection.cs
new file mode 100644
index 0000000..402dbbf
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/DefaultRabbitMQPersistentConnection.cs
@@ -0,0 +1,138 @@
+using Microsoft.Extensions.Logging;
+using RabbitMQ.Client;
+using RabbitMQ.Client.Events;
+using RabbitMQ.Client.Exceptions;
+using System.Net.Sockets;
+
+namespace ZeroFramework.EventBus.RabbitMQ
+{
+ public class DefaultRabbitMQPersistentConnection(IConnectionFactory connectionFactory, ILogger logger, int retryCount = 5) : IRabbitMQPersistentConnection
+ {
+ private readonly IConnectionFactory _connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
+
+ private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+
+ private readonly int _retryCount = retryCount;
+
+ private IConnection? _connection = null;
+
+ readonly object _syncRoot = new();
+
+ public bool IsConnected => _connection != null && _connection.IsOpen && !_disposed;
+
+ public IModel CreateModel()
+ {
+ if (!IsConnected || _connection is null)
+ {
+ throw new InvalidOperationException("No RabbitMQ connections are available to perform this action");
+ }
+
+ return _connection.CreateModel();
+ }
+
+ public bool TryConnect()
+ {
+ _logger.LogInformation("RabbitMQ Client is trying to connect");
+
+ lock (_syncRoot)
+ {
+ for (int retryAttempt = 1; retryAttempt <= _retryCount; retryAttempt++)
+ {
+ var time = TimeSpan.FromSeconds(Math.Pow(2, retryAttempt));
+
+ try
+ {
+ _connection = _connectionFactory.CreateConnection();
+ break;
+ }
+ catch (SystemException ex) when (ex is BrokerUnreachableException || ex is SocketException)
+ {
+ _logger.LogWarning(ex, "RabbitMQ Client could not connect after {TimeOut}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message);
+ }
+
+ Task.Delay(time).Wait();
+ }
+
+ if (IsConnected && _connection is not null)
+ {
+ _connection.ConnectionShutdown += OnConnectionShutdown!;
+ _connection.CallbackException += OnCallbackException!;
+ _connection.ConnectionBlocked += OnConnectionBlocked!;
+
+ _logger.LogInformation("RabbitMQ Client acquired a persistent connection to '{HostName}' and is subscribed to failure events", _connection.Endpoint.HostName);
+
+ return true;
+ }
+ else
+ {
+ _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");
+
+ return false;
+ }
+ }
+ }
+
+ private void OnConnectionBlocked(object sender, ConnectionBlockedEventArgs e)
+ {
+ if (_disposed) return;
+
+ _logger.LogWarning("A RabbitMQ connection is shutdown. Trying to re-connect...");
+
+ TryConnect();
+ }
+
+ void OnCallbackException(object sender, CallbackExceptionEventArgs e)
+ {
+ if (_disposed) return;
+
+ _logger.LogWarning("A RabbitMQ connection throw exception. Trying to re-connect...");
+
+ TryConnect();
+ }
+
+ void OnConnectionShutdown(object sender, ShutdownEventArgs reason)
+ {
+ if (_disposed) return;
+
+ _logger.LogWarning("A RabbitMQ connection is on shutdown. Trying to re-connect...");
+
+ TryConnect();
+ }
+
+ private bool _disposed;
+
+ // Protected implementation of Dispose pattern.
+ //https://docs.microsoft.com/zh-cn/dotnet/standard/garbage-collection/implementing-dispose
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ // Release any managed resources here.
+ if (disposing)
+ {
+ // dispose managed state (managed objects).
+ _connection?.Dispose();
+ }
+
+ // free unmanaged resources (unmanaged objects) and override a finalizer below.
+ // set large fields to null.
+
+ _disposed = true;
+
+ // Call the base class implementation.
+ //base.Dispose(disposing);
+ }
+
+ // Public implementation of Dispose pattern callable by consumers.
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ ~DefaultRabbitMQPersistentConnection() => Dispose(false);
+ }
+}
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/EventBusRabbitMQ.cs
new file mode 100644
index 0000000..7492624
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/EventBusRabbitMQ.cs
@@ -0,0 +1,300 @@
+using Microsoft.Extensions.Logging;
+using RabbitMQ.Client;
+using RabbitMQ.Client.Events;
+using RabbitMQ.Client.Exceptions;
+using System.Dynamic;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.Json;
+using ZeroFramework.EventBus.Abstractions;
+using ZeroFramework.EventBus.Events;
+using ZeroFramework.EventBus.Extensions;
+
+namespace ZeroFramework.EventBus.RabbitMQ
+{
+ public class EventBusRabbitMQ : IEventBus, IDisposable
+ {
+ const string ExchangeName = "my_event_bus";
+
+ private readonly IRabbitMQPersistentConnection _persistentConnection;
+ private readonly ILogger _logger;
+ private readonly IEventBusSubscriptionsManager _subsManager;
+ private readonly IServiceProvider _serviceProvider;
+ private readonly int _retryCount;
+
+ private IModel _consumerChannel;
+ private string? _queueName;
+
+ public EventBusRabbitMQ(IRabbitMQPersistentConnection persistentConnection, ILogger logger, IServiceProvider serviceProvider, IEventBusSubscriptionsManager subsManager, string? queueName, int retryCount = 5)
+ {
+ _persistentConnection = persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection));
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ _subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager();
+ _queueName = queueName;
+ _consumerChannel = CreateConsumerChannel();
+ _serviceProvider = serviceProvider;
+ _retryCount = retryCount;
+ _subsManager.OnEventRemoved += SubsManager_OnEventRemoved!;
+ }
+
+ private void SubsManager_OnEventRemoved(object sender, string eventName)
+ {
+ if (!_persistentConnection.IsConnected)
+ {
+ _persistentConnection.TryConnect();
+ }
+
+ using var channel = _persistentConnection.CreateModel();
+ channel.QueueUnbind(queue: _queueName, exchange: ExchangeName, routingKey: eventName);
+
+ if (_subsManager.IsEmpty)
+ {
+ _queueName = string.Empty;
+ _consumerChannel.Close();
+ }
+ }
+
+ public Task PublishAsync(IntegrationEvent @event, CancellationToken cancellationToken = default)
+ {
+ if (!_persistentConnection.IsConnected)
+ {
+ _persistentConnection.TryConnect();
+ }
+
+ var eventName = @event.GetType().Name;
+
+ _logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", @event.Id, eventName);
+
+ using var channel = _persistentConnection.CreateModel();
+ _logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id);
+
+ channel.ExchangeDeclare(exchange: ExchangeName, type: ExchangeType.Direct);
+
+ var message = JsonSerializer.Serialize(@event, @event.GetType());
+ var body = Encoding.UTF8.GetBytes(message);
+
+ for (int retryAttempt = 1; retryAttempt <= _retryCount; retryAttempt++)
+ {
+ var time = TimeSpan.FromSeconds(Math.Pow(2, retryAttempt));
+
+ try
+ {
+ var properties = channel.CreateBasicProperties();
+ properties.DeliveryMode = 2; // persistent
+
+ _logger.LogTrace("Publishing event to RabbitMQ: {EventId}", @event.Id);
+
+ channel.BasicPublish(exchange: ExchangeName, routingKey: eventName, mandatory: true, basicProperties: properties, body: body);
+
+ break;
+ }
+ catch (SystemException ex) when (ex is BrokerUnreachableException || ex is SocketException)
+ {
+ _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message);
+ }
+
+ Task.Delay(time, cancellationToken).Wait(cancellationToken);
+ }
+
+ return Task.CompletedTask;
+ }
+
+ public void SubscribeDynamic(string eventName) where TH : IDynamicIntegrationEventHandler
+ {
+ _logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, typeof(TH).GetGenericTypeName());
+
+ DoInternalSubscription(eventName);
+ _subsManager.AddDynamicSubscription | (eventName);
+ StartBasicConsume();
+ }
+
+ public void Subscribe() where T : IntegrationEvent where TH : IIntegrationEventHandler
+ {
+ var eventName = _subsManager.GetEventKey();
+ DoInternalSubscription(eventName);
+
+ _logger.LogInformation("Subscribing to event {EventName} with {EventHandler}", eventName, typeof(TH).GetGenericTypeName());
+
+ _subsManager.AddSubscription();
+ StartBasicConsume();
+ }
+
+ private void DoInternalSubscription(string eventName)
+ {
+ var containsKey = _subsManager.HasSubscriptionsForEvent(eventName);
+ if (!containsKey)
+ {
+ if (!_persistentConnection.IsConnected)
+ {
+ _persistentConnection.TryConnect();
+ }
+
+ using var channel = _persistentConnection.CreateModel();
+ channel.QueueBind(queue: _queueName, exchange: ExchangeName, routingKey: eventName);
+ }
+ }
+
+ public void Unsubscribe() where T : IntegrationEvent where TH : IIntegrationEventHandler
+ {
+ var eventName = _subsManager.GetEventKey();
+
+ _logger.LogInformation("Unsubscribing from event {EventName}", eventName);
+
+ _subsManager.RemoveSubscription();
+ }
+
+ public void UnsubscribeDynamic(string eventName) where TH : IDynamicIntegrationEventHandler
+ {
+ _subsManager.RemoveDynamicSubscription | (eventName);
+ }
+
+ private bool disposed = false;
+
+ // Protected implementation of Dispose pattern.
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposed)
+ {
+ return;
+ }
+
+ // Release any managed resources here.
+ if (disposing)
+ {
+ // dispose managed state (managed objects).
+ _consumerChannel?.Dispose();
+ _subsManager.Clear();
+ }
+
+ // free unmanaged resources (unmanaged objects) and override a finalizer below.
+ // set large fields to null.
+
+ disposed = true;
+
+ // Call the base class implementation.
+ //base.Dispose(disposing);
+ }
+
+ // Public implementation of Dispose pattern callable by consumers.
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ ~EventBusRabbitMQ() => Dispose(false);
+
+ private void StartBasicConsume()
+ {
+ _logger.LogTrace("Starting RabbitMQ basic consume");
+
+ if (_consumerChannel != null)
+ {
+ var consumer = new AsyncEventingBasicConsumer(_consumerChannel);
+
+ consumer.Received += Consumer_Received;
+
+ _consumerChannel.BasicConsume(queue: _queueName, autoAck: false, consumer: consumer);
+ }
+ else
+ {
+ _logger.LogError("StartBasicConsume can't call on _consumerChannel == null");
+ }
+ }
+
+ private async Task Consumer_Received(object sender, BasicDeliverEventArgs eventArgs)
+ {
+ var eventName = eventArgs.RoutingKey;
+ var message = Encoding.UTF8.GetString(eventArgs.Body.ToArray());
+
+ try
+ {
+ if (message.ToLowerInvariant().Contains("throw-fake-exception"))
+ {
+ throw new InvalidOperationException($"Fake exception requested: \"{message}\"");
+ }
+
+ await ProcessEvent(eventName, message);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "----- ERROR Processing message \"{Message}\"", message);
+ }
+
+ // Even on exception we take the message off the queue.
+ // in a REAL WORLD app this should be handled with a Dead Letter Exchange (DLX).
+ // For more information see: https://www.rabbitmq.com/dlx.html
+ _consumerChannel.BasicAck(eventArgs.DeliveryTag, multiple: false);
+ }
+
+ private IModel CreateConsumerChannel()
+ {
+ if (!_persistentConnection.IsConnected)
+ {
+ _persistentConnection.TryConnect();
+ }
+
+ _logger.LogTrace("Creating RabbitMQ consumer channel");
+
+ var channel = _persistentConnection.CreateModel();
+
+ channel.ExchangeDeclare(exchange: ExchangeName, type: ExchangeType.Direct);
+
+ channel.QueueDeclare(queue: _queueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
+
+ channel.CallbackException += (sender, ea) =>
+ {
+ _logger.LogWarning(ea.Exception, "Recreating RabbitMQ consumer channel");
+
+ _consumerChannel.Dispose();
+ _consumerChannel = CreateConsumerChannel();
+ StartBasicConsume();
+ };
+
+ return channel;
+ }
+
+ private async Task ProcessEvent(string eventName, string message)
+ {
+ _logger.LogTrace("Processing RabbitMQ event: {EventName}", eventName);
+
+ if (_subsManager.HasSubscriptionsForEvent(eventName))
+ {
+ var subscriptions = _subsManager.GetHandlersForEvent(eventName);
+
+ foreach (var subscription in subscriptions)
+ {
+ if (subscription.IsDynamic)
+ {
+ if (_serviceProvider.GetService(subscription.HandlerType) is IDynamicIntegrationEventHandler handler)
+ {
+ dynamic? eventData = JsonSerializer.Deserialize(message);
+ await handler.HandleAsync(eventData);
+ }
+ }
+ else
+ {
+ var handler = _serviceProvider.GetService(subscription.HandlerType);
+
+ if (handler is not null)
+ {
+ var eventType = _subsManager.GetEventTypeByName(eventName);
+ object? integrationEvent = JsonSerializer.Deserialize(message, eventType);
+ var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
+ if (integrationEvent is not null)
+ {
+ Task? task = concreteType.GetMethod("HandleAsync")?.Invoke(handler, new object[] { integrationEvent }) as Task;
+ task ??= Task.CompletedTask;
+ await task;
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ _logger.LogWarning("No subscription for RabbitMQ event: {EventName}", eventName);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/IRabbitMQPersistentConnection.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/IRabbitMQPersistentConnection.cs
new file mode 100644
index 0000000..875157a
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/IRabbitMQPersistentConnection.cs
@@ -0,0 +1,13 @@
+using RabbitMQ.Client;
+
+namespace ZeroFramework.EventBus.RabbitMQ
+{
+ public interface IRabbitMQPersistentConnection : IDisposable
+ {
+ bool IsConnected { get; }
+
+ bool TryConnect();
+
+ IModel CreateModel();
+ }
+}
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/ZeroFramework.EventBus.RabbitMQ.csproj b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/ZeroFramework.EventBus.RabbitMQ.csproj
new file mode 100644
index 0000000..ec65ee6
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus.RabbitMQ/ZeroFramework.EventBus.RabbitMQ.csproj
@@ -0,0 +1,14 @@
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IDynamicIntegrationEventHandler.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IDynamicIntegrationEventHandler.cs
new file mode 100644
index 0000000..11d2e0c
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IDynamicIntegrationEventHandler.cs
@@ -0,0 +1,7 @@
+namespace ZeroFramework.EventBus.Abstractions
+{
+ public interface IDynamicIntegrationEventHandler : IIntegrationEventHandler
+ {
+ Task HandleAsync(dynamic eventData);
+ }
+}
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IEventBus.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IEventBus.cs
new file mode 100644
index 0000000..e1c76d3
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IEventBus.cs
@@ -0,0 +1,17 @@
+using ZeroFramework.EventBus.Events;
+
+namespace ZeroFramework.EventBus.Abstractions
+{
+ public interface IEventBus
+ {
+ Task PublishAsync(IntegrationEvent @event, CancellationToken cancellationToken = default);
+
+ void Subscribe() where T : IntegrationEvent where TH : IIntegrationEventHandler;
+
+ void Unsubscribe() where T : IntegrationEvent where TH : IIntegrationEventHandler;
+
+ void SubscribeDynamic(string eventName) where TH : IDynamicIntegrationEventHandler;
+
+ void UnsubscribeDynamic | (string eventName) where TH : IDynamicIntegrationEventHandler;
+ }
+}
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IIntegrationEventHandler.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IIntegrationEventHandler.cs
new file mode 100644
index 0000000..863195a
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Abstractions/IIntegrationEventHandler.cs
@@ -0,0 +1,11 @@
+using ZeroFramework.EventBus.Events;
+
+namespace ZeroFramework.EventBus.Abstractions
+{
+ public interface IIntegrationEventHandler { }
+
+ public interface IIntegrationEventHandler : IIntegrationEventHandler where TIntegrationEvent : IntegrationEvent
+ {
+ Task HandleAsync(TIntegrationEvent @event);
+ }
+}
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/Events/IntegrationEvent.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Events/IntegrationEvent.cs
new file mode 100644
index 0000000..47040ed
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Events/IntegrationEvent.cs
@@ -0,0 +1,21 @@
+namespace ZeroFramework.EventBus.Events
+{
+ public class IntegrationEvent
+ {
+ public IntegrationEvent()
+ {
+ Id = Guid.NewGuid();
+ CreationTime = DateTimeOffset.Now;
+ }
+
+ public IntegrationEvent(Guid id, DateTime createDate)
+ {
+ Id = id;
+ CreationTime = createDate;
+ }
+
+ public Guid Id { get; set; }
+
+ public DateTimeOffset CreationTime { get; set; }
+ }
+}
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/Extensions/GenericTypeExtensions.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Extensions/GenericTypeExtensions.cs
new file mode 100644
index 0000000..99d7b5e
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/Extensions/GenericTypeExtensions.cs
@@ -0,0 +1,27 @@
+namespace ZeroFramework.EventBus.Extensions
+{
+ public static class GenericTypeExtensions
+ {
+ public static string GetGenericTypeName(this Type type)
+ {
+ var typeName = string.Empty;
+
+ if (type.IsGenericType)
+ {
+ var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
+ typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
+ }
+ else
+ {
+ typeName = type.Name;
+ }
+
+ return typeName;
+ }
+
+ public static string GetGenericTypeName(this object @object)
+ {
+ return @object.GetType().GetGenericTypeName();
+ }
+ }
+}
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/IEventBusSubscriptionsManager.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/IEventBusSubscriptionsManager.cs
new file mode 100644
index 0000000..4e4b702
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/IEventBusSubscriptionsManager.cs
@@ -0,0 +1,35 @@
+using ZeroFramework.EventBus.Abstractions;
+using ZeroFramework.EventBus.Events;
+using static ZeroFramework.EventBus.InMemoryEventBusSubscriptionsManager;
+
+namespace ZeroFramework.EventBus
+{
+ public interface IEventBusSubscriptionsManager
+ {
+ bool IsEmpty { get; }
+
+ event EventHandler OnEventRemoved;
+
+ void AddDynamicSubscription(string eventName) where TH : IDynamicIntegrationEventHandler;
+
+ void RemoveDynamicSubscription | (string eventName) where TH : IDynamicIntegrationEventHandler;
+
+ void AddSubscription() where T : IntegrationEvent where TH : IIntegrationEventHandler;
+
+ void RemoveSubscription() where TH : IIntegrationEventHandler where T : IntegrationEvent;
+
+ bool HasSubscriptionsForEvent() where T : IntegrationEvent;
+
+ bool HasSubscriptionsForEvent(string eventName);
+
+ Type GetEventTypeByName(string eventName);
+
+ void Clear();
+
+ IEnumerable GetHandlersForEvent() where T : IntegrationEvent;
+
+ IEnumerable GetHandlersForEvent(string eventName);
+
+ string GetEventKey();
+ }
+}
\ No newline at end of file
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/InMemoryEventBusSubscriptionsManager.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/InMemoryEventBusSubscriptionsManager.cs
new file mode 100644
index 0000000..c6eb402
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/InMemoryEventBusSubscriptionsManager.cs
@@ -0,0 +1,147 @@
+using ZeroFramework.EventBus.Abstractions;
+using ZeroFramework.EventBus.Events;
+
+namespace ZeroFramework.EventBus
+{
+ public partial class InMemoryEventBusSubscriptionsManager : IEventBusSubscriptionsManager
+ {
+ private readonly Dictionary> _handlers;
+
+ private readonly List _eventTypes;
+
+ public event EventHandler? OnEventRemoved;
+
+ public InMemoryEventBusSubscriptionsManager()
+ {
+ _handlers = [];
+ _eventTypes = [];
+ }
+
+ public bool IsEmpty => !_handlers.Keys.Any();
+
+ public void Clear() => _handlers.Clear();
+
+ public void AddDynamicSubscription(string eventName) where TH : IDynamicIntegrationEventHandler
+ {
+ DoAddSubscription(typeof(TH), eventName, isDynamic: true);
+ }
+
+ public void AddSubscription() where T : IntegrationEvent where TH : IIntegrationEventHandler
+ {
+ var eventName = GetEventKey();
+
+ DoAddSubscription(typeof(TH), eventName, isDynamic: false);
+
+ if (!_eventTypes.Contains(typeof(T)))
+ {
+ _eventTypes.Add(typeof(T));
+ }
+ }
+
+ private void DoAddSubscription(Type handlerType, string eventName, bool isDynamic)
+ {
+ if (!HasSubscriptionsForEvent(eventName))
+ {
+ _handlers.Add(eventName, []);
+ }
+
+ if (_handlers[eventName].Any(s => s.HandlerType == handlerType))
+ {
+ throw new ArgumentException($"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType));
+ }
+
+ if (isDynamic)
+ {
+ _handlers[eventName].Add(SubscriptionInfo.Dynamic(handlerType));
+ }
+ else
+ {
+ _handlers[eventName].Add(SubscriptionInfo.Typed(handlerType));
+ }
+ }
+
+ public void RemoveDynamicSubscription(string eventName) where TH : IDynamicIntegrationEventHandler
+ {
+ var handlerToRemove = FindDynamicSubscriptionToRemove | (eventName);
+ if (handlerToRemove is not null)
+ {
+ DoRemoveHandler(eventName, handlerToRemove);
+ }
+ }
+
+ public void RemoveSubscription() where TH : IIntegrationEventHandler where T : IntegrationEvent
+ {
+ var handlerToRemove = FindSubscriptionToRemove();
+ var eventName = GetEventKey();
+ if (handlerToRemove is not null)
+ {
+ DoRemoveHandler(eventName, handlerToRemove);
+ }
+ }
+
+ private void DoRemoveHandler(string eventName, SubscriptionInfo subsToRemove)
+ {
+ if (subsToRemove != null)
+ {
+ _handlers[eventName].Remove(subsToRemove);
+ if (!_handlers[eventName].Any())
+ {
+ _handlers.Remove(eventName);
+ var eventType = _eventTypes.SingleOrDefault(e => e.Name == eventName);
+ if (eventType != null)
+ {
+ _eventTypes.Remove(eventType);
+ }
+ RaiseOnEventRemoved(eventName);
+ }
+ }
+ }
+
+ public IEnumerable GetHandlersForEvent() where T : IntegrationEvent
+ {
+ var key = GetEventKey();
+ return GetHandlersForEvent(key);
+ }
+
+ public IEnumerable GetHandlersForEvent(string eventName) => _handlers[eventName];
+
+ private void RaiseOnEventRemoved(string eventName)
+ {
+ var handler = OnEventRemoved;
+ handler?.Invoke(this, eventName);
+ }
+
+ private SubscriptionInfo? FindDynamicSubscriptionToRemove(string eventName) where TH : IDynamicIntegrationEventHandler
+ {
+ return DoFindSubscriptionToRemove(eventName, typeof(TH));
+ }
+
+ private SubscriptionInfo? FindSubscriptionToRemove() where T : IntegrationEvent where TH : IIntegrationEventHandler
+ {
+ var eventName = GetEventKey();
+ return DoFindSubscriptionToRemove(eventName, typeof(TH));
+ }
+
+ private SubscriptionInfo? DoFindSubscriptionToRemove(string eventName, Type handlerType)
+ {
+ if (HasSubscriptionsForEvent(eventName))
+ {
+ return _handlers[eventName].Single(s => s.HandlerType == handlerType);
+ }
+
+ return null;
+ }
+
+ public bool HasSubscriptionsForEvent() where T : IntegrationEvent
+ {
+ var key = GetEventKey();
+ return HasSubscriptionsForEvent(key);
+ }
+
+ public bool HasSubscriptionsForEvent(string eventName) => _handlers.ContainsKey(eventName);
+
+ public Type GetEventTypeByName(string eventName) => _eventTypes.Single(t => t.Name == eventName);
+
+ public string GetEventKey() => typeof(T).Name;
+ }
+}
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/SubscriptionInfo.cs b/BuildingBlocks/EventBus/ZeroFramework.EventBus/SubscriptionInfo.cs
new file mode 100644
index 0000000..8da78b0
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/SubscriptionInfo.cs
@@ -0,0 +1,28 @@
+namespace ZeroFramework.EventBus
+{
+ public partial class InMemoryEventBusSubscriptionsManager : IEventBusSubscriptionsManager
+ {
+ public class SubscriptionInfo
+ {
+ public bool IsDynamic { get; }
+
+ public Type HandlerType { get; }
+
+ private SubscriptionInfo(bool isDynamic, Type handlerType)
+ {
+ IsDynamic = isDynamic;
+ HandlerType = handlerType;
+ }
+
+ public static SubscriptionInfo Dynamic(Type handlerType)
+ {
+ return new SubscriptionInfo(true, handlerType);
+ }
+
+ public static SubscriptionInfo Typed(Type handlerType)
+ {
+ return new SubscriptionInfo(false, handlerType);
+ }
+ }
+ }
+}
diff --git a/BuildingBlocks/EventBus/ZeroFramework.EventBus/ZeroFramework.EventBus.csproj b/BuildingBlocks/EventBus/ZeroFramework.EventBus/ZeroFramework.EventBus.csproj
new file mode 100644
index 0000000..a6b9113
--- /dev/null
+++ b/BuildingBlocks/EventBus/ZeroFramework.EventBus/ZeroFramework.EventBus.csproj
@@ -0,0 +1,7 @@
+
+
+ net8.0
+ enable
+ enable
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..de6c3ef
--- /dev/null
+++ b/README.md
@@ -0,0 +1,109 @@
+
+ ♥ 项目基本介绍
+
+零度框架是一套基于微服务和领域模型驱动设计的企业级快速开发框架,基于微软 .NET 7+ 最新技术栈构建,容器化微服务最佳实践,零度框架的搭建以开发简单,多屏体验,前后端分离,灵活部署,最少依赖,最新框架为原则,以物联网平台管理系统为业务模型,参考诸多优秀开源框架,采用主流稳定的技术栈,从零开始搭建企业级架构。
+
+后端技术:Visual Studio 2022 + C# 12.0 + .NET 8.0 + ASP.NET Core + EF Core
+
+前端技术:Visual Studio Code + Node.js + TypeScript + React + ANTD
+
+视频教程:https://www.xcode.me/Training/Module/250
+
+演示地址:https://cloud.helloworldnet.com
+
+演示账号:用户名 admin 密码 guest
+
+[]
+
+ ♥ 在 Visual Studio 2022 中运行后端微服务
+
+1、首先使用 EF Code First 使用代码生成数据库,为了简化操作,以下脚本可完成数据库删除创建迁移并重建数据库,在 Visual Studio 选择「工具」->「NuGet包管理器」->「程序包管理控制台」中执行以下命令即可:
+
+Drop-Database -Context DeviceCenterDbContext -Project ZeroFramework.DeviceCenter.Infrastructure -StartupProject ZeroFramework.DeviceCenter.Infrastructure -Confirm:$false
+Drop-Database -Context ApplicationDbContext -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API -Confirm:$false
+
+Remove-Migration -Context PersistedGrantDbContext -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Remove-Migration -Context ConfigurationDbContext -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Remove-Migration -Context ApplicationDbContext -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Remove-Migration -Context DeviceCenterDbContext -Project ZeroFramework.DeviceCenter.Infrastructure -StartupProject ZeroFramework.DeviceCenter.Infrastructure
+
+Add-Migration InitialCreate -c PersistedGrantDbContext -o Migrations/PersistedGrantMigrations -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Add-Migration InitialCreate -c ConfigurationDbContext -o Migrations/ConfigurationMigrations -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Add-Migration InitialCreate -c ApplicationDbContext -o Migrations/ApplicationMigrations -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Add-Migration InitialCreate -Context DeviceCenterDbContext -Project ZeroFramework.DeviceCenter.Infrastructure -StartupProject ZeroFramework.DeviceCenter.Infrastructure
+
+Update-Database -Context PersistedGrantDbContext -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Update-Database -Context ConfigurationDbContext -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Update-Database -Context ApplicationDbContext -Project ZeroFramework.IdentityServer.API -StartupProject ZeroFramework.IdentityServer.API
+Update-Database -Context DeviceCenterDbContext -Project ZeroFramework.DeviceCenter.Infrastructure -StartupProject ZeroFramework.DeviceCenter.Infrastructure
+
+2、设备数据通过「分桶模式」存储在 Mongdb 数据库中,因此你需要安装并启动 Mongdb 数据库,并在配置文件中修改连接字符串。
+
+3、依次启动 ZeroFramework.IdentityServer.API 和 ZeroFramework.DeviceCenter.API 项目,容器、网关和聚合可暂时不配置,后期根据需要进行配置。
+
+
+ ♥ 在 Visual Studio Code 中运行前端站点
+
+1、首先确保系统已安装 Visual Studio Code 工具和 Node.js 环境,并进入 ZeroFramework.DeviceCenter.Web 目录。
+
+2、在目录启动命令行并运行:「npm install --global yarn」 和 「yarn install」 即可安装前端所需的 NPM 包,如果失败,可重试几次。
+
+3、在目录启动命令行并运行:「npm run dev」即可启动编译,使用 「npm run build 」编译会生成 dist 目录,该目录可直接部署到生产平台。
+
+
+ ♥ 项目更新记录
+
++ 所有项目框架及其用到的包已经升级到 .NET 7 最新版,并消除了很多警告和建议。
+
++ 在配置文件中添加了 「"UseDemoLaunchMode": true」以表示以演示模式运行,演示模式使用 EF Core 拦截器禁用了编辑和删除操作。
+
+
+ ♥ 项目目录结构说明
+
+zeroframework「项目总目录」
+├── ApiGateways「网关和聚合」
+│ └── ZeroFramework.ReverseProxy「网关与反向代理」
+│ ├── Program.cs
+│ ├── Properties
+│ ├── ZeroFramework.ReverseProxy.csproj
+│ ├── appsettings.Development.json
+│ ├── appsettings.json
+│ ├── bin
+│ └── obj
+├── BuildingBlocks「公共中间件」
+│ └── EventBus
+│ ├── ZeroFramework.EventBus「事件总线抽象」
+│ ├── ZeroFramework.EventBus.MemoryQueue「基于内存的队列」
+│ └── ZeroFramework.EventBus.RabbitMQ「分布式队列」
+├── Services「微服务」
+│ ├── DeviceCenter「基于领域驱动的设备中心微服务」
+│ │ ├── ZeroFramework.DeviceCenter.API「开放接口」
+│ │ ├── ZeroFramework.DeviceCenter.Application「应用层」
+│ │ ├── ZeroFramework.DeviceCenter.BackgroundTasks「生成演示」
+│ │ ├── ZeroFramework.DeviceCenter.Domain「领域层」
+│ │ └── ZeroFramework.DeviceCenter.Infrastructure「基础设施层」
+│ └── Identity「认证和授权微服务」
+│ └── ZeroFramework.IdentityServer.API「OAuth2.0开放接口」
+├── Web
+│ └── ZeroFramework.DeviceCenter.Web「基于 ANTD 的前端站点」
+│ ├── README.md
+│ ├── ZeroFramework.DeviceCenter.Web.esproj
+│ ├── config
+│ ├── jest.config.js
+│ ├── jsconfig.json
+│ ├── mock
+│ ├── nuget.config
+│ ├── package.json
+│ ├── public
+│ ├── src
+│ ├── tests
+│ └── tsconfig.json
+└── ZeroFramework.sln「解决方案」
+
+♥ 前端学习技术资料整理
+
+TypeScript:http://www.patrickzhong.com/TypeScript
+React:https://react.docschina.org/docs/getting-started.html
+ECMAScript:https://es6.ruanyifeng.com
+ANTD:https://ant.design/docs/react/introduce-cn
+ANTD PRO:https://pro.ant.design/zh-CN/docs/overview
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/.config/dotnet-tools.json b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/.config/dotnet-tools.json
new file mode 100644
index 0000000..23f4f07
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/.config/dotnet-tools.json
@@ -0,0 +1,12 @@
+{
+ "version": 1,
+ "isRoot": true,
+ "tools": {
+ "dotnet-ef": {
+ "version": "6.0.3",
+ "commands": [
+ "dotnet-ef"
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Constants/TenantClaimTypes.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Constants/TenantClaimTypes.cs
new file mode 100644
index 0000000..dff1571
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Constants/TenantClaimTypes.cs
@@ -0,0 +1,9 @@
+namespace ZeroFramework.DeviceCenter.API.Constants
+{
+ public class TenantClaimTypes
+ {
+ public const string TenantId = "tenant_id";
+
+ public const string TenantName = "tenant_name";
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ConfigurationsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ConfigurationsController.cs
new file mode 100644
index 0000000..71b1720
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ConfigurationsController.cs
@@ -0,0 +1,181 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Localization;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Options;
+using System.Globalization;
+using System.Reflection;
+using System.Text.RegularExpressions;
+using ZeroFramework.DeviceCenter.Application.Services.Permissions;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ [Authorize]
+ public class ConfigurationsController(ILogger logger,
+ IHttpContextAccessor httpContextAccessor,
+ IOptions authorizationOptions,
+ IOptions requestLocalizationOptions,
+ IPermissionDefinitionManager permissionDefinitionManager,
+ IPermissionChecker permissionChecker,
+ IAuthorizationService authorizationService,
+ IStringLocalizerFactory stringLocalizerFactory) : ControllerBase
+ {
+ private readonly ILogger _logger = logger ?? NullLogger.Instance;
+ private readonly AuthorizationOptions _authorizationOptions = authorizationOptions.Value;
+ private readonly RequestLocalizationOptions _requestLocalizationOptions = requestLocalizationOptions.Value;
+ private readonly IPermissionDefinitionManager _permissionDefinitionManager = permissionDefinitionManager;
+ private readonly IPermissionChecker _permissionChecker = permissionChecker;
+ private readonly IAuthorizationService _authorizationService = authorizationService;
+ private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor;
+ private readonly IStringLocalizerFactory _stringLocalizerFactory = stringLocalizerFactory;
+
+ [HttpGet]
+ [AllowAnonymous]
+ public async Task GetAsync()
+ {
+ _logger.LogDebug("Executing ConfigurationApplicationService.GetAsync()...");
+
+ var result = new ApplicationConfiguration
+ {
+ Permissions = await GetPermissionConfigurationAsync()
+ };
+
+ _logger.LogDebug("Executed ConfigurationApplicationService.GetAsync().");
+
+ return result;
+ }
+
+ [Serializable]
+ public class ApplicationConfiguration
+ {
+ public PermissionConfiguration? Permissions { get; set; }
+
+ public LocalizationConfiguration? Localizations { get; set; }
+ }
+
+ [Serializable]
+ public class PermissionConfiguration
+ {
+ public Dictionary Policies { get; set; }
+
+ public Dictionary GrantedPolicies { get; set; }
+
+ public PermissionConfiguration()
+ {
+ Policies = [];
+ GrantedPolicies = [];
+ }
+ }
+
+ [Serializable]
+ public class LocalizationConfiguration
+ {
+ public IEnumerable? SupportedCultures { get; set; }
+
+ public string CurrentCulture { get; set; } = CultureInfo.CurrentCulture.Name;
+
+ public Dictionary>? Values { get; set; }
+ }
+
+ [NonAction]
+ private async Task GetPermissionConfigurationAsync()
+ {
+ PermissionConfiguration permissionConfiguration = new();
+
+ IEnumerable policyNames = _permissionDefinitionManager.GetPermissions().Select(p => p.Name);
+
+ PropertyInfo? policyMapProperty = typeof(AuthorizationOptions).GetProperty("PolicyMap", BindingFlags.Instance | BindingFlags.NonPublic);
+ if (policyMapProperty is not null)
+ {
+ object? policyMapPropertyValue = policyMapProperty.GetValue(_authorizationOptions);
+ if (policyMapPropertyValue is not null)
+ {
+ policyNames = policyNames.Union(((IDictionary>)policyMapPropertyValue).Keys.ToList());
+ }
+ }
+
+ List permissionPolicyNames = [];
+ List otherPolicyNames = [];
+
+ foreach (var policyName in policyNames)
+ {
+ if (_permissionDefinitionManager.GetOrNull(policyName) is not null)
+ {
+ permissionPolicyNames.Add(policyName);
+ }
+ else
+ {
+ otherPolicyNames.Add(policyName);
+ }
+ }
+
+ foreach (var policyName in otherPolicyNames)
+ {
+ permissionConfiguration.Policies[policyName] = true;
+
+ if (_httpContextAccessor is not null && _httpContextAccessor.HttpContext is not null)
+ {
+ if ((await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, policyName)).Succeeded)
+ {
+ permissionConfiguration.GrantedPolicies[policyName] = true;
+ }
+ }
+ }
+
+ MultiplePermissionGrantResult result = await _permissionChecker.IsGrantedAsync(permissionPolicyNames.ToArray());
+
+ foreach (var (key, value) in result.Result)
+ {
+ permissionConfiguration.Policies[key] = true;
+ if (value == PermissionGrantResult.Granted)
+ {
+ permissionConfiguration.GrantedPolicies[key] = true;
+ }
+ }
+
+ return permissionConfiguration;
+ }
+
+ [NonAction]
+#pragma warning disable IDE0051 // Remove unused private members
+ private async Task GetLocalizationConfigurationAsync()
+#pragma warning restore IDE0051 // Remove unused private members
+ {
+ LocalizationConfiguration localizationConfiguration = new() { Values = [] };
+
+ var assemblies = AppDomain.CurrentDomain.GetAssemblies();
+
+ string pattern = @"^(?[a-zA-Z0-9.]+).Resources.(?[a-zA-Z0-9.]+).([a-z]+-[A-Z]+.resources)$";
+
+ foreach (Assembly assembly in assemblies)
+ {
+ AssemblyName assemblyName = assembly.GetName();
+
+ if (assemblyName.Name is not null && assemblyName.Name.StartsWith("ZeroFramework"))
+ {
+ string[] resourceNames = assembly.GetManifestResourceNames();
+
+ foreach (var resourceName in resourceNames)
+ {
+ Match match = Regex.Match(resourceName, pattern, RegexOptions.IgnoreCase);
+
+ if (match.Success)
+ {
+ string baseName = match.Groups["baseName"].Value.TrimEnd('.');
+ string location = match.Groups["location"].Value;
+ var stringLocalizer = _stringLocalizerFactory.Create(baseName, location);
+ var dictionary = stringLocalizer.GetAllStrings(true).ToDictionary(s => s.Name, s => s.Value);
+ localizationConfiguration.Values.TryAdd($"{location}.{baseName}", dictionary);
+ }
+ }
+ }
+ }
+
+ localizationConfiguration.SupportedCultures = _requestLocalizationOptions.SupportedCultures?.Select(sc => sc.Name);
+
+ return await Task.FromResult(localizationConfiguration);
+ }
+ }
+}
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/DeviceGroupsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/DeviceGroupsController.cs
new file mode 100644
index 0000000..e88870d
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/DeviceGroupsController.cs
@@ -0,0 +1,76 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Devices;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Devices;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ ///
+ /// For more information on enabling Web API for empty projects
+ ///
+ [Route("api/[controller]")]
+ [ApiController]
+ public class DeviceGroupsController(IDeviceGroupApplicationService deviceGroupService) : ControllerBase
+ {
+ private readonly IDeviceGroupApplicationService _deviceGroupService = deviceGroupService;
+
+ // GET: api/
+ [HttpGet]
+ [Authorize(DeviceGroupPermissions.DeviceGroups.Default)]
+ public async Task> GetDeviceGroups([FromQuery] DeviceGroupPagedRequestModel model)
+ {
+ return await _deviceGroupService.GetListAsync(model);
+ }
+
+ [HttpPut("Devices")]
+ [Authorize(DeviceGroupPermissions.DeviceGroups.Edit)]
+ public async Task PutDevicesToGroup(int deviceGroupId, [FromBody] long[] deviceIds)
+ {
+ await _deviceGroupService.AddDevicesToGroup(deviceGroupId, deviceIds);
+ return Ok();
+ }
+
+ [HttpDelete("Devices")]
+ [Authorize(DeviceGroupPermissions.DeviceGroups.Edit)]
+ public async Task DeleteDevicesFromGroup(int deviceGroupId, [FromBody] long[] deviceIds)
+ {
+ await _deviceGroupService.RemoveDevicesFromGroup(deviceGroupId, deviceIds);
+ return Ok();
+ }
+
+ // GET api//5
+ [HttpGet("{id}")]
+ [Authorize(DeviceGroupPermissions.DeviceGroups.Default)]
+ public async Task GetDeviceGroup(int id)
+ {
+ return await _deviceGroupService.GetAsync(id);
+ }
+
+ // POST api/
+ [HttpPost]
+ [Authorize(DeviceGroupPermissions.DeviceGroups.Create)]
+ public async Task PostDeviceGroup([FromBody] DeviceGroupCreateRequestModel value)
+ {
+ return await _deviceGroupService.CreateAsync(value);
+ }
+
+ // PUT api//5
+ [HttpPut("{id}")]
+ [Authorize(DeviceGroupPermissions.DeviceGroups.Edit)]
+ public async Task PutDeviceGroup(int id, [FromBody] DeviceGroupUpdateRequestModel value)
+ {
+ value.Id = id;
+ return await _deviceGroupService.UpdateAsync(id, value);
+ }
+
+ // DELETE api//5
+ [HttpDelete("{id}")]
+ [Authorize(DeviceGroupPermissions.DeviceGroups.Delete)]
+ public async Task DeleteDeviceGroup(int id)
+ {
+ await _deviceGroupService.DeleteAsync(id);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/DevicesController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/DevicesController.cs
new file mode 100644
index 0000000..6ca1222
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/DevicesController.cs
@@ -0,0 +1,67 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Devices;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Devices;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ ///
+ /// For more information on enabling Web API for empty projects
+ ///
+ [Route("api/[controller]")]
+ [ApiController]
+ public class DevicesController(IDeviceApplicationService deviceService) : ControllerBase
+ {
+ private readonly IDeviceApplicationService _deviceService = deviceService;
+
+ // GET: api/
+ [HttpGet]
+ [Authorize(DevicePermissions.Devices.Default)]
+ public async Task> GetDevices([FromQuery] DevicePagedRequestModel model)
+ {
+ return await _deviceService.GetListAsync(model);
+ }
+
+ // GET api//5
+ [HttpGet("{id}")]
+ [Authorize(DevicePermissions.Devices.Default)]
+ public async Task GetDevice(long id)
+ {
+ return await _deviceService.GetAsync(id);
+ }
+
+ // POST api/
+ [HttpPost]
+ [Authorize(DevicePermissions.Devices.Create)]
+ public async Task PostDevice([FromBody] DeviceCreateRequestModel value)
+ {
+ return await _deviceService.CreateAsync(value);
+ }
+
+ // PUT api//5
+ [HttpPut("{id}")]
+ [Authorize(DevicePermissions.Devices.Edit)]
+ public async Task PutDevice(long id, [FromBody] DeviceUpdateRequestModel value)
+ {
+ value.Id = id;
+ return await _deviceService.UpdateAsync(id, value);
+ }
+
+ // DELETE api//5
+ [HttpDelete("{id}")]
+ [Authorize(DevicePermissions.Devices.Delete)]
+ public async Task DeleteDevice(long id)
+ {
+ await _deviceService.DeleteAsync(id);
+ }
+
+ [HttpGet("statistic")]
+ [Authorize(DevicePermissions.Devices.Default)]
+ public async Task GetStatistic()
+ {
+ return await _deviceService.GetStatistics();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MeasurementUnitsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MeasurementUnitsController.cs
new file mode 100644
index 0000000..80a4c78
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MeasurementUnitsController.cs
@@ -0,0 +1,60 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Products;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+using ZeroFramework.DeviceCenter.Application.Services.Products;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ ///
+ /// For more information on enabling Web API for empty projects
+ ///
+ [Route("api/[controller]")]
+ [ApiController]
+ public class MeasurementUnitsController(IMeasurementUnitApplicationService productService) : ControllerBase
+ {
+ private readonly IMeasurementUnitApplicationService _productService = productService;
+
+ // GET: api/
+ [HttpGet]
+ [Authorize(ProductPermissions.MeasurementUnits.Default)]
+ public async Task> GetMeasurementUnits([FromQuery] MeasurementUnitPagedRequestModel model)
+ {
+ return await _productService.GetListAsync(model);
+ }
+
+ // GET api//5
+ [HttpGet("{id}")]
+ [Authorize(ProductPermissions.MeasurementUnits.Default)]
+ public async Task GetMeasurementUnit(int id)
+ {
+ return await _productService.GetAsync(id);
+ }
+
+ // POST api/
+ [HttpPost]
+ [Authorize(ProductPermissions.MeasurementUnits.Create)]
+ public async Task PostMeasurementUnit([FromBody] MeasurementUnitCreateRequestModel value)
+ {
+ return await _productService.CreateAsync(value);
+ }
+
+ // PUT api//5
+ [HttpPut("{id}")]
+ [Authorize(ProductPermissions.MeasurementUnits.Edit)]
+ public async Task PutMeasurementUnit(int id, [FromBody] MeasurementUnitUpdateRequestModel value)
+ {
+ value.Id = id;
+ return await _productService.UpdateAsync(id, value);
+ }
+
+ // DELETE api//5
+ [HttpDelete("{id}")]
+ [Authorize(ProductPermissions.MeasurementUnits.Delete)]
+ public async Task DeleteMeasurementUnit(int id)
+ {
+ await _productService.DeleteAsync(id);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MeasurementsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MeasurementsController.cs
new file mode 100644
index 0000000..5a4f4de
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MeasurementsController.cs
@@ -0,0 +1,48 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Measurements;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+using ZeroFramework.DeviceCenter.Application.Services.Measurements;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class MeasurementsController(IDeviceDataApplicationService deviceDataApplication) : ControllerBase
+ {
+ private readonly IDeviceDataApplicationService _deviceDataApplication = deviceDataApplication;
+
+ [HttpGet("property-values")]
+ [Authorize(MeasurementPermissions.Measurements.DevicePropertyValues)]
+ public async Task?> GetDevicePropertyValues(int productId, long deviceId)
+ {
+ return await _deviceDataApplication.GetDevicePropertyValues(productId, deviceId);
+ }
+
+ [HttpGet("property-history-values")]
+ [Authorize(MeasurementPermissions.Measurements.DevicePropertyHistoryValues)]
+ public async Task?> GetDevicePropertyHistoryValues(int productId, long deviceId, string identifier, DateTimeOffset startTime, DateTimeOffset endTime, SortingOrder sorting, int pageNumber, int pageSize)
+ {
+ int offset = (pageNumber - 1) * pageSize;
+
+ return await _deviceDataApplication.GetDevicePropertyHistoryValues(productId, deviceId, identifier, startTime, endTime, false, sorting, offset, pageSize);
+ }
+
+ [HttpGet("property-reports")]
+ [Authorize(MeasurementPermissions.Measurements.DevicePropertyReports)]
+ public async Task?> GetDevicePropertyReports(int productId, long deviceId, string identifier, DateTimeOffset startTime, DateTimeOffset endTime, string reportType, int pageNumber, int pageSize)
+ {
+ int offset = (pageNumber - 1) * pageSize;
+
+ return await _deviceDataApplication.GetDevicePropertyReports(productId, deviceId, identifier, startTime, endTime, reportType, offset, pageSize);
+ }
+
+ [HttpPut("property-values")]
+ [Authorize(MeasurementPermissions.Measurements.SetDevicePropertyValues)]
+ public async Task SetDevicePropertyValue([FromQuery] int productId, [FromQuery] long deviceId, [FromBody] IDictionary values)
+ {
+ await _deviceDataApplication.SetDevicePropertyValues(productId, deviceId, values);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MonitoringFactorsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MonitoringFactorsController.cs
new file mode 100644
index 0000000..6f531e3
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/MonitoringFactorsController.cs
@@ -0,0 +1,54 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Monitoring;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Queries.Monitoring;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class MonitoringFactorsController(IMonitoringFactorQueries monitoringFactorQueries, ICrudApplicationService crudApplicationService) : ControllerBase
+ {
+ private readonly ICrudApplicationService _crudApplicationService = crudApplicationService;
+
+ private readonly IMonitoringFactorQueries _monitoringFactorQueries = monitoringFactorQueries;
+
+ [HttpGet]
+ [Authorize(MonitoringFactorPermissions.MonitoringFactors.Default)]
+ public async Task> GetMonitoringFactors([FromQuery] MonitoringFactorPagedRequestModel model)
+ {
+ return await _monitoringFactorQueries.GetMonitoringFactorsAsync(model);
+ }
+
+ [HttpGet("{id:int}")]
+ [Authorize(MonitoringFactorPermissions.MonitoringFactors.Default)]
+ public async Task GetMonitoringFactor(int id)
+ {
+ return await _monitoringFactorQueries.GetMonitoringFactorAsync(id);
+ }
+
+ [HttpPost]
+ [Authorize(MonitoringFactorPermissions.MonitoringFactors.Create)]
+ public async Task PostMonitoringFactor([FromBody] MonitoringFactorCreateRequestModel model)
+ {
+ return await _crudApplicationService.CreateAsync(model);
+ }
+
+ [HttpPut("{id:int}")]
+ [Authorize(MonitoringFactorPermissions.MonitoringFactors.Edit)]
+ public async Task PutMonitoringFactor(int id, [FromBody] MonitoringFactorUpdateRequestModel model)
+ {
+ model.Id = id;
+ return await _crudApplicationService.UpdateAsync(id, model);
+ }
+
+ [HttpDelete("{id:int}")]
+ [Authorize(MonitoringFactorPermissions.MonitoringFactors.Delete)]
+ public async Task DeleteMonitoringFactor(int id)
+ {
+ await _crudApplicationService.DeleteAsync(id);
+ }
+ }
+}
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/OrdersController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/OrdersController.cs
new file mode 100644
index 0000000..91941ea
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/OrdersController.cs
@@ -0,0 +1,42 @@
+using MediatR;
+using Microsoft.AspNetCore.Mvc;
+using System.Diagnostics;
+using System.Net;
+using ZeroFramework.DeviceCenter.Application.Commands.Ordering;
+using ZeroFramework.DeviceCenter.Application.Infrastructure;
+using ZeroFramework.DeviceCenter.Application.Queries.Ordering;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public class OrdersController(IOrderQueries orderQueries, IMediator mediator) : Controller
+ {
+ private readonly IOrderQueries _orderQueries = orderQueries;
+
+ private readonly IMediator _mediator = mediator;
+
+ [HttpGet]
+ [ProducesResponseType(typeof(OrderViewModel), (int)HttpStatusCode.OK)]
+ [ProducesResponseType((int)HttpStatusCode.NotFound)]
+ public async Task GetOrderAsync(Guid orderId)
+ {
+ //Todo: It's good idea to take advantage of GetOrderByIdQuery and handle by GetCustomerByIdQueryHandler
+ //var order customer = await _mediator.Send(new GetOrderByIdQuery(orderId));
+ OrderViewModel orderViewModel = await _orderQueries.GetOrderAsync(orderId);
+ return Ok(orderViewModel);
+ }
+
+ [HttpPut]
+ [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]
+ public async Task CancelOrderAsync([FromBody] CancelOrderCommand command, [FromHeader(Name = "X-Request-Id")] string? requestId)
+ {
+ requestId ??= Activity.Current?.Id ?? HttpContext.TraceIdentifier;
+
+ var identifiedCommand = new IdentifiedCommand(command, requestId);
+ await _mediator.Send(identifiedCommand);
+
+ return Ok();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/PermissionsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/PermissionsController.cs
new file mode 100644
index 0000000..881b6fe
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/PermissionsController.cs
@@ -0,0 +1,29 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Permissions;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Permissions;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class PermissionsController(IPermissionApplicationService permissionApplicationService) : ControllerBase
+ {
+ private readonly IPermissionApplicationService _permissionApplicationService = permissionApplicationService;
+
+ [HttpPut]
+ [Authorize(PermissionPermissions.Permissions.Edit)]
+ public virtual Task UpdateAsync(PermissionUpdateRequestModel updateModel)
+ {
+ return _permissionApplicationService.UpdateAsync(updateModel);
+ }
+
+ [HttpGet]
+ [Authorize(PermissionPermissions.Permissions.Get)]
+ public virtual Task GetAsync(string? providerName, string? providerKey, Guid? resourceGroupId)
+ {
+ return _permissionApplicationService.GetAsync(providerName, providerKey, resourceGroupId);
+ }
+ }
+}
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ProductsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ProductsController.cs
new file mode 100644
index 0000000..891c1a7
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ProductsController.cs
@@ -0,0 +1,74 @@
+using MediatR;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using System.Diagnostics;
+using System.Net;
+using ZeroFramework.DeviceCenter.Application.Commands.Products;
+using ZeroFramework.DeviceCenter.Application.Infrastructure;
+using ZeroFramework.DeviceCenter.Application.Models.Products;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+using ZeroFramework.DeviceCenter.Application.Services.Products;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ ///
+ /// For more information on enabling Web API for empty projects
+ ///
+ [Route("api/[controller]")]
+ [ApiController]
+ public class ProductsController(IProductApplicationService productService, IMediator mediator) : ControllerBase
+ {
+ private readonly IProductApplicationService _productService = productService;
+
+ private readonly IMediator _mediator = mediator;
+
+ // GET: api/
+ [HttpGet]
+ [Authorize(ProductPermissions.Products.Default)]
+ public async Task> GetProducts([FromQuery] ProductPagedRequestModel model)
+ {
+ return await _productService.GetListAsync(model);
+ }
+
+ // GET api//5
+ [HttpGet("{id}")]
+ [Authorize(ProductPermissions.Products.Default)]
+ public async Task GetProduct(int id)
+ {
+ return await _productService.GetAsync(id);
+ }
+
+ // POST api/
+ [HttpPost]
+ [Authorize(ProductPermissions.Products.Create)]
+ [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]
+ public async Task PostProduct([FromBody] CreateProductCommand command, [FromHeader(Name = "X-Request-Id")] string? requestId)
+ {
+ requestId ??= Activity.Current?.Id ?? HttpContext.TraceIdentifier;
+
+ var identifiedCommand = new IdentifiedCommand(command, requestId);
+ ProductGetResponseModel result = await _mediator.Send(identifiedCommand);
+
+ return CreatedAtAction(nameof(GetProduct), new { id = result.Id }, result);
+ }
+
+ // PUT api//5
+ [HttpPut("{id}")]
+ [Authorize(ProductPermissions.Products.Edit)]
+ public async Task PutProduct(int id, [FromBody] ProductUpdateRequestModel value)
+ {
+ value.Id = id;
+ return await _productService.UpdateAsync(id, value);
+ }
+
+ // DELETE api//5
+ [HttpDelete("{id}")]
+ [Authorize(ProductPermissions.Products.Delete)]
+ public async Task DeleteProduct(int id)
+ {
+ await _productService.DeleteAsync(id);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ProjectsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ProjectsController.cs
new file mode 100644
index 0000000..5b83168
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ProjectsController.cs
@@ -0,0 +1,59 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Projects;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ ///
+ /// For more information on enabling Web API for empty projects
+ ///
+ [Route("api/[controller]")]
+ [ApiController]
+ public class ProjectsController(ICrudApplicationService crudService) : ControllerBase
+ {
+ private readonly ICrudApplicationService _crudService = crudService;
+
+ // GET: api/
+ [HttpGet]
+ [Authorize(ProjectPermissions.Projects.Default)]
+ public async Task> Get([FromQuery] PagedRequestModel model)
+ {
+ return await _crudService.GetListAsync(model);
+ }
+
+ // GET api//5
+ [HttpGet("{id}")]
+ [Authorize(ProjectPermissions.Projects.Default)]
+ public async Task Get(int id)
+ {
+ return await _crudService.GetAsync(id);
+ }
+
+ // POST api/
+ [HttpPost]
+ [Authorize(ProjectPermissions.Projects.Create)]
+ public async Task Post([FromBody] ProjectCreateOrUpdateRequestModel value)
+ {
+ return await _crudService.CreateAsync(value);
+ }
+
+ // PUT api//5
+ [HttpPut("{id}")]
+ [Authorize(ProjectPermissions.Projects.Edit)]
+ public async Task Put(int id, [FromBody] ProjectCreateOrUpdateRequestModel value)
+ {
+ value.Id = id;
+ return await _crudService.UpdateAsync(id, value);
+ }
+
+ // DELETE api//5
+ [HttpDelete("{id}")]
+ [Authorize(ProjectPermissions.Projects.Delete)]
+ public async Task Delete(int id)
+ {
+ await _crudService.DeleteAsync(id);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ResourceGroupsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ResourceGroupsController.cs
new file mode 100644
index 0000000..feb6f56
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ResourceGroupsController.cs
@@ -0,0 +1,52 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.ResourceGroups;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+using ZeroFramework.DeviceCenter.Application.Services.ResourceGroups;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class ResourceGroupsController(IResourceGroupApplicationService resourceGroupApplicationService) : ControllerBase
+ {
+ private readonly IResourceGroupApplicationService _resourceGroupApplicationService = resourceGroupApplicationService;
+
+ [HttpGet]
+ [Authorize(ResourceGroupPermissions.ResourceGroups.Default)]
+ public async Task> GetResourceGroups([FromQuery] ResourceGroupPagedRequestModel model)
+ {
+ return await _resourceGroupApplicationService.GetListAsync(model);
+ }
+
+ [HttpGet("{id:guid}")]
+ [Authorize(ResourceGroupPermissions.ResourceGroups.Default)]
+ public async Task GetResourceGroup(Guid id)
+ {
+ return await _resourceGroupApplicationService.GetAsync(id);
+ }
+
+ [HttpPost]
+ [Authorize(ResourceGroupPermissions.ResourceGroups.Create)]
+ public async Task PostResourceGroup([FromBody] ResourceGroupCreateRequestModel model)
+ {
+ return await _resourceGroupApplicationService.CreateAsync(model);
+ }
+
+ [HttpPut("{id:guid}")]
+ [Authorize(ResourceGroupPermissions.ResourceGroups.Edit)]
+ public async Task PutResourceGroup(Guid id, [FromBody] ResourceGroupUpdateRequestModel model)
+ {
+ model.Id = id;
+ return await _resourceGroupApplicationService.UpdateAsync(id, model);
+ }
+
+ [HttpDelete("{id:guid}")]
+ [Authorize(ResourceGroupPermissions.ResourceGroups.Delete)]
+ public async Task DeleteResourceGroup(Guid id)
+ {
+ await _resourceGroupApplicationService.DeleteAsync(id);
+ }
+ }
+}
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/TenantsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/TenantsController.cs
new file mode 100644
index 0000000..01f2445
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/TenantsController.cs
@@ -0,0 +1,81 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Tenants;
+using ZeroFramework.DeviceCenter.Application.PermissionProviders;
+using ZeroFramework.DeviceCenter.Application.Services.Generics;
+using ZeroFramework.DeviceCenter.Application.Services.Tenants;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ ///
+ /// For more information on enabling Web API for empty projects
+ ///
+ [Route("api/[controller]")]
+ [ApiController, ApiExplorerSettings(IgnoreApi = true)]
+ public class TenantsController(ITenantApplicationService tenantService) : ControllerBase
+ {
+ private readonly ITenantApplicationService _tenantService = tenantService;
+
+ // GET: api/
+ [HttpGet]
+ [Authorize(TenantPermissions.Tenants.Default)]
+ public async Task> Get([FromQuery] PagedRequestModel model)
+ {
+ return await _tenantService.GetListAsync(model);
+ }
+
+ // GET api//5
+ [HttpGet("{id}")]
+ [Authorize(TenantPermissions.Tenants.Default)]
+ public async Task Get(Guid id)
+ {
+ return await _tenantService.GetAsync(id);
+ }
+
+ // POST api/
+ [HttpPost]
+ [Authorize(TenantPermissions.Tenants.Create)]
+ public async Task Post([FromBody] TenantCreateOrUpdateRequestModel value)
+ {
+ return await _tenantService.CreateAsync(value);
+ }
+
+ // PUT api//5
+ [HttpPut("{id}")]
+ [Authorize(TenantPermissions.Tenants.Edit)]
+ public async Task Put(Guid id, [FromBody] TenantCreateOrUpdateRequestModel value)
+ {
+ value.Id = id;
+ return await _tenantService.UpdateAsync(id, value);
+ }
+
+ // DELETE api//5
+ [HttpDelete("{id}")]
+ [Authorize(TenantPermissions.Tenants.Delete)]
+ public async Task Delete(Guid id)
+ {
+ await _tenantService.DeleteAsync(id);
+ }
+
+ [HttpGet("{id}/default-connection-string")]
+ [Authorize(TenantPermissions.Tenants.ConnectionString)]
+ public async Task GetDefaultConnectionStringAsync(Guid id)
+ {
+ return await _tenantService.GetDefaultConnectionStringAsync(id);
+ }
+
+ [HttpPut("{id}/default-connection-string")]
+ [Authorize(TenantPermissions.Tenants.ConnectionString)]
+ public async Task UpdateDefaultConnectionStringAsync(Guid id, string defaultConnectionString)
+ {
+ await _tenantService.UpdateDefaultConnectionStringAsync(id, defaultConnectionString);
+ }
+
+ [HttpDelete("{id}/default-connection-string")]
+ [Authorize(TenantPermissions.Tenants.ConnectionString)]
+ public async Task DeleteDefaultConnectionStringAsync(Guid id)
+ {
+ await _tenantService.DeleteDefaultConnectionStringAsync(id);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/TestsController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/TestsController.cs
new file mode 100644
index 0000000..b73d9f4
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/TestsController.cs
@@ -0,0 +1,68 @@
+using FluentValidation;
+using FluentValidation.Results;
+using Microsoft.AspNetCore.Mvc;
+using ZeroFramework.DeviceCenter.Application.Models.Measurements;
+using ZeroFramework.DeviceCenter.Application.Models.Projects;
+using ZeroFramework.DeviceCenter.Application.Services.Measurements;
+using ZeroFramework.DeviceCenter.Domain.Aggregates.MeasurementAggregate;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public class TestsController(IValidator validator, IDeviceDataApplicationService deviceDataApplicationService) : ControllerBase
+ {
+ private readonly IValidator _validator = validator;
+
+ private readonly IDeviceDataApplicationService _deviceDataApplicationService = deviceDataApplicationService;
+
+ [HttpGet]
+ public async Task> Get()
+ {
+ int productId = int.Parse("b4b9996c-beb5-4695-ad91-072eac1a6f89");
+
+ long deviceId = 10000;
+
+ Random random = new();
+
+ DateTimeOffset currentDateTime = DateTimeOffset.Now;
+
+ for (int i = 1; i < 45; i++)
+ {
+ currentDateTime = currentDateTime.AddMinutes(random.Next(5, 20));
+
+ Measurement value = new(currentDateTime.LocalDateTime);
+
+ value.Fields.Add("Value", i);
+
+ await _deviceDataApplicationService.SetDevicePropertyValues(productId, deviceId, new Dictionary
+ {
+ {
+ "Abc",
+ new DevicePropertyValue
+ {
+ Timestamp = currentDateTime.ToUnixTimeMilliseconds(),
+ Value = i
+ }
+ }
+ });
+ }
+
+ return Ok("OK");
+ }
+
+ [HttpPost]
+ public async Task> Post([FromBody] ProjectCreateOrUpdateRequestModel value)
+ {
+ ValidationResult validationResult = _validator.Validate(value);
+
+ if (validationResult.IsValid)
+ {
+ return await Task.FromResult(new ProjectGetResponseModel());
+ }
+
+ return BadRequest(validationResult);
+ }
+ }
+}
diff --git a/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ValuesController.cs b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ValuesController.cs
new file mode 100644
index 0000000..1cb1f5f
--- /dev/null
+++ b/Services/DeviceCenter/ZeroFramework.DeviceCenter.API/Controllers/ValuesController.cs
@@ -0,0 +1,164 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Caching.Distributed;
+using System.Text;
+using System.Text.Json;
+
+namespace ZeroFramework.DeviceCenter.API.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ [Authorize]
+ public class ValuesController(IDistributedCache distributedCache) : ControllerBase
+ {
+ private readonly IDistributedCache _distributedCache = distributedCache;
+
+ const string memberkey = "9VQrbUztIWJGu9IhPPeK";
+ const string appkey = "2302600008";
+ const string secret = "288Hs33a";
+ const string apiEndpoint = "http://219.151.131.31:19103";
+
+ static readonly HttpClient httpClient = new() { BaseAddress = new Uri(apiEndpoint) };
+
+ static readonly Dictionary geocodingMap = new()
+ {
+ { "50000002041320029010", "108.6280,30.6700" }, // 龙驹一级
+ { "50000002041320029011", "108.6190,30.6400" }, // 龙驹二级
+ { "50000002041320029008", "108.5476,30.7365" }, // 龙滩电站
+ { "50000002041320029009", "108.4380,30.7713" }, // 高洞子电站
+ };
+
+ [HttpGet]
+ public async Task GetAsync()
+ {
+ Dictionary deviceListparmeters = new()
+ {
+ { nameof(memberkey), memberkey },
+ };
+
+ string deviceListReadAsString = await SendApiRequest(HttpMethod.Post, "api/dict/device/select", deviceListparmeters);
+
+ JsonElement deviceListData = JsonDocument.Parse(deviceListReadAsString).RootElement;
+
+ if (deviceListData.GetProperty("code").GetString() == "0")
+ {
+ return Ok(deviceListData);
+ }
+
+ List | | | | | | | | |