Repository: kgrzybek/modular-monolith-with-ddd
Branch: master
Commit: 91c8ef24b4cb
Files: 1289
Total size: 2.2 MB
Directory structure:
gitextract_sty9z65e/
├── .github/
│ └── workflows/
│ └── buildPipeline.yml
├── .gitignore
├── .nuke/
│ ├── build.schema.json
│ └── parameters.json
├── LICENSE
├── README.md
├── azure-pipelines.yml
├── build/
│ ├── .editorconfig
│ ├── Build.cs
│ ├── BuildIntegrationTests.cs
│ ├── Configuration.cs
│ ├── Database.cs
│ ├── Directory.Build.props
│ ├── Directory.Build.targets
│ ├── SUTCreator.cs
│ ├── Utils/
│ │ └── SqlReadinessChecker.cs
│ ├── _build.csproj
│ └── _build.csproj.DotSettings
├── build.cmd
├── build.ps1
├── build.sh
├── docker-compose.yml
├── docs/
│ ├── C4/
│ │ ├── c1_system_context.puml
│ │ ├── c2_container.puml
│ │ ├── c3_components.puml
│ │ ├── c3_components_module.puml
│ │ └── c4_class.puml
│ ├── PlantUML/
│ │ ├── Commenting_Conceptual_Model.puml
│ │ └── Conceptual_Model.puml
│ ├── Project/
│ │ └── MyMeetings.vpp
│ ├── architecture-decision-log/
│ │ ├── 0001-record-architecture-decisions.md
│ │ ├── 0002-use_modular-monolith-system-architecture.md
│ │ ├── 0003-use_dotnetcore_and_csharp.md
│ │ ├── 0004-divide-the-system-into-4-modules.md
│ │ ├── 0005-create-one-rest-api-module.md
│ │ ├── 0006-create-facade-between-api-and-business-module.md
│ │ ├── 0007-use-cqrs-architectural-style.md
│ │ ├── 0008-allow-return-result-after-command-processing.md
│ │ ├── 0009-use-2-layered-architectural-style-for-reads.md
│ │ ├── 0010-use-clean-architecture-for-writes.md
│ │ ├── 0011-create-rich-domain-models.md
│ │ ├── 0012-use-domain-driven-design-tactical-patterns.md
│ │ ├── 0013-protect-business-invariants-using-exceptions.md
│ │ ├── 0014-event-driven-communication-between-modules.md
│ │ ├── 0015-use-in-memory-events-bus.md
│ │ ├── 0016-create-ioc-container-per-module.md
│ │ └── 0017-implement-archictecture-tests.md
│ ├── catalog-of-terms/
│ │ ├── Aggregate-DDD/
│ │ │ ├── README.md
│ │ │ └── aggregate-ddd.puml
│ │ ├── Command/
│ │ │ ├── README.md
│ │ │ └── command.puml
│ │ ├── Decorator-Pattern/
│ │ │ ├── README.md
│ │ │ └── decorator-pattern.puml
│ │ ├── Dependency-Injection/
│ │ │ ├── README.md
│ │ │ └── dependency-injection.puml
│ │ ├── Domain-Event/
│ │ │ ├── README.md
│ │ │ └── domain-event.puml
│ │ ├── Entity-DDD/
│ │ │ ├── README.md
│ │ │ └── entity-ddd.puml
│ │ ├── Event/
│ │ │ └── README.md
│ │ ├── Event-Driven-Architecture/
│ │ │ └── README.md
│ │ ├── Event-Sourcing/
│ │ │ └── README.md
│ │ ├── Event-Storming/
│ │ │ └── README.md
│ │ ├── Integration-Event/
│ │ │ └── README.md
│ │ ├── README.md
│ │ ├── Strategy-Pattern/
│ │ │ ├── README.md
│ │ │ └── strategy-pattern.puml
│ │ └── ValueObject-DDD/
│ │ ├── README.md
│ │ └── value-object-ddd.puml
│ └── mutation-tests-reports/
│ └── mutation-report.html
├── runIntegrationTests.cmd
└── src/
├── .dockerignore
├── .editorconfig
├── API/
│ ├── CompanyName.MyMeetings.API/
│ │ ├── CompanyName.MyMeetings.API.csproj
│ │ ├── Configuration/
│ │ │ ├── Authorization/
│ │ │ │ ├── AttributeAuthorizationHandler.cs
│ │ │ │ ├── AuthorizationChecker.cs
│ │ │ │ ├── HasPermissionAttribute.cs
│ │ │ │ ├── HasPermissionAuthorizationHandler.cs
│ │ │ │ ├── HasPermissionAuthorizationRequirement.cs
│ │ │ │ └── NoPermissionRequiredAttribute.cs
│ │ │ ├── ExecutionContext/
│ │ │ │ ├── CorrelationMiddleware.cs
│ │ │ │ └── ExecutionContextAccessor.cs
│ │ │ ├── Extensions/
│ │ │ │ └── SwaggerExtensions.cs
│ │ │ └── Validation/
│ │ │ ├── BusinessRuleValidationExceptionProblemDetails.cs
│ │ │ └── InvalidCommandProblemDetails.cs
│ │ ├── Modules/
│ │ │ ├── Administration/
│ │ │ │ ├── AdministrationAutofacModule.cs
│ │ │ │ ├── AdministrationPermissions.cs
│ │ │ │ └── MeetingGroupProposals/
│ │ │ │ └── MeetingGroupProposalsController.cs
│ │ │ ├── Meetings/
│ │ │ │ ├── Countries/
│ │ │ │ │ └── CountriesController.cs
│ │ │ │ ├── MeetingCommentingConfiguration/
│ │ │ │ │ └── MeetingCommentingConfigurationController.cs
│ │ │ │ ├── MeetingComments/
│ │ │ │ │ ├── AddMeetingCommentRequest.cs
│ │ │ │ │ ├── EditMeetingCommentRequest.cs
│ │ │ │ │ └── MeetingCommentsController.cs
│ │ │ │ ├── MeetingGroupProposals/
│ │ │ │ │ ├── MeetingGroupProposalsController.cs
│ │ │ │ │ └── ProposeMeetingGroupRequest.cs
│ │ │ │ ├── MeetingGroups/
│ │ │ │ │ ├── CreateNewMeetingGroupRequest.cs
│ │ │ │ │ ├── EditMeetingGroupGeneralAttributesRequest.cs
│ │ │ │ │ └── MeetingGroupsController.cs
│ │ │ │ ├── Meetings/
│ │ │ │ │ ├── AddMeetingAttendeeRequest.cs
│ │ │ │ │ ├── ChangeMeetingMainAttributesRequest.cs
│ │ │ │ │ ├── CreateMeetingRequest.cs
│ │ │ │ │ ├── MeetingsController.cs
│ │ │ │ │ ├── RemoveMeetingAttendeeRequest.cs
│ │ │ │ │ ├── SetMeetingAttendeeRequest.cs
│ │ │ │ │ └── SetMeetingHostRequest.cs
│ │ │ │ ├── MeetingsAutofacModule.cs
│ │ │ │ └── MeetingsPermissions.cs
│ │ │ ├── Payments/
│ │ │ │ ├── MeetingFees/
│ │ │ │ │ ├── CreateMeetingFeePaymentRequest.cs
│ │ │ │ │ ├── MeetingFeePaymentsController.cs
│ │ │ │ │ └── RegisterMeetingFeePaymentRequest.cs
│ │ │ │ ├── Payers/
│ │ │ │ │ └── PayersController.cs
│ │ │ │ ├── PaymentsAutofacModule.cs
│ │ │ │ ├── PaymentsPermissions.cs
│ │ │ │ ├── PriceListItems/
│ │ │ │ │ ├── ChangePriceListItemAttributesRequest.cs
│ │ │ │ │ ├── CreatePriceListItemRequest.cs
│ │ │ │ │ ├── GetPriceListItemRequest.cs
│ │ │ │ │ └── PriceListItemsController.cs
│ │ │ │ ├── RegisterSubscriptionRenewalPaymentRequest.cs
│ │ │ │ ├── SubscriptionRenewalsController.cs
│ │ │ │ └── Subscriptions/
│ │ │ │ ├── BuySubscriptionRequest.cs
│ │ │ │ ├── RegisterSubscriptionPaymentRequest.cs
│ │ │ │ ├── RenewSubscriptionRequest.cs
│ │ │ │ ├── SubscriptionPaymentsController.cs
│ │ │ │ └── SubscriptionsController.cs
│ │ │ └── UserAccess/
│ │ │ ├── AuthenticatedUserController.cs
│ │ │ ├── EmailsController.cs
│ │ │ ├── RegisterNewUserRequest.cs
│ │ │ ├── UserAccessAutofacModule.cs
│ │ │ └── UserRegistrationsController.cs
│ │ ├── Program.cs
│ │ ├── Properties/
│ │ │ └── launchSettings.json
│ │ ├── Startup.cs
│ │ ├── appsettings.Development.json
│ │ ├── appsettings.Production.json
│ │ ├── appsettings.json
│ │ ├── entrypoint.sh
│ │ └── tempkey.rsa
│ └── RequestExamples/
│ ├── Authentication.http
│ ├── Users.http
│ └── http-client.env.json
├── BuildingBlocks/
│ ├── Application/
│ │ ├── CompanyName.MyMeetings.BuildingBlocks.Application.csproj
│ │ ├── Data/
│ │ │ └── ISqlConnectionFactory.cs
│ │ ├── Emails/
│ │ │ ├── EmailMessage.cs
│ │ │ └── IEmailSender.cs
│ │ ├── Events/
│ │ │ ├── DomainNotificationBase.cs
│ │ │ └── IDomainEventNotification.cs
│ │ ├── IExecutionContextAccessor.cs
│ │ ├── InvalidCommandException.cs
│ │ ├── Outbox/
│ │ │ ├── IOutbox.cs
│ │ │ └── OutboxMessage.cs
│ │ └── Queries/
│ │ ├── IPagedQuery.cs
│ │ ├── PageData.cs
│ │ └── PagedQueryHelper.cs
│ ├── Domain/
│ │ ├── BusinessRuleValidationException.cs
│ │ ├── CompanyName.MyMeetings.BuildingBlocks.Domain.csproj
│ │ ├── DomainEventBase.cs
│ │ ├── Entity.cs
│ │ ├── IAggregateRoot.cs
│ │ ├── IBusinessRule.cs
│ │ ├── IDomainEvent.cs
│ │ ├── IgnoreMemberAttribute.cs
│ │ ├── TypedIdValueBase.cs
│ │ └── ValueObject.cs
│ ├── Infrastructure/
│ │ ├── BiDictionary.cs
│ │ ├── CompanyName.MyMeetings.BuildingBlocks.Infrastructure.csproj
│ │ ├── DomainEventsDispatching/
│ │ │ ├── DomainEventsAccessor.cs
│ │ │ ├── DomainEventsDispatcher.cs
│ │ │ ├── DomainEventsDispatcherNotificationHandlerDecorator.cs
│ │ │ ├── DomainNotificationsMapper.cs
│ │ │ ├── IDomainEventsAccessor.cs
│ │ │ ├── IDomainEventsDispatcher.cs
│ │ │ ├── IDomainNotificationsMapper.cs
│ │ │ └── UnitOfWorkCommandHandlerDecorator.cs
│ │ ├── Emails/
│ │ │ ├── EmailSender.cs
│ │ │ └── EmailsConfiguration.cs
│ │ ├── EventBus/
│ │ │ ├── IEventsBus.cs
│ │ │ ├── IIntegrationEventHandler.cs
│ │ │ ├── InMemoryEventBus.cs
│ │ │ ├── InMemoryEventBusClient.cs
│ │ │ └── IntegrationEvent.cs
│ │ ├── IUnitOfWork.cs
│ │ ├── Inbox/
│ │ │ └── InboxMessage.cs
│ │ ├── InternalCommands/
│ │ │ ├── IInternalCommandsMapper.cs
│ │ │ ├── InternalCommand.cs
│ │ │ └── InternalCommandsMapper.cs
│ │ ├── Serialization/
│ │ │ └── AllPropertiesContractResolver.cs
│ │ ├── ServiceProviderWrapper.cs
│ │ ├── SqlConnectionFactory.cs
│ │ ├── StronglyTypedIdValueConverterSelector.cs
│ │ ├── TypedIdValueConverter.cs
│ │ └── UnitOfWork.cs
│ └── Tests/
│ ├── Application.UnitTests/
│ │ ├── CompanyName.MyMeetings.BuildingBlocks.Application.UnitTests.csproj
│ │ └── Queries/
│ │ └── PagedQueryHelperTests.cs
│ └── IntegrationTests/
│ ├── CompanyName.MyMeetings.BuildingBlocks.IntegrationTests.csproj
│ ├── EnvironmentVariablesProvider.cs
│ └── Probing/
│ ├── AssertErrorException.cs
│ ├── IProbe.cs
│ ├── Poller.cs
│ └── Timeout.cs
├── CompanyName.MyMeetings.sln
├── Database/
│ ├── .dockerignore
│ ├── ClearDatabase.sql
│ ├── CompanyName.MyMeetings.Database/
│ │ ├── CompanyName.MyMeetings.Database.sqlproj
│ │ ├── Scripts/
│ │ │ ├── ClearDatabase.sql
│ │ │ ├── CreateDatabase.sql
│ │ │ ├── CreateDatabase_Linux.sql
│ │ │ ├── CreateDatabase_Windows.sql
│ │ │ ├── CreateStructure.sql
│ │ │ ├── Migrations/
│ │ │ │ └── 1_0_0_0/
│ │ │ │ ├── 0001_initial_structure.sql
│ │ │ │ ├── 0002_change_meeting_comments_edit_date_type_and_add_meeting_comments_view.sql
│ │ │ │ ├── 0003_add_meetings_countries_table.sql
│ │ │ │ ├── 0004_add_meeting_commenting_configurations_table.sql
│ │ │ │ ├── 0005_add_payer_id_to_subcription_details_view.sql
│ │ │ │ ├── 0006_add_member_meeting_groups_view.sql
│ │ │ │ ├── 0007_add_meeting_attendees_view.sql
│ │ │ │ ├── 0008_add_meeting_details_view.sql
│ │ │ │ ├── 0009_add_mock_emails_table.sql
│ │ │ │ ├── 0010_add_member_meetings_view.sql
│ │ │ │ ├── 0011_add_likes_count_to_meeting_comments_table.sql
│ │ │ │ ├── 0012_add_likes_count_to_meeting_comments_view.sql
│ │ │ │ ├── 0013_add_meeting_member_comment_likes_table.sql
│ │ │ │ └── 0014_add_missing_tables_for_registrations.sql
│ │ │ ├── SeedDatabase.sql
│ │ │ └── Seeds/
│ │ │ └── 0001_SeedCountries.sql
│ │ └── Structure/
│ │ ├── Security/
│ │ │ └── Schemas.sql
│ │ ├── administration/
│ │ │ ├── Tables/
│ │ │ │ ├── InboxMessages.sql
│ │ │ │ ├── InternalCommands.sql
│ │ │ │ ├── MeetingGroupProposals.sql
│ │ │ │ ├── Members.sql
│ │ │ │ └── OutboxMessages.sql
│ │ │ └── Views/
│ │ │ ├── v_MeetingGroupProposals.sql
│ │ │ └── v_Members.sql
│ │ ├── app/
│ │ │ └── Tables/
│ │ │ ├── Emails.sql
│ │ │ └── MigrationsJournal.sql
│ │ ├── meetings/
│ │ │ ├── Tables/
│ │ │ │ ├── Countries.sql
│ │ │ │ ├── InboxMessages.sql
│ │ │ │ ├── InternalCommands.sql
│ │ │ │ ├── MeetingAttendees.sql
│ │ │ │ ├── MeetingCommentingConfigurations.sql
│ │ │ │ ├── MeetingComments.sql
│ │ │ │ ├── MeetingGroupMembers.sql
│ │ │ │ ├── MeetingGroupProposals.sql
│ │ │ │ ├── MeetingGroups.sql
│ │ │ │ ├── MeetingMemberCommentLikes.sql
│ │ │ │ ├── MeetingNotAttendees.sql
│ │ │ │ ├── MeetingWaitlistMembers.sql
│ │ │ │ ├── Meetings.sql
│ │ │ │ ├── MemberSubscriptions.sql
│ │ │ │ ├── Members.sql
│ │ │ │ └── OutboxMessages.sql
│ │ │ └── Views/
│ │ │ ├── v_Countries.sql
│ │ │ ├── v_MeetingAttendees.sql
│ │ │ ├── v_MeetingComments.sql
│ │ │ ├── v_MeetingDetails.sql
│ │ │ ├── v_MeetingGroupMembers.sql
│ │ │ ├── v_MeetingGroupProposals.sql
│ │ │ ├── v_MeetingGroups.sql
│ │ │ ├── v_Meetings.sql
│ │ │ ├── v_MemberMeetingGroups.sql
│ │ │ ├── v_MemberMeetings.sql
│ │ │ └── v_Members.sql
│ │ ├── payments/
│ │ │ ├── Tables/
│ │ │ │ ├── InboxMessages.sql
│ │ │ │ ├── InternalCommands.sql
│ │ │ │ ├── MeetingFees.sql
│ │ │ │ ├── Messages.sql
│ │ │ │ ├── OutboxMessages.sql
│ │ │ │ ├── Payers.sql
│ │ │ │ ├── PriceListItems.sql
│ │ │ │ ├── Streams.sql
│ │ │ │ ├── SubscriptionCheckpoints.sql
│ │ │ │ ├── SubscriptionDetails.sql
│ │ │ │ └── SubscriptionPayments.sql
│ │ │ └── Types/
│ │ │ └── NewStreamMessages.sql
│ │ ├── registrations/
│ │ │ ├── Tables/
│ │ │ │ ├── InboxMessages.sql
│ │ │ │ ├── InternalCommands.sql
│ │ │ │ ├── OutboxMessages.sql
│ │ │ │ └── UserRegistrations.sql
│ │ │ └── Views/
│ │ │ └── v_UserRegistrations.sql
│ │ └── users/
│ │ ├── Tables/
│ │ │ ├── InboxMessages.sql
│ │ │ ├── InternalCommands.sql
│ │ │ ├── OutboxMessages.sql
│ │ │ ├── Permissions.sql
│ │ │ ├── RolesToPermissions.sql
│ │ │ ├── UserRoles.sql
│ │ │ └── Users.sql
│ │ └── Views/
│ │ ├── v_UserPermissions.sql
│ │ ├── v_UserRoles.sql
│ │ └── v_Users.sql
│ ├── CompanyName.MyMeetings.Database.Build/
│ │ └── CompanyName.MyMeetings.Database.Build.csproj
│ ├── DatabaseMigrator/
│ │ ├── .dockerignore
│ │ ├── DatabaseMigrator.csproj
│ │ ├── Program.cs
│ │ └── SerilogUpgradeLog.cs
│ ├── Dockerfile
│ ├── Dockerfile_DatabaseMigrator
│ ├── InitializeDatabase.sql
│ ├── entrypoint.sh
│ ├── entrypoint_DatabaseMigrator.sh
│ └── wait-for-it.sh
├── Directory.Build.props
├── Directory.Build.targets
├── Directory.Packages.props
├── Dockerfile
├── Modules/
│ ├── Administration/
│ │ ├── Application/
│ │ │ ├── CompanyName.MyMeetings.Modules.Administration.Application.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── Commands/
│ │ │ │ │ ├── ICommandHandler.cs
│ │ │ │ │ ├── ICommandsScheduler.cs
│ │ │ │ │ └── InternalCommandBase.cs
│ │ │ │ └── Queries/
│ │ │ │ └── IQueryHandler.cs
│ │ │ ├── Contracts/
│ │ │ │ ├── CommandBase.cs
│ │ │ │ ├── IAdministrationModule.cs
│ │ │ │ ├── ICommand.cs
│ │ │ │ ├── IQuery.cs
│ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ └── QueryBase.cs
│ │ │ ├── MeetingGroupProposals/
│ │ │ │ ├── AcceptMeetingGroupProposal/
│ │ │ │ │ ├── AcceptMeetingGroupProposalCommand.cs
│ │ │ │ │ ├── AcceptMeetingGroupProposalCommandHandler.cs
│ │ │ │ │ ├── MeetingGroupProposalAcceptedNotification.cs
│ │ │ │ │ └── MeetingGroupProposalAcceptedNotificationHandler.cs
│ │ │ │ ├── GetMeetingGroupProposal/
│ │ │ │ │ ├── GetMeetingGroupProposalQuery.cs
│ │ │ │ │ ├── GetMeetingGroupProposalQueryHandler.cs
│ │ │ │ │ └── MeetingGroupProposalDto.cs
│ │ │ │ ├── GetMeetingGroupProposals/
│ │ │ │ │ ├── GetMeetingGroupProposalsQuery.cs
│ │ │ │ │ └── GetMeetingGroupProposalsQueryHandler.cs
│ │ │ │ ├── MeetingGroupProposedIntegrationEventHandler.cs
│ │ │ │ └── RequestMeetingGroupProposalVerification/
│ │ │ │ ├── RequestMeetingGroupProposalVerificationCommand.cs
│ │ │ │ └── RequestMeetingGroupProposalVerificationCommandHandler.cs
│ │ │ └── Members/
│ │ │ ├── CreateMember/
│ │ │ │ ├── CreateMemberCommand.cs
│ │ │ │ └── CreateMemberCommandHandler.cs
│ │ │ ├── GetMember/
│ │ │ │ ├── GetMemberQuery.cs
│ │ │ │ ├── GetMemberQueryHandler.cs
│ │ │ │ └── MemberDto.cs
│ │ │ └── NewUserRegisteredIntegrationEventHandler.cs
│ │ ├── Domain/
│ │ │ ├── CompanyName.MyMeetings.Modules.Administration.Domain.csproj
│ │ │ ├── MeetingGroupProposals/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingGroupProposalAcceptedDomainEvent.cs
│ │ │ │ │ ├── MeetingGroupProposalRejectedDomainEvent.cs
│ │ │ │ │ └── MeetingGroupProposalVerificationRequestedDomainEvent.cs
│ │ │ │ ├── IMeetingGroupProposalRepository.cs
│ │ │ │ ├── MeetingGroupLocation.cs
│ │ │ │ ├── MeetingGroupProposal.cs
│ │ │ │ ├── MeetingGroupProposalDecision.cs
│ │ │ │ ├── MeetingGroupProposalId.cs
│ │ │ │ ├── MeetingGroupProposalStatus.cs
│ │ │ │ └── Rules/
│ │ │ │ ├── MeetingGroupProposalCanBeVerifiedOnceRule.cs
│ │ │ │ └── MeetingGroupProposalRejectionMustHaveAReasonRule.cs
│ │ │ ├── Members/
│ │ │ │ ├── Events/
│ │ │ │ │ └── MemberCreatedDomainEvent.cs
│ │ │ │ ├── IMemberRepository.cs
│ │ │ │ ├── Member.cs
│ │ │ │ └── MemberId.cs
│ │ │ └── Users/
│ │ │ ├── IUserContext.cs
│ │ │ └── UserId.cs
│ │ ├── Infrastructure/
│ │ │ ├── AdministrationContext.cs
│ │ │ ├── AdministrationModule.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Administration.Infrastructure.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── AdministrationCompositionRoot.cs
│ │ │ │ ├── AdministrationStartup.cs
│ │ │ │ ├── AllConstructorFinder.cs
│ │ │ │ ├── Assemblies.cs
│ │ │ │ ├── Authentication/
│ │ │ │ │ └── AuthenticationModule.cs
│ │ │ │ ├── DataAccess/
│ │ │ │ │ └── DataAccessModule.cs
│ │ │ │ ├── EventsBus/
│ │ │ │ │ ├── EventsBusModule.cs
│ │ │ │ │ ├── EventsBusStartup.cs
│ │ │ │ │ └── IntegrationEventGenericHandler.cs
│ │ │ │ ├── Logging/
│ │ │ │ │ └── LoggingModule.cs
│ │ │ │ ├── Mediation/
│ │ │ │ │ └── MediatorModule.cs
│ │ │ │ ├── Processing/
│ │ │ │ │ ├── CommandsExecutor.cs
│ │ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ │ ├── Inbox/
│ │ │ │ │ │ ├── InboxMessageDto.cs
│ │ │ │ │ │ ├── ProcessInboxCommand.cs
│ │ │ │ │ │ ├── ProcessInboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessInboxJob.cs
│ │ │ │ │ ├── InternalCommands/
│ │ │ │ │ │ ├── CommandsScheduler.cs
│ │ │ │ │ │ ├── InternalCommandsModule.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommand.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommandHandler.cs
│ │ │ │ │ │ └── ProcessInternalCommandsJob.cs
│ │ │ │ │ ├── LoggingCommandHandlerDecorator.cs
│ │ │ │ │ ├── LoggingCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── Outbox/
│ │ │ │ │ │ ├── OutboxMessageDto.cs
│ │ │ │ │ │ ├── OutboxModule.cs
│ │ │ │ │ │ ├── ProcessOutboxCommand.cs
│ │ │ │ │ │ ├── ProcessOutboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessOutboxJob.cs
│ │ │ │ │ ├── ProcessingModule.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerDecorator.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── ValidationCommandHandlerDecorator.cs
│ │ │ │ │ └── ValidationCommandHandlerWithResultDecorator.cs
│ │ │ │ ├── Quartz/
│ │ │ │ │ ├── QuartzModule.cs
│ │ │ │ │ ├── QuartzStartup.cs
│ │ │ │ │ └── SerilogLogProvider.cs
│ │ │ │ └── Users/
│ │ │ │ └── UserContext.cs
│ │ │ ├── Domain/
│ │ │ │ ├── MeetingGroupProposals/
│ │ │ │ │ ├── MeetingGroupProposalEntityTypeConfiguration.cs
│ │ │ │ │ └── MeetingGroupProposalRepository.cs
│ │ │ │ └── Members/
│ │ │ │ ├── MemberEntityTypeConfiguration.cs
│ │ │ │ └── MemberRepository.cs
│ │ │ ├── InternalCommands/
│ │ │ │ └── InternalCommandEntityTypeConfiguration.cs
│ │ │ └── Outbox/
│ │ │ ├── OutboxAccessor.cs
│ │ │ └── OutboxMessageEntityTypeConfiguration.cs
│ │ ├── IntegrationEvents/
│ │ │ ├── CompanyName.MyMeetings.Modules.Administration.IntegrationEvents.csproj
│ │ │ └── MeetingGroupProposals/
│ │ │ └── MeetingGroupProposalAcceptedIntegrationEvent.cs
│ │ └── Tests/
│ │ ├── ArchTests/
│ │ │ ├── Application/
│ │ │ │ └── ApplicationTests.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Administration.ArchTests.csproj
│ │ │ ├── Domain/
│ │ │ │ └── DomainTests.cs
│ │ │ ├── Module/
│ │ │ │ └── LayersTests.cs
│ │ │ └── SeedWork/
│ │ │ └── TestBase.cs
│ │ ├── IntegrationTests/
│ │ │ ├── AssemblyInfo.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Administration.IntegrationTests.csproj
│ │ │ ├── MeetingGroupProposals/
│ │ │ │ ├── MeetingGroupProposalSampleData.cs
│ │ │ │ └── MeetingGroupProposalTests.cs
│ │ │ ├── Members/
│ │ │ │ ├── CreateMemberTests.cs
│ │ │ │ └── MemberSampleData.cs
│ │ │ └── SeedWork/
│ │ │ ├── ExecutionContextMock.cs
│ │ │ ├── OutboxMessagesHelper.cs
│ │ │ └── TestBase.cs
│ │ └── UnitTests/
│ │ ├── CompanyName.MyMeetings.Modules.Administration.Domain.UnitTests.csproj
│ │ ├── MeetingGroupProposals/
│ │ │ └── MeetingGroupProposalTests.cs
│ │ ├── Members/
│ │ │ └── MemberTests.cs
│ │ └── SeedWork/
│ │ ├── DomainEventsTestHelper.cs
│ │ └── TestBase.cs
│ ├── Meetings/
│ │ ├── Application/
│ │ │ ├── CompanyName.MyMeetings.Modules.Meetings.Application.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── Commands/
│ │ │ │ │ ├── ICommandHandler.cs
│ │ │ │ │ ├── ICommandsScheduler.cs
│ │ │ │ │ └── InternalCommandBase.cs
│ │ │ │ └── Queries/
│ │ │ │ └── IQueryHandler.cs
│ │ │ ├── Contracts/
│ │ │ │ ├── CommandBase.cs
│ │ │ │ ├── ICommand.cs
│ │ │ │ ├── IMeetingsModule.cs
│ │ │ │ ├── IQuery.cs
│ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ └── QueryBase.cs
│ │ │ ├── Countries/
│ │ │ │ ├── CountryDto.cs
│ │ │ │ ├── GetAllCountriesQuery.cs
│ │ │ │ └── GetAllCountriesQueryHandler.cs
│ │ │ ├── MeetingCommentingConfigurations/
│ │ │ │ ├── DisableMeetingCommentingConfiguration/
│ │ │ │ │ ├── DisableMeetingCommentingConfigurationCommand.cs
│ │ │ │ │ └── DisableMeetingCommentingConfigurationCommandHandler.cs
│ │ │ │ ├── EnableMeetingCommentingConfiguration/
│ │ │ │ │ ├── EnableMeetingCommentingConfigurationCommand.cs
│ │ │ │ │ └── EnableMeetingCommentingConfigurationCommandHandler.cs
│ │ │ │ ├── GetMeetingCommentingConfiguration/
│ │ │ │ │ ├── GetMeetingCommentingConfigurationQuery.cs
│ │ │ │ │ ├── GetMeetingCommentingConfigurationQueryHandler.cs
│ │ │ │ │ └── MeetingCommentingConfigurationDto.cs
│ │ │ │ └── MeetingCreatedEventHandler.cs
│ │ │ ├── MeetingComments/
│ │ │ │ ├── AddMeetingComment/
│ │ │ │ │ ├── AddMeetingCommentCommand.cs
│ │ │ │ │ ├── AddMeetingCommentCommandHandler.cs
│ │ │ │ │ └── AddMeetingCommentCommandValidator.cs
│ │ │ │ ├── AddMeetingCommentLike/
│ │ │ │ │ ├── AddMeetingCommentLikeCommand.cs
│ │ │ │ │ └── AddMeetingCommentLikeCommandHandler.cs
│ │ │ │ ├── AddMeetingCommentReply/
│ │ │ │ │ ├── AddReplyToMeetingCommentCommand.cs
│ │ │ │ │ └── AddReplyToMeetingCommentCommandHandler.cs
│ │ │ │ ├── EditMeetingComment/
│ │ │ │ │ ├── EditMeetingCommentCommand.cs
│ │ │ │ │ ├── EditMeetingCommentCommandHandler.cs
│ │ │ │ │ └── EditMeetingCommentCommandValidator.cs
│ │ │ │ ├── GetMeetingCommentLikers/
│ │ │ │ │ ├── GetMeetingCommentLikersQuery.cs
│ │ │ │ │ ├── GetMeetingCommentLikersQueryHandler.cs
│ │ │ │ │ └── MeetingCommentLikerDto.cs
│ │ │ │ ├── GetMeetingComments/
│ │ │ │ │ ├── GetMeetingCommentsQuery.cs
│ │ │ │ │ ├── GetMeetingCommentsQueryHandler.cs
│ │ │ │ │ └── MeetingCommentDto.cs
│ │ │ │ ├── MeetingCommentLikedNotification.cs
│ │ │ │ ├── MeetingCommentLikedNotificationHandler.cs
│ │ │ │ ├── MeetingCommentUnlikeNotificationHandler.cs
│ │ │ │ ├── MeetingCommentUnlikedNotification.cs
│ │ │ │ ├── RemoveMeetingComment/
│ │ │ │ │ ├── RemoveMeetingCommentCommand.cs
│ │ │ │ │ └── RemoveMeetingCommentCommandHandler.cs
│ │ │ │ └── RemoveMeetingCommentLike/
│ │ │ │ ├── RemoveMeetingCommentLikeCommand.cs
│ │ │ │ └── RemoveMeetingCommentLikeCommandHandler.cs
│ │ │ ├── MeetingGroupProposals/
│ │ │ │ ├── AcceptMeetingGroupProposal/
│ │ │ │ │ ├── AcceptMeetingGroupProposalCommand.cs
│ │ │ │ │ ├── AcceptMeetingGroupProposalCommandHandler.cs
│ │ │ │ │ ├── AcceptMeetingGroupProposalCommandValidator.cs
│ │ │ │ │ ├── MeetingGroupProposalAcceptedNotification.cs
│ │ │ │ │ └── MeetingGroupProposalAcceptedNotificationHandler.cs
│ │ │ │ ├── GetAllMeetingGroupProposals/
│ │ │ │ │ ├── GetAllMeetingGroupProposalsQuery.cs
│ │ │ │ │ └── GetAllMeetingGroupProposalsQueryHandler.cs
│ │ │ │ ├── GetMeetingGroupProposal/
│ │ │ │ │ ├── GetMeetingGroupProposalQuery.cs
│ │ │ │ │ ├── GetMeetingGroupProposalQueryHandler.cs
│ │ │ │ │ └── MeetingGroupProposalDto.cs
│ │ │ │ ├── GetMemberMeetingGroupProposals/
│ │ │ │ │ ├── GetMemberMeetingGroupProposalsQuery.cs
│ │ │ │ │ └── GetMemberMeetingGroupProposalsQueryHandler.cs
│ │ │ │ ├── MeetingGroupProposalAcceptedIntegrationEventHandler.cs
│ │ │ │ ├── MeetingGroupProposedNotification.cs
│ │ │ │ ├── MeetingGroupProposedNotificationHandler.cs
│ │ │ │ └── ProposeMeetingGroup/
│ │ │ │ ├── ProposeMeetingGroupCommand.cs
│ │ │ │ ├── ProposeMeetingGroupCommandHandler.cs
│ │ │ │ └── ProposeMeetingGroupCommandValidator.cs
│ │ │ ├── MeetingGroups/
│ │ │ │ ├── CreateNewMeetingGroup/
│ │ │ │ │ ├── CreateNewMeetingGroupCommand.cs
│ │ │ │ │ └── CreateNewMeetingGroupCommandHandler.cs
│ │ │ │ ├── EditMeetingGroupGeneralAttributes/
│ │ │ │ │ ├── EditMeetingGroupGeneralAttributesCommand.cs
│ │ │ │ │ └── EditMeetingGroupGeneralAttributesCommandHandler.cs
│ │ │ │ ├── GetAllMeetingGroups/
│ │ │ │ │ ├── GetAllMeetingGroupsQuery.cs
│ │ │ │ │ ├── GetAllMeetingGroupsQueryHandler.cs
│ │ │ │ │ └── MeetingGroupDto.cs
│ │ │ │ ├── GetAuthenticationMemberMeetingGroups/
│ │ │ │ │ ├── GetAuthenticationMemberMeetingGroupsQuery.cs
│ │ │ │ │ ├── GetAuthenticationMemberMeetingGroupsQueryHandler.cs
│ │ │ │ │ └── MemberMeetingGroupDto.cs
│ │ │ │ ├── GetMeetingGroupDetails/
│ │ │ │ │ ├── GetMeetingGroupDetailsQuery.cs
│ │ │ │ │ ├── GetMeetingGroupDetailsQueryHandler.cs
│ │ │ │ │ └── MeetingGroupDetailsDto.cs
│ │ │ │ ├── JoinToGroup/
│ │ │ │ │ ├── JoinToGroupCommand.cs
│ │ │ │ │ └── JoinToGroupCommandHandler.cs
│ │ │ │ ├── LeaveMeetingGroup/
│ │ │ │ │ ├── LeaveMeetingGroupCommand.cs
│ │ │ │ │ └── LeaveMeetingGroupCommandHandler.cs
│ │ │ │ ├── MeetingGroupCreatedNotification.cs
│ │ │ │ ├── MeetingGroupCreatedSendEmailHandler.cs
│ │ │ │ ├── SendMeetingGroupCreatedEmail/
│ │ │ │ │ ├── SendMeetingGroupCreatedEmailCommand.cs
│ │ │ │ │ └── SendMeetingGroupCreatedEmailCommandHandler.cs
│ │ │ │ └── SetMeetingGroupExpirationDate/
│ │ │ │ ├── SetMeetingGroupExpirationDateCommand.cs
│ │ │ │ └── SetMeetingGroupExpirationDateCommandHandler.cs
│ │ │ ├── Meetings/
│ │ │ │ ├── AddMeetingAttendee/
│ │ │ │ │ ├── AddMeetingAttendeeCommand.cs
│ │ │ │ │ └── AddMeetingAttendeeCommandHandler.cs
│ │ │ │ ├── AddMeetingNotAttendee/
│ │ │ │ │ ├── AddMeetingNotAttendeeCommand.cs
│ │ │ │ │ └── AddMeetingNotAttendeeCommandHandler.cs
│ │ │ │ ├── CancelMeeting/
│ │ │ │ │ ├── CancelMeetingCommand.cs
│ │ │ │ │ └── CancelMeetingCommandHandler.cs
│ │ │ │ ├── ChangeMeetingMainAttributes/
│ │ │ │ │ ├── ChangeMeetingMainAttributesCommand.cs
│ │ │ │ │ └── ChangeMeetingMainAttributesCommandHandler.cs
│ │ │ │ ├── ChangeNotAttendeeDecision/
│ │ │ │ │ ├── ChangeNotAttendeeDecisionCommand.cs
│ │ │ │ │ └── ChangeNotAttendeeDecisionCommandHandler.cs
│ │ │ │ ├── CreateMeeting/
│ │ │ │ │ ├── CreateMeetingCommand.cs
│ │ │ │ │ └── CreateMeetingCommandHandler.cs
│ │ │ │ ├── GetAuthenticatedMemberMeetings/
│ │ │ │ │ ├── GetAuthenticatedMemberMeetingsQuery.cs
│ │ │ │ │ ├── GetAuthenticatedMemberMeetingsQueryHandler.cs
│ │ │ │ │ └── MemberMeetingDto.cs
│ │ │ │ ├── GetMeetingAttendees/
│ │ │ │ │ ├── GetMeetingAttendeesQuery.cs
│ │ │ │ │ ├── GetMeetingAttendeesQueryHandler.cs
│ │ │ │ │ └── MeetingAttendeeDto.cs
│ │ │ │ ├── GetMeetingDetails/
│ │ │ │ │ ├── GetMeetingDetailsQuery.cs
│ │ │ │ │ ├── GetMeetingDetailsQueryHandler.cs
│ │ │ │ │ └── MeetingDetailsDto.cs
│ │ │ │ ├── MarkMeetingAttendeeFeeAsPayedCommand.cs
│ │ │ │ ├── MarkMeetingAttendeeFeeAsPayedCommandHandler.cs
│ │ │ │ ├── MeetingDto.cs
│ │ │ │ ├── MeetingFeePaidIntegrationEventHandler.cs
│ │ │ │ ├── MeetingsQueryHelper.cs
│ │ │ │ ├── RemoveMeetingAttendee/
│ │ │ │ │ ├── RemoveMeetingAttendeeCommand.cs
│ │ │ │ │ └── RemoveMeetingAttendeeCommandHandler.cs
│ │ │ │ ├── SendMeetingAttendeeAddedEmail/
│ │ │ │ │ ├── MeetingAttendeeAddedNotification.cs
│ │ │ │ │ ├── MeetingAttendeeAddedNotificationHandler.cs
│ │ │ │ │ ├── MeetingAttendeeAddedPublishEventNotificationHandler.cs
│ │ │ │ │ ├── SendMeetingAttendeeAddedEmailCommand.cs
│ │ │ │ │ └── SendMeetingAttendeeAddedEmailCommandHandler.cs
│ │ │ │ ├── SetMeetingAttendeeRole/
│ │ │ │ │ ├── SetMeetingAttendeeRoleCommand.cs
│ │ │ │ │ └── SetMeetingAttendeeRoleCommandHandler.cs
│ │ │ │ ├── SetMeetingHostRole/
│ │ │ │ │ ├── SetMeetingHostRoleCommand.cs
│ │ │ │ │ └── SetMeetingHostRoleCommandHandler.cs
│ │ │ │ ├── SignOffMemberFromWaitlist/
│ │ │ │ │ ├── SignOffMemberFromWaitlistCommand.cs
│ │ │ │ │ └── SignOffMemberFromWaitlistCommandHandler.cs
│ │ │ │ └── SignUpMemberToWaitlist/
│ │ │ │ ├── SignUpMemberToWaitlistCommand.cs
│ │ │ │ └── SignUpMemberToWaitlistCommandHandler.cs
│ │ │ ├── MemberSubscriptions/
│ │ │ │ ├── ChangeSubscriptionExpirationDateForMember/
│ │ │ │ │ ├── ChangeSubscriptionExpirationDateForMemberCommand.cs
│ │ │ │ │ └── ChangeSubscriptionExpirationDateForMemberCommandHandler.cs
│ │ │ │ ├── MemberSubscriptionExpirationDateChangedNotification.cs
│ │ │ │ ├── MemberSubscriptionExpirationDateChangedNotificationHandler.cs
│ │ │ │ └── SubscriptionExpirationDateChangedIntegrationEventHandler.cs
│ │ │ └── Members/
│ │ │ ├── CreateMember/
│ │ │ │ ├── CreateMemberCommand.cs
│ │ │ │ ├── CreateMemberCommandHandler.cs
│ │ │ │ ├── MemberCratedNotificationHandler.cs
│ │ │ │ ├── MemberCreatedNotification.cs
│ │ │ │ └── NewUserRegisteredIntegrationEventHandler.cs
│ │ │ ├── MemberContext.cs
│ │ │ ├── MemberDto.cs
│ │ │ └── MembersQueryHelper.cs
│ │ ├── Domain/
│ │ │ ├── CompanyName.MyMeetings.Modules.Meetings.Domain.csproj
│ │ │ ├── MeetingCommentingConfigurations/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingCommentingConfigurationCreatedDomainEvent.cs
│ │ │ │ │ ├── MeetingCommentingDisabledDomainEvent.cs
│ │ │ │ │ └── MeetingCommentingEnabledDomainEvent.cs
│ │ │ │ ├── IMeetingCommentingConfigurationRepository.cs
│ │ │ │ ├── MeetingCommentingConfiguration.cs
│ │ │ │ ├── MeetingCommentingConfigurationId.cs
│ │ │ │ └── Rules/
│ │ │ │ ├── MeetingCommentingCanBeDisabledOnlyByGroupOrganizerRule.cs
│ │ │ │ └── MeetingCommentingCanBeEnabledOnlyByGroupOrganizerRule.cs
│ │ │ ├── MeetingComments/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingCommentAddedDomainEvent.cs
│ │ │ │ │ ├── MeetingCommentEditedDomainEvent.cs
│ │ │ │ │ ├── MeetingCommentRemovedDomainEvent.cs
│ │ │ │ │ └── ReplyToMeetingCommentAddedDomainEvent.cs
│ │ │ │ ├── IMeetingCommentRepository.cs
│ │ │ │ ├── MeetingComment.cs
│ │ │ │ ├── MeetingCommentId.cs
│ │ │ │ └── Rules/
│ │ │ │ ├── CommentCanBeAddedOnlyByMeetingGroupMemberRule.cs
│ │ │ │ ├── CommentCanBeCreatedOnlyIfCommentingForMeetingEnabledRule.cs
│ │ │ │ ├── CommentCanBeEditedOnlyIfCommentingForMeetingEnabledRule.cs
│ │ │ │ ├── CommentCanBeLikedOnlyByMeetingGroupMemberRule.cs
│ │ │ │ ├── CommentCannotBeLikedByTheSameMemberMoreThanOnceRule.cs
│ │ │ │ ├── CommentTextMustBeProvidedRule.cs
│ │ │ │ ├── MeetingCommentCanBeEditedOnlyByAuthorRule.cs
│ │ │ │ ├── MeetingCommentCanBeRemovedOnlyByAuthorOrGroupOrganizerRule.cs
│ │ │ │ └── RemovingReasonCanBeProvidedOnlyByGroupOrganizerRule.cs
│ │ │ ├── MeetingGroupProposals/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingGroupProposalAcceptedDomainEvent.cs
│ │ │ │ │ └── MeetingGroupProposedDomainEvent.cs
│ │ │ │ ├── IMeetingGroupProposalRepository.cs
│ │ │ │ ├── MeetingGroupProposal.cs
│ │ │ │ ├── MeetingGroupProposalId.cs
│ │ │ │ ├── MeetingGroupProposalStatus.cs
│ │ │ │ └── Rules/
│ │ │ │ └── MeetingGroupProposalCannotBeAcceptedMoreThanOnceRule.cs
│ │ │ ├── MeetingGroups/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingAttendeeChangedDecisionDomainEvent.cs
│ │ │ │ │ ├── MeetingGroupCreatedDomainEvent.cs
│ │ │ │ │ ├── MeetingGroupGeneralAttributesEditedDomainEvent.cs
│ │ │ │ │ ├── MeetingGroupMemberLeftGroupDomainEvent.cs
│ │ │ │ │ ├── MeetingGroupPaymentInfoUpdatedDomainEvent.cs
│ │ │ │ │ ├── MeetingNotAttendeeChangedDecisionDomainEvent.cs
│ │ │ │ │ └── NewMeetingGroupMemberJoinedDomainEvent.cs
│ │ │ │ ├── IMeetingGroupRepository.cs
│ │ │ │ ├── MeetingGroup.cs
│ │ │ │ ├── MeetingGroupId.cs
│ │ │ │ ├── MeetingGroupLocation.cs
│ │ │ │ ├── MeetingGroupMember.cs
│ │ │ │ ├── MeetingGroupMemberRole.cs
│ │ │ │ ├── Policies/
│ │ │ │ │ ├── MeetingGroupExpirationDatePolicy.cs
│ │ │ │ │ └── MeetingGroupMemberData.cs
│ │ │ │ └── Rules/
│ │ │ │ ├── MeetingCanBeOrganizedOnlyByPayedGroupRule.cs
│ │ │ │ ├── MeetingGroupMemberCannotBeAddedTwiceRule.cs
│ │ │ │ ├── MeetingHostMustBeAMeetingGroupMemberRule.cs
│ │ │ │ └── NotActualGroupMemberCannotLeaveGroupRule.cs
│ │ │ ├── MeetingMemberCommentLikes/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingCommentLikedDomainEvent.cs
│ │ │ │ │ └── MeetingCommentUnlikedDomainEvent.cs
│ │ │ │ ├── IMeetingMemberCommentLikesRepository.cs
│ │ │ │ ├── MeetingMemberCommentLike.cs
│ │ │ │ └── MeetingMemberCommentLikeId.cs
│ │ │ ├── Meetings/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingAttendeeAddedDomainEvent.cs
│ │ │ │ │ ├── MeetingAttendeeFeePaidDomainEvent.cs
│ │ │ │ │ ├── MeetingAttendeeRemovedDomainEvent.cs
│ │ │ │ │ ├── MeetingCanceledDomainEvent.cs
│ │ │ │ │ ├── MeetingCreatedDomainEvent.cs
│ │ │ │ │ ├── MeetingEditedDomainEvent.cs
│ │ │ │ │ ├── MeetingMainAttributesChangedDomainEvent.cs
│ │ │ │ │ ├── MeetingNotAttendeeAddedDomainEvent.cs
│ │ │ │ │ ├── MeetingWaitlistMemberAddedDomainEvent.cs
│ │ │ │ │ ├── MemberSetAsAttendeeDomainEvent.cs
│ │ │ │ │ ├── MemberSignedOffFromMeetingWaitlistDomainEvent.cs
│ │ │ │ │ └── NewMeetingHostSetDomainEvent.cs
│ │ │ │ ├── IMeetingRepository.cs
│ │ │ │ ├── Meeting.cs
│ │ │ │ ├── MeetingAttendee.cs
│ │ │ │ ├── MeetingAttendeeRole.cs
│ │ │ │ ├── MeetingId.cs
│ │ │ │ ├── MeetingLimits.cs
│ │ │ │ ├── MeetingLocation.cs
│ │ │ │ ├── MeetingNotAttendee.cs
│ │ │ │ ├── MeetingTerm.cs
│ │ │ │ ├── MeetingWaitlistMember.cs
│ │ │ │ ├── MoneyValue.cs
│ │ │ │ ├── Rules/
│ │ │ │ │ ├── AttendeeCanBeAddedOnlyInRsvpTermRule.cs
│ │ │ │ │ ├── AttendeesLimitCannotBeChangedToSmallerThanActiveAttendeesRule.cs
│ │ │ │ │ ├── MeetingAttendeeMustBeAMemberOfGroupRule.cs
│ │ │ │ │ ├── MeetingAttendeesLimitCannotBeNegativeRule.cs
│ │ │ │ │ ├── MeetingAttendeesLimitMustBeGreaterThanGuestsLimitRule.cs
│ │ │ │ │ ├── MeetingAttendeesNumberIsAboveLimitRule.cs
│ │ │ │ │ ├── MeetingCannotBeChangedAfterStartRule.cs
│ │ │ │ │ ├── MeetingGuestsLimitCannotBeNegativeRule.cs
│ │ │ │ │ ├── MeetingGuestsNumberIsAboveLimitRule.cs
│ │ │ │ │ ├── MeetingMustHaveAtLeastOneHostRule.cs
│ │ │ │ │ ├── MemberCannotBeAnAttendeeOfMeetingMoreThanOnceRule.cs
│ │ │ │ │ ├── MemberCannotBeMoreThanOnceOnMeetingWaitlistRule.cs
│ │ │ │ │ ├── MemberCannotBeNotAttendeeTwiceRule.cs
│ │ │ │ │ ├── MemberCannotHaveSetAttendeeRoleMoreThanOnceRule.cs
│ │ │ │ │ ├── MemberOnWaitlistMustBeAMemberOfGroupRule.cs
│ │ │ │ │ ├── NotActiveMemberOfWaitlistCannotBeSignedOffRule.cs
│ │ │ │ │ ├── NotActiveNotAttendeeCannotChangeDecisionRule.cs
│ │ │ │ │ ├── OnlyActiveAttendeeCanBeRemovedFromMeetingRule.cs
│ │ │ │ │ ├── OnlyMeetingAttendeeCanHaveChangedRoleRule.cs
│ │ │ │ │ ├── OnlyMeetingOrGroupOrganizerCanSetMeetingMemberRolesRule.cs
│ │ │ │ │ └── ReasonOfRemovingAttendeeFromMeetingMustBeProvidedRule.cs
│ │ │ │ └── Term.cs
│ │ │ ├── Members/
│ │ │ │ ├── Events/
│ │ │ │ │ └── MemberCreatedDomainEvent.cs
│ │ │ │ ├── IMemberContext.cs
│ │ │ │ ├── IMemberRepository.cs
│ │ │ │ ├── MeetingGroupMemberData.cs
│ │ │ │ ├── Member.cs
│ │ │ │ ├── MemberId.cs
│ │ │ │ └── MemberSubscriptions/
│ │ │ │ ├── Events/
│ │ │ │ │ └── MemberSubscriptionExpirationDateChangedDomainEvent.cs
│ │ │ │ ├── IMemberSubscriptionRepository.cs
│ │ │ │ ├── MemberSubscription.cs
│ │ │ │ └── MemberSubscriptionId.cs
│ │ │ └── SharedKernel/
│ │ │ └── SystemClock.cs
│ │ ├── Infrastructure/
│ │ │ ├── CompanyName.MyMeetings.Modules.Meetings.Infrastructure.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── AllConstructorFinder.cs
│ │ │ │ ├── Assemblies.cs
│ │ │ │ ├── Authentication/
│ │ │ │ │ └── AuthenticationModule.cs
│ │ │ │ ├── DataAccess/
│ │ │ │ │ └── DataAccessModule.cs
│ │ │ │ ├── Email/
│ │ │ │ │ └── EmailModule.cs
│ │ │ │ ├── EventsBus/
│ │ │ │ │ ├── EventsBusModule.cs
│ │ │ │ │ ├── EventsBusStartup.cs
│ │ │ │ │ └── IntegrationEventGenericHandler.cs
│ │ │ │ ├── Logging/
│ │ │ │ │ └── LoggingModule.cs
│ │ │ │ ├── Mediation/
│ │ │ │ │ └── MediatorModule.cs
│ │ │ │ ├── MeetingsCompositionRoot.cs
│ │ │ │ ├── MeetingsStartup.cs
│ │ │ │ ├── Processing/
│ │ │ │ │ ├── CommandsExecutor.cs
│ │ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ │ ├── Inbox/
│ │ │ │ │ │ ├── InboxMessageDto.cs
│ │ │ │ │ │ ├── ProcessInboxCommand.cs
│ │ │ │ │ │ ├── ProcessInboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessInboxJob.cs
│ │ │ │ │ ├── InternalCommands/
│ │ │ │ │ │ ├── CommandsScheduler.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommand.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommandHandler.cs
│ │ │ │ │ │ └── ProcessInternalCommandsJob.cs
│ │ │ │ │ ├── LoggingCommandHandlerDecorator.cs
│ │ │ │ │ ├── LoggingCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── Outbox/
│ │ │ │ │ │ ├── OutboxMessageDto.cs
│ │ │ │ │ │ ├── OutboxModule.cs
│ │ │ │ │ │ ├── ProcessOutboxCommand.cs
│ │ │ │ │ │ ├── ProcessOutboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessOutboxJob.cs
│ │ │ │ │ ├── ProcessingModule.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerDecorator.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── ValidationCommandHandlerDecorator.cs
│ │ │ │ │ └── ValidationCommandHandlerWithResultDecorator.cs
│ │ │ │ └── Quartz/
│ │ │ │ ├── QuartzModule.cs
│ │ │ │ ├── QuartzStartup.cs
│ │ │ │ └── SerilogLogProvider.cs
│ │ │ ├── Domain/
│ │ │ │ ├── MeetingCommentingConfigurations/
│ │ │ │ │ ├── MeetingCommentingConfigurationEntityTypeConfiguration.cs
│ │ │ │ │ └── MeetingCommentingConfigurationRepository.cs
│ │ │ │ ├── MeetingComments/
│ │ │ │ │ ├── MeetingCommentEntityTypeConfiguration.cs
│ │ │ │ │ └── MeetingCommentRepository.cs
│ │ │ │ ├── MeetingGroupProposals/
│ │ │ │ │ ├── MeetingGroupProposalEntityTypeConfiguration.cs
│ │ │ │ │ └── MeetingGroupProposalRepository.cs
│ │ │ │ ├── MeetingGroups/
│ │ │ │ │ ├── MeetingGroupRepository.cs
│ │ │ │ │ └── MeetingGroupsEntityTypeConfiguration.cs
│ │ │ │ ├── MeetingMemberCommentLikes/
│ │ │ │ │ ├── MeetingMemberCommentLikeEntityTypeConfiguration.cs
│ │ │ │ │ └── MeetingMemberCommentLikeRepository.cs
│ │ │ │ ├── Meetings/
│ │ │ │ │ ├── MeetingEntityTypeConfiguration.cs
│ │ │ │ │ └── MeetingRepository.cs
│ │ │ │ └── Members/
│ │ │ │ ├── MemberEntityTypeConfiguration.cs
│ │ │ │ ├── MemberRepository.cs
│ │ │ │ └── MemberSubscriptions/
│ │ │ │ ├── MemberSubscriptionEntityTypeConfiguration.cs
│ │ │ │ └── MemberSubscriptionRepository.cs
│ │ │ ├── InternalCommands/
│ │ │ │ └── InternalCommandEntityTypeConfiguration.cs
│ │ │ ├── MeetingsContext.cs
│ │ │ ├── MeetingsModule.cs
│ │ │ └── Outbox/
│ │ │ ├── OutboxAccessor.cs
│ │ │ └── OutboxMessageEntityTypeConfiguration.cs
│ │ ├── IntegrationEvents/
│ │ │ ├── CompanyName.MyMeetings.Modules.Meetings.IntegrationEvents.csproj
│ │ │ ├── MeetingAttendeeAddedIntegrationEvent.cs
│ │ │ ├── MeetingGroupProposedIntegrationEvent.cs
│ │ │ └── MemberCreatedIntegrationEvent.cs
│ │ └── Tests/
│ │ ├── ArchTests/
│ │ │ ├── Application/
│ │ │ │ └── ApplicationTests.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Meetings.ArchTests.csproj
│ │ │ ├── Domain/
│ │ │ │ └── DomainTests.cs
│ │ │ ├── Module/
│ │ │ │ └── LayersTests.cs
│ │ │ └── SeedWork/
│ │ │ └── TestBase.cs
│ │ ├── IntegrationTests/
│ │ │ ├── AssemblyInfo.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Meetings.IntegrationTests.csproj
│ │ │ ├── Countries/
│ │ │ │ ├── 0001_SeedCountries.sql
│ │ │ │ └── GetCountriesTests.cs
│ │ │ ├── MeetingCommentLikes/
│ │ │ │ ├── AddMeetingCommentLikeTests.cs
│ │ │ │ ├── GetLikedMeetingCommentProbe.cs
│ │ │ │ ├── GetMeetingCommentsProbe.cs
│ │ │ │ └── RemoveMeetingCommentLikeTests.cs
│ │ │ ├── MeetingCommentingConfigurations/
│ │ │ │ ├── CreateMeetingCommentingConfigurationTests.cs
│ │ │ │ ├── DisableMeetingCommentingConfigurationTests.cs
│ │ │ │ └── EnableMeetingCommentingConfigurationTests.cs
│ │ │ ├── MeetingComments/
│ │ │ │ ├── AddMeetingCommentTests.cs
│ │ │ │ ├── AddReplyToMeetingCommentTests.cs
│ │ │ │ ├── EditMeetingCommentTests.cs
│ │ │ │ ├── GetMeetingCommentsTests.cs
│ │ │ │ └── RemoveMeetingCommentTests.cs
│ │ │ ├── MeetingGroupProposals/
│ │ │ │ ├── GetMeetingGroupProposalsTests.cs
│ │ │ │ ├── MeetingGroupProposalSampleData.cs
│ │ │ │ └── ProposeMeetingGroupTests.cs
│ │ │ ├── MeetingGroups/
│ │ │ │ └── CreateNewMeetingGroupTests.cs
│ │ │ ├── Meetings/
│ │ │ │ ├── MeetingCreateTests.cs
│ │ │ │ └── MeetingHelper.cs
│ │ │ └── SeedWork/
│ │ │ ├── EventsBusMock.cs
│ │ │ ├── ExecutionContextMock.cs
│ │ │ ├── OutboxMessagesHelper.cs
│ │ │ └── TestBase.cs
│ │ └── UnitTests/
│ │ ├── CompanyName.MyMeetings.Modules.Meetings.Domain.UnitTests.csproj
│ │ ├── MeetingGroupProposals/
│ │ │ └── MeetingGroupProposalTests.cs
│ │ ├── MeetingGroups/
│ │ │ └── MeetingGroupTests.cs
│ │ ├── Meetings/
│ │ │ ├── MeetingAddAttendeeTests.cs
│ │ │ ├── MeetingAddNotAttendeeTests.cs
│ │ │ ├── MeetingCommentTests.cs
│ │ │ ├── MeetingCommentingConfigurationTests.cs
│ │ │ ├── MeetingLimitsTests.cs
│ │ │ ├── MeetingRolesTests.cs
│ │ │ ├── MeetingTests.cs
│ │ │ ├── MeetingTestsBase.cs
│ │ │ └── MeetingWaitlistTests.cs
│ │ ├── Members/
│ │ │ └── MemberTests.cs
│ │ └── SeedWork/
│ │ ├── DomainEventsTestHelper.cs
│ │ └── TestBase.cs
│ ├── Payments/
│ │ ├── Application/
│ │ │ ├── CompanyName.MyMeetings.Modules.Payments.Application.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── Commands/
│ │ │ │ │ ├── ICommandHandler.cs
│ │ │ │ │ ├── ICommandsScheduler.cs
│ │ │ │ │ └── InternalCommandBase.cs
│ │ │ │ ├── Projections/
│ │ │ │ │ ├── IProjector.cs
│ │ │ │ │ └── ProjectorBase.cs
│ │ │ │ └── Queries/
│ │ │ │ └── IQueryHandler.cs
│ │ │ ├── Contracts/
│ │ │ │ ├── CommandBase.cs
│ │ │ │ ├── ICommand.cs
│ │ │ │ ├── IPaymentsModule.cs
│ │ │ │ ├── IQuery.cs
│ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ └── QueryBase.cs
│ │ │ ├── MeetingFees/
│ │ │ │ ├── CreateMeetingFee/
│ │ │ │ │ ├── CreateMeetingFeeCommand.cs
│ │ │ │ │ └── CreateMeetingFeeCommandHandler.cs
│ │ │ │ ├── CreateMeetingFeePayment/
│ │ │ │ │ ├── CreateMeetingFeePaymentCommand.cs
│ │ │ │ │ └── CreateMeetingFeePaymentCommandHandler.cs
│ │ │ │ ├── GetMeetingFees/
│ │ │ │ │ ├── GetMeetingFeesQuery.cs
│ │ │ │ │ ├── GetMeetingFeesQueryHandler.cs
│ │ │ │ │ ├── MeetingFeeDto.cs
│ │ │ │ │ └── MeetingFeesProjector.cs
│ │ │ │ ├── MarkMeetingFeeAsPaid/
│ │ │ │ │ ├── MarkMeetingFeeAsPaidCommand.cs
│ │ │ │ │ ├── MarkMeetingFeeAsPaidCommandHandler.cs
│ │ │ │ │ ├── MeetingFeePaidNotification.cs
│ │ │ │ │ └── MeetingFeePaidNotificationHandler.cs
│ │ │ │ ├── MarkMeetingFeePaymentAsPaid/
│ │ │ │ │ ├── MarkMeetingFeePaymentAsPaidCommand.cs
│ │ │ │ │ ├── MarkMeetingFeePaymentAsPaidCommandHandler.cs
│ │ │ │ │ ├── MeetingFeePaymentPaidNotification.cs
│ │ │ │ │ └── MeetingFeePaymentPaidNotificationHandler.cs
│ │ │ │ └── MeetingAttendeeAddedIntegrationEventHandler.cs
│ │ │ ├── Payers/
│ │ │ │ ├── CreatePayer/
│ │ │ │ │ ├── CreatePayerCommand.cs
│ │ │ │ │ ├── CreatePayerCommandHandler.cs
│ │ │ │ │ └── NewUserRegisteredIntegrationEventHandler.cs
│ │ │ │ ├── GetPayer/
│ │ │ │ │ ├── GetPayerQuery.cs
│ │ │ │ │ ├── GetPayerQueryHandler.cs
│ │ │ │ │ ├── PayerDetailsProjector.cs
│ │ │ │ │ └── PayerDto.cs
│ │ │ │ └── GetPayerEmail/
│ │ │ │ └── PayerEmailProvider.cs
│ │ │ ├── PriceListItems/
│ │ │ │ ├── ActivatePriceListItem/
│ │ │ │ │ ├── ActivatePriceListItemCommand.cs
│ │ │ │ │ └── ActivatePriceListItemCommandHandler.cs
│ │ │ │ ├── ChangePriceListItemAttributes/
│ │ │ │ │ ├── ChangePriceListItemAttributesCommand.cs
│ │ │ │ │ └── ChangePriceListItemAttributesCommandHandler.cs
│ │ │ │ ├── CreatePriceListItem/
│ │ │ │ │ ├── CreatePriceListItemCommand.cs
│ │ │ │ │ └── CreatePriceListItemCommandHandler.cs
│ │ │ │ ├── DeactivatePriceListItem/
│ │ │ │ │ ├── DeactivatePriceListItemCommand.cs
│ │ │ │ │ └── DeactivatePriceListItemCommandHandler.cs
│ │ │ │ ├── GetPriceListItem/
│ │ │ │ │ ├── GetPriceListItemQuery.cs
│ │ │ │ │ ├── GetPriceListItemQueryHandler.cs
│ │ │ │ │ ├── PriceListItemMoneyValueDto.cs
│ │ │ │ │ └── PriceListItemsProjector.cs
│ │ │ │ ├── GetPriceListItems/
│ │ │ │ │ ├── GetPriceListItemsQuery.cs
│ │ │ │ │ └── GetPriceListItemsQueryHandler.cs
│ │ │ │ ├── PriceListFactory.cs
│ │ │ │ └── PriceListItemDto.cs
│ │ │ └── Subscriptions/
│ │ │ ├── BuySubscription/
│ │ │ │ ├── BuySubscriptionCommand.cs
│ │ │ │ └── BuySubscriptionCommandHandler.cs
│ │ │ ├── BuySubscriptionRenewal/
│ │ │ │ ├── BuySubscriptionRenewalCommand.cs
│ │ │ │ └── BuySubscriptionRenewalCommandHandler.cs
│ │ │ ├── CreateSubscription/
│ │ │ │ ├── CreateSubscriptionCommand.cs
│ │ │ │ ├── CreateSubscriptionCommandHandler.cs
│ │ │ │ ├── SubscriptionCreatedEnqueueEmailConfirmationHandler.cs
│ │ │ │ ├── SubscriptionCreatedNotification.cs
│ │ │ │ └── SubscriptionCreatedNotificationHandler.cs
│ │ │ ├── ExpireSubscription/
│ │ │ │ ├── ExpireSubscriptionCommand.cs
│ │ │ │ └── ExpireSubscriptionCommandHandler.cs
│ │ │ ├── ExpireSubscriptionPayment/
│ │ │ │ ├── ExpireSubscriptionPaymentCommand.cs
│ │ │ │ └── ExpireSubscriptionPaymentCommandHandler.cs
│ │ │ ├── ExpireSubscriptionPayments/
│ │ │ │ ├── ExpireSubscriptionPaymentsCommand.cs
│ │ │ │ └── ExpireSubscriptionPaymentsCommandHandler.cs
│ │ │ ├── ExpireSubscriptions/
│ │ │ │ ├── ExpireSubscriptionsCommand.cs
│ │ │ │ └── ExpireSubscriptionsCommandHandler.cs
│ │ │ ├── GetPayerSubscription/
│ │ │ │ ├── GetAuthenticatedPayerSubscriptionQuery.cs
│ │ │ │ └── GetAuthenticatedPayerSubscriptionQueryHandler.cs
│ │ │ ├── GetSubscriptionDetails/
│ │ │ │ ├── GetSubscriptionDetailsQuery.cs
│ │ │ │ ├── GetSubscriptionDetailsQueryHandler.cs
│ │ │ │ ├── SubscriptionDetailsDto.cs
│ │ │ │ └── SubscriptionDetailsProjector.cs
│ │ │ ├── GetSubscriptionPayments/
│ │ │ │ ├── GetSubscriptionPaymentsQuery.cs
│ │ │ │ ├── GetSubscriptionPaymentsQueryHandler.cs
│ │ │ │ ├── SubscriptionPaymentDto.cs
│ │ │ │ └── SubscriptionPaymentsProjector.cs
│ │ │ ├── MarkSubscriptionPaymentAsPaid/
│ │ │ │ ├── MarkSubscriptionPaymentAsPaidCommand.cs
│ │ │ │ ├── MarkSubscriptionPaymentAsPaidCommandHandler.cs
│ │ │ │ ├── SubscriptionPaymentPaidNotification.cs
│ │ │ │ └── SubscriptionPaymentPaidNotificationHandler.cs
│ │ │ ├── MarkSubscriptionRenewalPaymentAsPaid/
│ │ │ │ ├── MarkSubscriptionRenewalPaymentAsPaidCommand.cs
│ │ │ │ ├── MarkSubscriptionRenewalPaymentAsPaidCommandHandler.cs
│ │ │ │ ├── SubscriptionRenewalPaymentAsPaidNotificationHandler.cs
│ │ │ │ └── SubscriptionRenewalPaymentPaidNotification.cs
│ │ │ ├── RenewSubscription/
│ │ │ │ ├── RenewSubscriptionCommand.cs
│ │ │ │ ├── RenewSubscriptionCommandHandler.cs
│ │ │ │ ├── SubscriptionRenewedEnqueueEmailConfirmationHandler.cs
│ │ │ │ ├── SubscriptionRenewedNotification.cs
│ │ │ │ └── SubscriptionRenewedNotificationHandler.cs
│ │ │ ├── SendSubscriptionCreationConfirmationEmail/
│ │ │ │ ├── SendSubscriptionCreationConfirmationEmailCommand.cs
│ │ │ │ └── SendSubscriptionCreationConfirmationEmailCommandHandler.cs
│ │ │ └── SendSubscriptionRenewalConfirmationEmail/
│ │ │ ├── SendSubscriptionRenewalConfirmationEmailCommand.cs
│ │ │ └── SendSubscriptionRenewalConfirmationEmailCommandHandler.cs
│ │ ├── Domain/
│ │ │ ├── CompanyName.MyMeetings.Modules.Payments.Domain.csproj
│ │ │ ├── MeetingFeePayments/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingFeePaymentCreatedDomainEvent.cs
│ │ │ │ │ ├── MeetingFeePaymentExpiredDomainEvent.cs
│ │ │ │ │ └── MeetingFeePaymentPaidDomainEvent.cs
│ │ │ │ ├── MeetingFeePayment.cs
│ │ │ │ ├── MeetingFeePaymentId.cs
│ │ │ │ ├── MeetingFeePaymentSnapshot.cs
│ │ │ │ └── MeetingFeePaymentStatus.cs
│ │ │ ├── MeetingFees/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── MeetingFeeCanceledDomainEvent.cs
│ │ │ │ │ ├── MeetingFeeCreatedDomainEvent.cs
│ │ │ │ │ ├── MeetingFeeExpiredDomainEvent.cs
│ │ │ │ │ └── MeetingFeePaidDomainEvent.cs
│ │ │ │ ├── MeetingFee.cs
│ │ │ │ ├── MeetingFeeId.cs
│ │ │ │ ├── MeetingFeeSnapshot.cs
│ │ │ │ ├── MeetingFeeStatus.cs
│ │ │ │ └── MeetingId.cs
│ │ │ ├── Payers/
│ │ │ │ ├── Events/
│ │ │ │ │ └── PayerCreatedDomainEvent.cs
│ │ │ │ ├── IPayerContext.cs
│ │ │ │ ├── IPayerRepository.cs
│ │ │ │ ├── Payer.cs
│ │ │ │ └── PayerId.cs
│ │ │ ├── PriceListItems/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── PriceListItemActivatedDomainEvent.cs
│ │ │ │ │ ├── PriceListItemAttributesChangedDomainEvent.cs
│ │ │ │ │ ├── PriceListItemCreatedDomainEvent.cs
│ │ │ │ │ └── PriceListItemDeactivatedDomainEvent.cs
│ │ │ │ ├── PriceList.cs
│ │ │ │ ├── PriceListItem.cs
│ │ │ │ ├── PriceListItemCategory.cs
│ │ │ │ ├── PriceListItemData.cs
│ │ │ │ ├── PriceListItemId.cs
│ │ │ │ └── PricingStrategies/
│ │ │ │ ├── DirectValueFromPriceListPricingStrategy.cs
│ │ │ │ ├── DirectValuePricingStrategy.cs
│ │ │ │ ├── DiscountedValueFromPriceListPricingStrategy.cs
│ │ │ │ └── IPricingStrategy.cs
│ │ │ ├── SeedWork/
│ │ │ │ ├── AggregateId.cs
│ │ │ │ ├── AggregateRoot.cs
│ │ │ │ ├── IAggregateStore.cs
│ │ │ │ ├── MoneyValue.cs
│ │ │ │ ├── Rules/
│ │ │ │ │ ├── MoneyMustHaveTheSameCurrencyRule.cs
│ │ │ │ │ └── ValueOfMoneyMustNotBeNegativeRule.cs
│ │ │ │ └── SystemClock.cs
│ │ │ ├── SubscriptionPayments/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── SubscriptionPaymentCreatedDomainEvent.cs
│ │ │ │ │ ├── SubscriptionPaymentExpiredDomainEvent.cs
│ │ │ │ │ └── SubscriptionPaymentPaidDomainEvent.cs
│ │ │ │ ├── Rules/
│ │ │ │ │ ├── PriceForSubscriptionMustBeDefinedRule.cs
│ │ │ │ │ └── PriceOfferMustMatchPriceInPriceListRule.cs
│ │ │ │ ├── SubscriptionPayment.cs
│ │ │ │ ├── SubscriptionPaymentId.cs
│ │ │ │ ├── SubscriptionPaymentSnapshot.cs
│ │ │ │ └── SubscriptionPaymentStatus.cs
│ │ │ ├── SubscriptionRenewalPayments/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── SubscriptionRenewalPaymentCreatedDomainEvent.cs
│ │ │ │ │ └── SubscriptionRenewalPaymentPaidDomainEvent.cs
│ │ │ │ ├── Rules/
│ │ │ │ │ └── PriceOfferMustMatchPriceInPriceListRule.cs
│ │ │ │ ├── SubscriptionRenewalPayment.cs
│ │ │ │ ├── SubscriptionRenewalPaymentId.cs
│ │ │ │ ├── SubscriptionRenewalPaymentSnapshot.cs
│ │ │ │ └── SubscriptionRenewalPaymentStatus.cs
│ │ │ ├── Subscriptions/
│ │ │ │ ├── Events/
│ │ │ │ │ ├── SubscriptionCreatedDomainEvent.cs
│ │ │ │ │ ├── SubscriptionExpiredDomainEvent.cs
│ │ │ │ │ └── SubscriptionRenewedDomainEvent.cs
│ │ │ │ ├── SubscriberId.cs
│ │ │ │ ├── Subscription.cs
│ │ │ │ ├── SubscriptionDateExpirationCalculator.cs
│ │ │ │ ├── SubscriptionId.cs
│ │ │ │ ├── SubscriptionPeriod.cs
│ │ │ │ └── SubscriptionStatus.cs
│ │ │ └── Users/
│ │ │ ├── IUserContext.cs
│ │ │ └── UserId.cs
│ │ ├── Infrastructure/
│ │ │ ├── AggregateStore/
│ │ │ │ ├── AggregateStoreDomainEventsAccessor.cs
│ │ │ │ ├── DomainEventTypeMappings.cs
│ │ │ │ ├── ICheckpointStore.cs
│ │ │ │ ├── SqlOutboxAccessor.cs
│ │ │ │ ├── SqlServerCheckpointStore.cs
│ │ │ │ ├── SqlStreamAggregateStore.cs
│ │ │ │ ├── SubscriptionCode.cs
│ │ │ │ └── SubscriptionsManager.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Payments.Infrastructure.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── AllConstructorFinder.cs
│ │ │ │ ├── Assemblies.cs
│ │ │ │ ├── Authentication/
│ │ │ │ │ ├── AuthenticationModule.cs
│ │ │ │ │ └── PayerContext.cs
│ │ │ │ ├── DataAccess/
│ │ │ │ │ └── DataAccessModule.cs
│ │ │ │ ├── DatabaseSchema.cs
│ │ │ │ ├── Email/
│ │ │ │ │ └── EmailModule.cs
│ │ │ │ ├── EventsBus/
│ │ │ │ │ ├── EventsBusModule.cs
│ │ │ │ │ ├── EventsBusStartup.cs
│ │ │ │ │ └── IntegrationEventGenericHandler.cs
│ │ │ │ ├── Logging/
│ │ │ │ │ └── LoggingModule.cs
│ │ │ │ ├── Mediation/
│ │ │ │ │ └── MediatorModule.cs
│ │ │ │ ├── PaymentsCompositionRoot.cs
│ │ │ │ ├── PaymentsStartup.cs
│ │ │ │ ├── Processing/
│ │ │ │ │ ├── CommandsExecutor.cs
│ │ │ │ │ ├── Inbox/
│ │ │ │ │ │ ├── InboxMessageDto.cs
│ │ │ │ │ │ ├── ProcessInboxCommand.cs
│ │ │ │ │ │ ├── ProcessInboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessInboxJob.cs
│ │ │ │ │ ├── InternalCommands/
│ │ │ │ │ │ ├── CommandsScheduler.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommand.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommandHandler.cs
│ │ │ │ │ │ └── ProcessInternalCommandsJob.cs
│ │ │ │ │ ├── LoggingCommandHandlerDecorator.cs
│ │ │ │ │ ├── LoggingCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── Outbox/
│ │ │ │ │ │ ├── OutboxMessageDto.cs
│ │ │ │ │ │ ├── OutboxModule.cs
│ │ │ │ │ │ ├── ProcessOutboxCommand.cs
│ │ │ │ │ │ ├── ProcessOutboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessOutboxJob.cs
│ │ │ │ │ ├── PaymentsUnitOfWork.cs
│ │ │ │ │ ├── ProcessingModule.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerDecorator.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── ValidationCommandHandlerDecorator.cs
│ │ │ │ │ └── ValidationCommandHandlerWithResultDecorator.cs
│ │ │ │ └── Quartz/
│ │ │ │ ├── Jobs/
│ │ │ │ │ ├── ExpireSubscriptionPaymentsJob.cs
│ │ │ │ │ └── ExpireSubscriptionsJob.cs
│ │ │ │ ├── QuartzModule.cs
│ │ │ │ ├── QuartzStartup.cs
│ │ │ │ └── SerilogLogProvider.cs
│ │ │ ├── InternalCommands/
│ │ │ │ └── InternalCommandEntityTypeConfiguration.cs
│ │ │ └── PaymentsModule.cs
│ │ ├── IntegrationEvents/
│ │ │ ├── CompanyName.MyMeetings.Modules.Payments.IntegrationEvents.csproj
│ │ │ ├── MeetingFeePaidIntegrationEvent.cs
│ │ │ └── SubscriptionExpirationDateChangedIntegrationEvent.cs
│ │ └── Tests/
│ │ ├── ArchTests/
│ │ │ ├── Application/
│ │ │ │ └── ApplicationTests.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Payments.ArchTests.csproj
│ │ │ ├── Domain/
│ │ │ │ └── DomainTests.cs
│ │ │ ├── Module/
│ │ │ │ └── LayersTests.cs
│ │ │ └── SeedWork/
│ │ │ └── TestBase.cs
│ │ ├── IntegrationTests/
│ │ │ ├── AssemblyInfo.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Payments.IntegrationTests.csproj
│ │ │ ├── MeetingFees/
│ │ │ │ └── MeetingFeesTests.cs
│ │ │ ├── Payers/
│ │ │ │ ├── PayerSampleData.cs
│ │ │ │ └── PayerTests.cs
│ │ │ ├── PriceList/
│ │ │ │ └── PriceListHelper.cs
│ │ │ ├── SeedWork/
│ │ │ │ ├── EventsBusMock.cs
│ │ │ │ ├── ExecutionContextMock.cs
│ │ │ │ ├── OutboxMessagesHelper.cs
│ │ │ │ └── TestBase.cs
│ │ │ └── Subscriptions/
│ │ │ ├── BuySubscriptionTests.cs
│ │ │ ├── GetSubscriptionPaymentsProbe.cs
│ │ │ ├── SubscriptionLifecycleTests.cs
│ │ │ └── SubscriptionPaymentsTests.cs
│ │ └── UnitTests/
│ │ ├── CompanyName.MyMeetings.Modules.Payments.Domain.UnitTests.csproj
│ │ ├── Payers/
│ │ │ └── PayerTests.cs
│ │ ├── PriceListItems/
│ │ │ └── PriceListItemTests.cs
│ │ ├── SeedWork/
│ │ │ ├── DomainEventsTestHelper.cs
│ │ │ └── TestBase.cs
│ │ ├── SubscriptionPayments/
│ │ │ ├── SubscriptionPaymentTests.cs
│ │ │ └── SubscriptionPaymentTestsBase.cs
│ │ ├── SubscriptionRenewalPayments/
│ │ │ ├── SubscriptionRenewalPaymentTests.cs
│ │ │ └── SubscriptionRenewalPaymentTestsBase.cs
│ │ └── Subscriptions/
│ │ ├── SubscriptionDateExpirationCalculatorTests.cs
│ │ └── SubscriptionTests.cs
│ ├── Registrations/
│ │ ├── Application/
│ │ │ ├── CompanyName.MyMeetings.Modules.Registrations.Application.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── Commands/
│ │ │ │ │ ├── ICommandHandler.cs
│ │ │ │ │ ├── ICommandsScheduler.cs
│ │ │ │ │ └── InternalCommandBase.cs
│ │ │ │ └── Queries/
│ │ │ │ └── IQueryHandler.cs
│ │ │ ├── Contracts/
│ │ │ │ ├── CommandBase.cs
│ │ │ │ ├── CustomClaimTypes.cs
│ │ │ │ ├── ICommand.cs
│ │ │ │ ├── IQuery.cs
│ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ ├── IRegistrationsModule.cs
│ │ │ │ ├── QueryBase.cs
│ │ │ │ └── Roles.cs
│ │ │ └── UserRegistrations/
│ │ │ ├── ConfirmUserRegistration/
│ │ │ │ ├── ConfirmUserRegistrationCommand.cs
│ │ │ │ ├── ConfirmUserRegistrationCommandHandler.cs
│ │ │ │ ├── IUserCreator.cs
│ │ │ │ ├── UserRegistrationConfirmedNotification.cs
│ │ │ │ └── UserRegistrationConfirmedNotificationHandler.cs
│ │ │ ├── GetUserRegistration/
│ │ │ │ ├── GetUserRegistrationQuery.cs
│ │ │ │ ├── GetUserRegistrationQueryHandler.cs
│ │ │ │ ├── UserRegistrationDto.cs
│ │ │ │ └── UserRegistrationProvider.cs
│ │ │ ├── RegisterNewUser/
│ │ │ │ ├── NewUserRegisteredEnqueueEmailConfirmationHandler.cs
│ │ │ │ ├── NewUserRegisteredNotification.cs
│ │ │ │ ├── NewUserRegisteredPublishEventHandler.cs
│ │ │ │ ├── PasswordManager.cs
│ │ │ │ ├── RegisterNewUserCommand.cs
│ │ │ │ └── RegisterNewUserCommandHandler.cs
│ │ │ ├── SendUserRegistrationConfirmationEmail/
│ │ │ │ ├── SendUserRegistrationConfirmationEmailCommand.cs
│ │ │ │ └── SendUserRegistrationConfirmationEmailCommandHandler.cs
│ │ │ └── UsersCounter.cs
│ │ ├── Domain/
│ │ │ ├── CompanyName.MyMeetings.Modules.Registrations.Domain.csproj
│ │ │ └── UserRegistrations/
│ │ │ ├── Events/
│ │ │ │ ├── NewUserRegisteredDomainEvent.cs
│ │ │ │ ├── UserRegistrationConfirmedDomainEvent.cs
│ │ │ │ └── UserRegistrationExpiredDomainEvent.cs
│ │ │ ├── IUserRegistrationRepository.cs
│ │ │ ├── IUsersCounter.cs
│ │ │ ├── Rules/
│ │ │ │ ├── UserCannotBeCreatedWhenRegistrationIsNotConfirmedRule.cs
│ │ │ │ ├── UserLoginMustBeUniqueRule.cs
│ │ │ │ ├── UserRegistrationCannotBeConfirmedAfterExpirationRule.cs
│ │ │ │ ├── UserRegistrationCannotBeConfirmedMoreThanOnceRule.cs
│ │ │ │ └── UserRegistrationCannotBeExpiredMoreThanOnceRule.cs
│ │ │ ├── UserRegistration.cs
│ │ │ ├── UserRegistrationId.cs
│ │ │ └── UserRegistrationStatus.cs
│ │ ├── Infrastructure/
│ │ │ ├── CompanyName.MyMeetings.Modules.Registrations.Infrastructure.csproj
│ │ │ ├── Configuration/
│ │ │ │ ├── AllConstructorFinder.cs
│ │ │ │ ├── Assemblies.cs
│ │ │ │ ├── Commands/
│ │ │ │ │ ├── ICommandHandler.cs
│ │ │ │ │ ├── ICommandsScheduler.cs
│ │ │ │ │ └── InternalCommandBase.cs
│ │ │ │ ├── DataAccess/
│ │ │ │ │ └── DataAccessModule.cs
│ │ │ │ ├── Domain/
│ │ │ │ │ └── DomainModule.cs
│ │ │ │ ├── Email/
│ │ │ │ │ └── EmailModule.cs
│ │ │ │ ├── EventsBus/
│ │ │ │ │ ├── EventsBusModule.cs
│ │ │ │ │ ├── EventsBusStartup.cs
│ │ │ │ │ └── IntegrationEventGenericHandler.cs
│ │ │ │ ├── Logging/
│ │ │ │ │ └── LoggingModule.cs
│ │ │ │ ├── Mediation/
│ │ │ │ │ └── MediatorModule.cs
│ │ │ │ ├── Processing/
│ │ │ │ │ ├── CommandsExecutor.cs
│ │ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ │ ├── Inbox/
│ │ │ │ │ │ ├── InboxMessageDto.cs
│ │ │ │ │ │ ├── ProcessInboxCommand.cs
│ │ │ │ │ │ ├── ProcessInboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessInboxJob.cs
│ │ │ │ │ ├── InternalCommands/
│ │ │ │ │ │ ├── CommandsScheduler.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommand.cs
│ │ │ │ │ │ ├── ProcessInternalCommandsCommandHandler.cs
│ │ │ │ │ │ └── ProcessInternalCommandsJob.cs
│ │ │ │ │ ├── LoggingCommandHandlerDecorator.cs
│ │ │ │ │ ├── LoggingCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── Outbox/
│ │ │ │ │ │ ├── OutboxMessageDto.cs
│ │ │ │ │ │ ├── OutboxModule.cs
│ │ │ │ │ │ ├── ProcessOutboxCommand.cs
│ │ │ │ │ │ ├── ProcessOutboxCommandHandler.cs
│ │ │ │ │ │ └── ProcessOutboxJob.cs
│ │ │ │ │ ├── ProcessingModule.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerDecorator.cs
│ │ │ │ │ ├── UnitOfWorkCommandHandlerWithResultDecorator.cs
│ │ │ │ │ ├── ValidationCommandHandlerDecorator.cs
│ │ │ │ │ └── ValidationCommandHandlerWithResultDecorator.cs
│ │ │ │ ├── Quartz/
│ │ │ │ │ ├── QuartzModule.cs
│ │ │ │ │ ├── QuartzStartup.cs
│ │ │ │ │ └── SerilogLogProvider.cs
│ │ │ │ ├── RegistrationsCompositionRoot.cs
│ │ │ │ ├── RegistrationsStartup.cs
│ │ │ │ └── UserAccess/
│ │ │ │ └── UserAccessAutofacModule.cs
│ │ │ ├── Domain/
│ │ │ │ └── UserRegistrations/
│ │ │ │ ├── UserRegistrationEntityTypeConfiguration.cs
│ │ │ │ └── UserRegistrationRepository.cs
│ │ │ ├── InternalCommands/
│ │ │ │ └── InternalCommandEntityTypeConfiguration.cs
│ │ │ ├── Outbox/
│ │ │ │ ├── OutboxAccessor.cs
│ │ │ │ └── OutboxMessageEntityTypeConfiguration.cs
│ │ │ ├── RegistrationsContext.cs
│ │ │ ├── RegistrationsModule.cs
│ │ │ └── Users/
│ │ │ └── UserAccessGateway.cs
│ │ ├── IntegrationEvents/
│ │ │ ├── Class1.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Registrations.IntegrationEvents.csproj
│ │ │ └── NewUserRegisteredIntegrationEvent.cs
│ │ └── Tests/
│ │ ├── ArchTests/
│ │ │ ├── Application/
│ │ │ │ └── ApplicationTests.cs
│ │ │ ├── CompanyName.MyMeetings.Modules.Registrations.ArchTests.csproj
│ │ │ ├── Domain/
│ │ │ │ └── DomainTests.cs
│ │ │ ├── Module/
│ │ │ │ └── LayersTests.cs
│ │ │ └── SeedWork/
│ │ │ └── TestBase.cs
│ │ ├── IntegrationTests/
│ │ │ ├── AssemblyInfo.cs
│ │ │ ├── CompanyNames.MyMeetings.Modules.Registrations.IntegrationTests.csproj
│ │ │ ├── SeedWork/
│ │ │ │ ├── ExecutionContextMock.cs
│ │ │ │ ├── OutboxMessagesHelper.cs
│ │ │ │ └── TestBase.cs
│ │ │ └── UserRegistrations/
│ │ │ ├── ConfirmUserRegistrationTests.cs
│ │ │ ├── SendUserRegistrationConfirmationEmailTests.cs
│ │ │ ├── UserRegistrationSampleData.cs
│ │ │ └── UserRegistrationTests.cs
│ │ └── UnitTests/
│ │ ├── CompanyName.MyMeetings.Modules.Registrations.Domain.UnitTests.csproj
│ │ ├── SeedWork/
│ │ │ ├── DomainEventsTestHelper.cs
│ │ │ └── TestBase.cs
│ │ └── UserRegistrations/
│ │ └── UserRegistrationTests.cs
│ └── UserAccess/
│ ├── Application/
│ │ ├── Authentication/
│ │ │ └── Authenticate/
│ │ │ ├── AuthenticateCommand.cs
│ │ │ ├── AuthenticateCommandHandler.cs
│ │ │ ├── AuthenticateCommandValidator.cs
│ │ │ ├── AuthenticationResult.cs
│ │ │ ├── PasswordManager.cs
│ │ │ └── UserDto.cs
│ │ ├── Authorization/
│ │ │ ├── GetAuthenticatedUserPermissions/
│ │ │ │ ├── GetAuthenticatedUserPermissionsQuery.cs
│ │ │ │ └── GetAuthenticatedUserPermissionsQueryHandler.cs
│ │ │ └── GetUserPermissions/
│ │ │ ├── GetUserPermissionsQuery.cs
│ │ │ ├── GetUserPermissionsQueryHandler.cs
│ │ │ └── UserPermissionDto.cs
│ │ ├── CompanyName.MyMeetings.Modules.UserAccess.Application.csproj
│ │ ├── Configuration/
│ │ │ ├── Commands/
│ │ │ │ ├── ICommandHandler.cs
│ │ │ │ ├── ICommandsScheduler.cs
│ │ │ │ └── InternalCommandBase.cs
│ │ │ └── Queries/
│ │ │ └── IQueryHandler.cs
│ │ ├── Contracts/
│ │ │ ├── CommandBase.cs
│ │ │ ├── CustomClaimTypes.cs
│ │ │ ├── ICommand.cs
│ │ │ ├── IQuery.cs
│ │ │ ├── IRecurringCommand.cs
│ │ │ ├── IUserAccessModule.cs
│ │ │ ├── QueryBase.cs
│ │ │ └── Roles.cs
│ │ ├── Emails/
│ │ │ ├── EmailDto.cs
│ │ │ ├── GetAllEmailsQuery.cs
│ │ │ └── GetAllEmailsQueryHandler.cs
│ │ └── Users/
│ │ ├── AddAdminUser/
│ │ │ ├── AddAdminUserCommand.cs
│ │ │ └── AddAdminUserCommandHandler.cs
│ │ ├── CreateUser/
│ │ │ ├── CreateUserCommand.cs
│ │ │ └── CreateUserCommandHandler.cs
│ │ ├── GetAuthenticatedUser/
│ │ │ ├── GetAuthenticatedUserQuery.cs
│ │ │ └── GetAuthenticatedUserQueryHandler.cs
│ │ └── GetUser/
│ │ ├── GetUserQuery.cs
│ │ ├── GetUserQueryHandler.cs
│ │ └── UserDto.cs
│ ├── Domain/
│ │ ├── CompanyName.MyMeetings.Modules.UserAccess.Domain.csproj
│ │ └── Users/
│ │ ├── Events/
│ │ │ └── UserCreatedDomainEvent.cs
│ │ ├── IUserRepository.cs
│ │ ├── User.cs
│ │ ├── UserId.cs
│ │ └── UserRole.cs
│ ├── Infrastructure/
│ │ ├── CompanyName.MyMeetings.Modules.UserAccess.Infrastructure.csproj
│ │ ├── Configuration/
│ │ │ ├── AllConstructorFinder.cs
│ │ │ ├── Assemblies.cs
│ │ │ ├── DataAccess/
│ │ │ │ └── DataAccessModule.cs
│ │ │ ├── Email/
│ │ │ │ └── EmailModule.cs
│ │ │ ├── EventsBus/
│ │ │ │ ├── EventsBusModule.cs
│ │ │ │ ├── EventsBusStartup.cs
│ │ │ │ └── IntegrationEventGenericHandler.cs
│ │ │ ├── Identity/
│ │ │ │ └── IdentityConfiguration.cs
│ │ │ ├── Logging/
│ │ │ │ └── LoggingModule.cs
│ │ │ ├── Mediation/
│ │ │ │ └── MediatorModule.cs
│ │ │ ├── Processing/
│ │ │ │ ├── CommandsExecutor.cs
│ │ │ │ ├── IRecurringCommand.cs
│ │ │ │ ├── Inbox/
│ │ │ │ │ ├── InboxMessageDto.cs
│ │ │ │ │ ├── ProcessInboxCommand.cs
│ │ │ │ │ ├── ProcessInboxCommandHandler.cs
│ │ │ │ │ └── ProcessInboxJob.cs
│ │ │ │ ├── InternalCommands/
│ │ │ │ │ ├── CommandsScheduler.cs
│ │ │ │ │ ├── ProcessInternalCommandsCommand.cs
│ │ │ │ │ ├── ProcessInternalCommandsCommandHandler.cs
│ │ │ │ │ └── ProcessInternalCommandsJob.cs
│ │ │ │ ├── LoggingCommandHandlerDecorator.cs
│ │ │ │ ├── LoggingCommandHandlerWithResultDecorator.cs
│ │ │ │ ├── Outbox/
│ │ │ │ │ ├── OutboxMessageDto.cs
│ │ │ │ │ ├── OutboxModule.cs
│ │ │ │ │ ├── ProcessOutboxCommand.cs
│ │ │ │ │ ├── ProcessOutboxCommandHandler.cs
│ │ │ │ │ └── ProcessOutboxJob.cs
│ │ │ │ ├── ProcessingModule.cs
│ │ │ │ ├── UnitOfWorkCommandHandlerDecorator.cs
│ │ │ │ ├── UnitOfWorkCommandHandlerWithResultDecorator.cs
│ │ │ │ ├── ValidationCommandHandlerDecorator.cs
│ │ │ │ └── ValidationCommandHandlerWithResultDecorator.cs
│ │ │ ├── Quartz/
│ │ │ │ ├── QuartzModule.cs
│ │ │ │ ├── QuartzStartup.cs
│ │ │ │ └── SerilogLogProvider.cs
│ │ │ ├── Security/
│ │ │ │ ├── AesDataProtector.cs
│ │ │ │ ├── IDataProtector.cs
│ │ │ │ └── SecurityModule.cs
│ │ │ ├── UserAccessCompositionRoot.cs
│ │ │ └── UserAccessStartup.cs
│ │ ├── Domain/
│ │ │ └── Users/
│ │ │ ├── UserEntityTypeConfiguration.cs
│ │ │ └── UserRepository.cs
│ │ ├── IdentityServer/
│ │ │ ├── IdentityServerConfig.cs
│ │ │ ├── ProfileService.cs
│ │ │ └── ResourceOwnerPasswordValidator.cs
│ │ ├── InternalCommands/
│ │ │ └── InternalCommandEntityTypeConfiguration.cs
│ │ ├── Outbox/
│ │ │ ├── OutboxAccessor.cs
│ │ │ └── OutboxMessageEntityTypeConfiguration.cs
│ │ ├── UserAccessContext.cs
│ │ └── UserAccessModule.cs
│ ├── IntegrationEvents/
│ │ └── CompanyName.MyMeetings.Modules.UserAccess.IntegrationEvents.csproj
│ └── Tests/
│ ├── ArchTests/
│ │ ├── Application/
│ │ │ └── ApplicationTests.cs
│ │ ├── CompanyName.MyMeetings.Modules.UserAccess.ArchTests.csproj
│ │ ├── Domain/
│ │ │ └── DomainTests.cs
│ │ ├── Module/
│ │ │ └── LayersTests.cs
│ │ └── SeedWork/
│ │ └── TestBase.cs
│ ├── IntegrationTests/
│ │ ├── AssemblyInfo.cs
│ │ ├── CompanyNames.MyMeetings.Modules.UserAccess.IntegrationTests.csproj
│ │ ├── SeedWork/
│ │ │ ├── ExecutionContextMock.cs
│ │ │ ├── OutboxMessagesHelper.cs
│ │ │ └── TestBase.cs
│ │ └── Users/
│ │ └── CreateUserTests.cs
│ └── UnitTests/
│ ├── CompanyName.MyMeetings.Modules.UserAccess.Domain.UnitTests.csproj
│ └── SeedWork/
│ ├── DomainEventsTestHelper.cs
│ └── TestBase.cs
├── Tests/
│ ├── ArchTests/
│ │ ├── Api/
│ │ │ └── ApiTests.cs
│ │ ├── CompanyName.MyMeetings.ArchTests.csproj
│ │ ├── Modules/
│ │ │ └── ModuleTests.cs
│ │ └── SeedWork/
│ │ └── TestBase.cs
│ ├── IntegrationTests/
│ │ ├── AssemblyInfo.cs
│ │ ├── CompanyName.MyMeetings.IntegrationTests.csproj
│ │ ├── CreateMeetingGroup/
│ │ │ └── CreateMeetingGroupTests.cs
│ │ └── SeedWork/
│ │ ├── ExecutionContextMock.cs
│ │ └── TestBase.cs
│ └── SUT/
│ ├── CompanyName.MyMeetings.SUT.csproj
│ ├── Helpers/
│ │ ├── MeetingGroupsFactory.cs
│ │ ├── TestMeetingFactory.cs
│ │ ├── TestMeetingGroupManager.cs
│ │ ├── TestMeetingManager.cs
│ │ ├── TestPaymentsManager.cs
│ │ ├── TestPriceListManager.cs
│ │ └── UsersFactory.cs
│ ├── Scripts/
│ │ └── SeedPermissions.sql
│ ├── SeedWork/
│ │ ├── AsyncOperationsHelper.cs
│ │ ├── DatabaseCleaner.cs
│ │ ├── ExecutionContextMock.cs
│ │ ├── Probing/
│ │ │ ├── AssertErrorException.cs
│ │ │ ├── IProbe.cs
│ │ │ ├── Poller.cs
│ │ │ └── Timeout.cs
│ │ └── TestBase.cs
│ └── TestCases/
│ ├── CleanDatabaseTestCase.cs
│ ├── CreateMeeting.cs
│ └── OnlyAdminTestCase.cs
├── entrypoint.sh
├── global.json
└── stylecop.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/buildPipeline.yml
================================================
name: CI Pipeline
on:
push:
branches: [master]
pull_request:
branches: [master]
jobs:
build:
name: Build and run Unit and Architecture Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Run build
run: ./build.sh BuildAndUnitTests --configuration Release
integration:
name: Build and run Integration Tests
needs: [build]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Run build
run: ./build.sh RunAllIntegrationTests
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
.vscode/
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
**/wwwroot/lib/
!/wwwroot/lib/signalr
!/wwwroot/lib/toastr
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
pub/
/src/Web/WebMVC/Properties/PublishProfiles/eShopOnContainersWebMVC2016 - Web Deploy-publish.ps1
/src/Web/WebMVC/Properties/PublishProfiles/publish-module.psm1
/src/Services/Identity/eShopOnContainers.Identity/Properties/launchSettings.json
#Ignore marker-file used to know which docker files we have.
.eshopdocker_*
/src/Web/WebMVC/wwwroot/lib
/src/Web/WebMVC/wwwroot/css/site.min.css
**/.kube/**
.mfractor
#Ignore logs folder
[Ll]ogs
#Ignore uploaded files folder
UploadedFiles
/src/CompanyName.MyMeetings.v3.ncrunchsolution
#Nuke working directory
.nuke-working-directory
/src/API/CompanyName.MyMeetings.API/tempkey.jwk
================================================
FILE: .nuke/build.schema.json
================================================
{
"$schema": "http://json-schema.org/draft-04/schema#",
"$ref": "#/definitions/build",
"title": "Build Schema",
"definitions": {
"build": {
"type": "object",
"properties": {
"Configuration": {
"type": "string",
"description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)",
"enum": [
"Debug",
"Release"
]
},
"Continue": {
"type": "boolean",
"description": "Indicates to continue a previously failed build attempt"
},
"DatabaseConnectionString": {
"type": "string",
"description": "Modular Monolith database connection string"
},
"Help": {
"type": "boolean",
"description": "Shows the help text for this build assembly"
},
"Host": {
"type": "string",
"description": "Host for execution. Default is 'automatic'",
"enum": [
"AppVeyor",
"AzurePipelines",
"Bamboo",
"Bitbucket",
"Bitrise",
"GitHubActions",
"GitLab",
"Jenkins",
"Rider",
"SpaceAutomation",
"TeamCity",
"Terminal",
"TravisCI",
"VisualStudio",
"VSCode"
]
},
"NoLogo": {
"type": "boolean",
"description": "Disables displaying the NUKE logo"
},
"Partition": {
"type": "string",
"description": "Partition to use on CI"
},
"Plan": {
"type": "boolean",
"description": "Shows the execution plan (HTML)"
},
"Profile": {
"type": "array",
"description": "Defines the profiles to load",
"items": {
"type": "string"
}
},
"Root": {
"type": "string",
"description": "Root directory during build execution"
},
"Skip": {
"type": "array",
"description": "List of targets to be skipped. Empty list skips all dependencies",
"items": {
"type": "string",
"enum": [
"ArchitectureTests",
"BuildAdministrationModuleIntegrationTests",
"BuildAndUnitTests",
"BuildMeetingsModuleIntegrationTests",
"BuildPaymentsModuleIntegrationTests",
"BuildSystemIntegrationTests",
"BuildUserAccessModuleIntegrationTests",
"Clean",
"Compile",
"CompileDbUpMigrator",
"CompileDbUpMigratorForIntegrationTests",
"CreateDatabase",
"MigrateDatabase",
"PrepareInputFiles",
"PrepareSqlServer",
"PrepareSUT",
"Restore",
"RunAdministrationModuleIntegrationTests",
"RunAllIntegrationTests",
"RunDatabaseMigrations",
"RunMeetingsModuleIntegrationTests",
"RunPaymentsModuleIntegrationTests",
"RunSystemIntegrationTests",
"RunUserAccessModuleIntegrationTests",
"UnitTests"
]
}
},
"Solution": {
"type": "string",
"description": "Path to a solution file that is automatically loaded"
},
"SUTTestName": {
"type": "string",
"description": "SUT creator test name to execute"
},
"Target": {
"type": "array",
"description": "List of targets to be invoked. Default is '{default_target}'",
"items": {
"type": "string",
"enum": [
"ArchitectureTests",
"BuildAdministrationModuleIntegrationTests",
"BuildAndUnitTests",
"BuildMeetingsModuleIntegrationTests",
"BuildPaymentsModuleIntegrationTests",
"BuildSystemIntegrationTests",
"BuildUserAccessModuleIntegrationTests",
"Clean",
"Compile",
"CompileDbUpMigrator",
"CompileDbUpMigratorForIntegrationTests",
"CreateDatabase",
"MigrateDatabase",
"PrepareInputFiles",
"PrepareSqlServer",
"PrepareSUT",
"Restore",
"RunAdministrationModuleIntegrationTests",
"RunAllIntegrationTests",
"RunDatabaseMigrations",
"RunMeetingsModuleIntegrationTests",
"RunPaymentsModuleIntegrationTests",
"RunSystemIntegrationTests",
"RunUserAccessModuleIntegrationTests",
"UnitTests"
]
}
},
"Verbosity": {
"type": "string",
"description": "Logging verbosity during build execution. Default is 'Normal'",
"enum": [
"Minimal",
"Normal",
"Quiet",
"Verbose"
]
}
}
}
}
}
================================================
FILE: .nuke/parameters.json
================================================
{
"$schema": "./build.schema.json",
"Solution": "src/CompanyName.MyMeetings.sln"
}
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2019 Kamil Grzybek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Modular Monolith with DDD
Full Modular Monolith .NET application with Domain-Driven Design approach.
## Announcement

Learn, use and benefit from this project only if:
- You **condemn Russia and its military aggression against Ukraine**
- You **recognize that Russia is an occupant that unlawfully invaded a sovereign state**
- You **support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas**
- You **reject false narratives perpetuated by Russian state propaganda**
Otherwise, leave this project immediately and educate yourself.
Putin, idi nachuj.
## CI

## FrontEnd application
FrontEnd application : [Modular Monolith With DDD: FrontEnd React application](https://github.com/kgrzybek/modular-monolith-with-ddd-fe-react)
## Table of contents
[1. Introduction](#1-introduction)
[1.1 Purpose of this Repository](#11-purpose-of-this-repository)
[1.2 Out of Scope](#12-out-of-scope)
[1.3 Reason](#13-reason)
[1.4 Disclaimer](#14-disclaimer)
[1.5 Give a Star](#15-give-a-star)
[1.6 Share It](#16-share-it)
[2. Domain](#2-domain)
[2.1 Description](#21-description)
[2.2 Conceptual Model](#22-conceptual-model)
[2.3 Event Storming](#23-event-storming)
[3. Architecture](#3-architecture)
[3.0 C4 Model](#30-c4-model)
[3.1 High Level View](#31-high-level-view)
[3.2 Module Level View](#32-module-level-view)
[3.3 API and Module Communication](#33-api-and-module-communication)
[3.4 Module Requests Processing via CQRS](#34-module-requests-processing-via-cqrs)
[3.5 Domain Model Principles and Attributes](#35-domain-model-principles-and-attributes)
[3.6 Cross-Cutting Concerns](#36-cross-cutting-concerns)
[3.7 Modules Integration](#37-modules-integration)
[3.8 Internal Processing](#38-internal-processing)
[3.9 Security](#39-security)
[3.10 Unit Tests](#310-unit-tests)
[3.11 Architecture Decision Log](#311-architecture-decision-log)
[3.12 Architecture Unit Tests](#312-architecture-unit-tests)
[3.13 Integration Tests](#313-integration-tests)
[3.14 System Integration Testing](#314-system-integration-testing)
[3.15 Event Sourcing](#315-event-sourcing)
[3.16 Database change management](#316-database-change-management)
[3.17 Continuous Integration](#317-continuous-integration)
[3.18 Static code analysis](#318-static-code-analysis)
[3.19 System Under Test SUT](#319-system-under-test-sut)
[3.20 Mutation Testing](#320-mutation-testing)
[4. Technology](#4-technology)
[5. How to Run](#5-how-to-run)
[6. Contribution](#6-contribution)
[7. Roadmap](#7-roadmap)
[8. Authors](#8-authors)
[9. License](#9-license)
[10. Inspirations and Recommendations](#10-inspirations-and-recommendations)
## 1. Introduction
### 1.1 Purpose of this Repository
This is a list of the main goals of this repository:
- Showing how you can implement a **monolith** application in a **modular** way
- Presentation of the **full implementation** of an application
- This is not another simple application
- This is not another proof of concept (PoC)
- The goal is to present the implementation of an application that would be ready to run in production
- Showing the application of **best practices** and **object-oriented programming principles**
- Presentation of the use of **design patterns**. When, how and why they can be used
- Presentation of some **architectural** considerations, decisions, approaches
- Presentation of the implementation using **Domain-Driven Design** approach (**tactical** patterns)
- Presentation of the implementation of **Unit Tests** for Domain Model (Testable Design in mind)
- Presentation of the implementation of **Integration Tests**
- Presentation of the implementation of **Event Sourcing**
- Presentation of **C4 Model**
- Presentation of **diagram as text** approach
### 1.2 Out of Scope
This is a list of subjects which are out of scope for this repository:
- Business requirements gathering and analysis
- System analysis
- Domain exploration
- Domain distillation
- Domain-Driven Design **strategic** patterns
- Architecture evaluation, quality attributes analysis
- Integration, system tests
- Project management
- Infrastructure
- Containerization
- Software engineering process
- Deployment process
- Maintenance
- Documentation
### 1.3 Reason
The reason for creating this repository is the lack of something similar. Most sample applications on GitHub have at least one of the following issues:
- Very, very simple - few entities and use cases implemented
- Not finished (for example there is no authentication, logging, etc..)
- Poorly designed (in my opinion)
- Poorly implemented (in my opinion)
- Not well described
- Assumptions and decisions are not clearly explained
- Implements "Orders" domain - yes, everyone knows this domain, but something different is needed
- Implemented in old technology
- Not maintained
To sum up, there are some very good examples, but there are far too few of them. This repository has the task of filling this gap at some level.
### 1.4 Disclaimer
Software architecture should always be created to resolve specific **business problems**. Software architecture always supports some quality attributes and at the same time does not support others. A lot of other factors influence your software architecture - your team, opinions, preferences, experiences, technical constraints, time, budget, etc.
Always functional requirements, quality attributes, technical constraints and other factors should be considered before an architectural decision is made.
Because of the above, the architecture and implementation presented in this repository is **one of the many ways** to solve some problems. Take from this repository as much as you want, use it as you like but remember to **always pick the best solution which is appropriate to the problem class you have**.
### 1.5 Give a Star
My primary focus in this project is on quality. Creating a good quality product involves a lot of analysis, research and work. It takes a lot of time. If you like this project, learned something or you are using it in your applications, please give it a star :star:. This is the best motivation for me to continue this work. Thanks!
### 1.6 Share It
There are very few really good examples of this type of application. If you think this repository makes a difference and is worth it, please share it with your friends and on social networks. I will be extremely grateful.
## 2. Domain
### 2.1 Description
**Definition:**
> Domain - A sphere of knowledge, influence, or activity. The subject area to which the user applies a program is the domain of the software. [Domain-Driven Design Reference](http://domainlanguage.com/ddd/reference/), Eric Evans
The **Meeting Groups** domain was selected for the purposes of this project based on the [Meetup.com](https://www.meetup.com/) system.
**Main reasons for selecting this domain:**
- It is common, a lot of people use the Meetup site to organize or attend meetings
- There is a system for it, so everyone can check this implementation against a working site which supports this domain
- It is not complex so it is easy to understand
- It is not trivial - there are some business rules and logic and it is not just CRUD operations
- You don't need much specific domain knowledge unlike other domains like financing, banking, medical
- It is not big so it is easier to implement
**Meetings**
The main business entities are `Member`, `Meeting Group` and `Meeting`. A `Member` can create a `Meeting Group`, be part of a `Meeting Group` or can attend a `Meeting`.
A `Meeting Group Member` can be an `Organizer` of this group or a normal `Member`.
Only an `Organizer` of a `Meeting Group` can create a new `Meeting`.
A `Meeting` has attendees, not attendees (`Members` which declare they will not attend the `Meeting`) and `Members` on the `Waitlist`.
A `Meeting` can have an attendee limit. If the limit is reached, `Members` can only sign up to the `Waitlist`.
A `Meeting Attendee` can bring guests to the `Meeting`. The number of guests allowed is an attribute of the `Meeting`. Bringing guests can be unallowed.
A `Meeting Attendee` can have one of two roles: `Attendee` or `Host`. A `Meeting` must have at least one `Host`. The `Host` is a special role which grants permission to edit `Meeting` information or change the attendees list.
A `Member` can comment `Meetings`. A `Member` can reply to, like other `Comments`. `Organizer` manages commenting of `Meeting` by `Meeting Commenting Configuration`. `Organizer` can delete any `Comment`.
Each `Meeting Group` must have an organizer with active `Subscription`. One organizer can cover 3 `Meeting Groups` by his `Subscription`.
Additionally, Meeting organizer can set an `Event Fee`. Each `Meeting Attendee` is obliged to pay the fee. All guests should be paid by `Meeting Attendee` too.
**Administration**
To create a new `Meeting Group`, a `Member` needs to propose the group. A `Meeting Group Proposal` is sent to `Administrators`. An `Administrator` can accept or reject a `Meeting Group Proposal`. If a `Meeting Group Proposal` is accepted, a `Meeting Group` is created.
**Payments**
Each `Member` who is the `Payer` can buy the `Subscription`. He needs to pay the `Subscription Payment`. `Subscription` can expire so `Subscription Renewal` is required (by `Subscription Renewal Payment` payment to keep `Subscription` active).
When the `Meeting` fee is required, the `Payer` needs to pay `Meeting Fee` (through `Meeting Fee Payment`).
**Users**
Each `Administrator`, `Member` and `Payer` is a `User`. To be a `User`, `User Registration` is required and confirmed.
Each `User` is assigned one or more `User Role`.
Each `User Role` has set of `Permissions`. A `Permission` defines whether `User` can invoke a particular action.
### 2.2 Conceptual Model
**Definition:**
> Conceptual Model - A conceptual model is a representation of a system, made of the composition of concepts that are used to help people know, understand, or simulate a subject the model represents. [Wikipedia - Conceptual model](https://en.wikipedia.org/wiki/Conceptual_model)
**Conceptual Model**
PlantUML version:

VisualParadigm version (not maintained, only for demonstration):

**Conceptual Model of commenting feature**

### 2.3 Event Storming
While a Conceptual Model focuses on structures and relationships between them, **behavior** and **events** that occur in our domain are more important.
There are many ways to show behavior and events. One of them is a light technique called [Event Storming](https://www.eventstorming.com/) which is becoming more popular. Below are presented 3 main business processes using this technique: user registration, meeting group creation and meeting organization.
Note: Event Storming is a light, live workshop. One of the possible outputs of this workshop is presented here. Even if you are not doing Event Storming workshops, this type of process presentation can be very valuable to you and your stakeholders.
**User Registration process**
------

------
**Meeting Group creation**

------
**Meeting organization**

------
**Payments**

[Download high resolution file](docs/Images/Payments_EventStorming_Design_HighRes.jpg)
------
## 3. Architecture
### 3.0 C4 Model
[C4 model](https://c4model.com/) is a lean graphical notation technique for modelling the architecture of software systems.
As can be found on the website of the author of this model ([Simon Brown](https://simonbrown.je/)): *The C4 model was created as a way to help software development teams describe and communicate software architecture, both during up-front design sessions and when retrospectively documenting an existing codebase*
*Model C4* defines 4 levels (views) of the system architecture: *System Context*, *Container*, *Component* and *Code*. Below are examples of each of these levels that describe the architecture of this system.
*Note: The [PlantUML](https://plantuml.com/) (diagram as text) component was used to describe all C4 model levels. Additionally, for levels C1-C3, a [C4-PlantUML](https://github.com/plantuml-stdlib/C4-PlantUML) plug-in connecting PlantUML with the C4 model was used*.
#### 3.0.1 C1 System Context

#### 3.0.2 C2 Container

#### 3.0.3 C3 Component (high-level)

#### 3.0.4 C3 Component (module-level)

#### 3.0.5 C4 Code (meeting group aggregate)

### 3.1 High Level View

**Module descriptions:**
- **API** - Very thin ASP.NET MVC Core REST API application. Main responsibilities are:
1. Accept request
2. Authenticate and authorize request (using User Access module)
3. Delegate work to specific module sending Command or Query
4. Return response
- **User Access** - responsible for user authentication and authorization
- **Registrations** - responsible for user registration
- **Meetings** - implements Meetings Bounded Context: creating meeting groups, meetings
- **Administration** - implements Administration Bounded Context: implements administrative tasks like meeting group proposal verification
- **Payments** - implements Payments Bounded Context: implements all functionalities associated with payments
- **In Memory Events Bus** - Publish/Subscribe implementation to asynchronously integrate all modules using events ([Event Driven Architecture](https://en.wikipedia.org/wiki/Event-driven_architecture)).
**Key assumptions:**
1. API contains no application logic
2. API communicates with Modules using a small interface to send Queries and Commands
3. Each Module has its own interface which is used by API
4. **Modules communicate each other only asynchronously using Events Bus** - direct method calls are not allowed
5. Each Module **has it's own data** in a separate schema - shared data is not allowed
- Module data could be moved into separate databases if desired
6. Modules can only have a dependency on the integration events assembly of other Module (see [Module level view](#32-module-level-view))
7. Each Module has its own [Composition Root](https://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/), which implies that each Module has its own Inversion-of-Control container
8. API as a host needs to initialize each module and each module has an initialization method
9. Each Module is **highly encapsulated** - only required types and members are public, the rest are internal or private
### 3.2 Module Level View

Each Module has [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) and consists of the following submodules (assemblies):
- **Application** - the application logic submodule which is responsible for requests processing: use cases, domain events, integration events, internal commands.
- **Domain** - Domain Model in Domain-Driven Design terms implements the applicable [Bounded Context](https://martinfowler.com/bliki/BoundedContext.html)
- **Infrastructure** - infrastructural code responsible for module initialization, background processing, data access, communication with Events Bus and other external components or systems
- **IntegrationEvents** - **Contracts** published to the Events Bus; only this assembly can be called by other modules

**Note:** Application, Domain and Infrastructure assemblies could be merged into one assembly. Some people like horizontal layering or more decomposition, some don't. Implementing the Domain Model or Infrastructure in separate assembly allows encapsulation using the [`internal`](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal) keyword. Sometimes Bounded Context logic is not worth it because it is too simple. As always, be pragmatic and take whatever approach you like.
### 3.3 API and Module Communication
The API only communicates with Modules in two ways: during module initialization and request processing.
**Module initialization**
Each module has a static ``Initialize`` method which is invoked in the API ``Startup`` class. All configuration needed by this module should be provided as arguments to this method. All services are configured during initialization and the Composition Root is created using the Inversion-of-Control Container.
```csharp
public static void Initialize(
string connectionString,
IExecutionContextAccessor executionContextAccessor,
ILogger logger,
EmailsConfiguration emailsConfiguration)
{
var moduleLogger = logger.ForContext("Module", "Meetings");
ConfigureCompositionRoot(connectionString, executionContextAccessor, moduleLogger, emailsConfiguration);
QuartzStartup.Initialize(moduleLogger);
EventsBusStartup.Initialize(moduleLogger);
}
```
**Request processing**
Each module has the same interface signature exposed to the API. It contains 3 methods: command with result, command without result and query.
```csharp
public interface IMeetingsModule
{
Task ExecuteCommandAsync(ICommand command);
Task ExecuteCommandAsync(ICommand command);
Task ExecuteQueryAsync(IQuery query);
}
```
**Note:** Some people say that processing a command should not return a result. This is an understandable approach but sometimes impractical, especially when you want to immediately return the ID of a newly created resource. Sometimes the boundary between Command and Query is blurry. One example is ``AuthenticateCommand`` - it returns a token but it is not a query because it has a side effect.
### 3.4 Module Requests Processing via CQRS
Processing of Commands and Queries is separated by applying the architectural style/pattern [Command Query Responsibility Segregation (CQRS)](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs).

Commands are processed using *Write Model* which is implemented using DDD tactical patterns:
```csharp
internal class CreateNewMeetingGroupCommandHandler : ICommandHandler
{
private readonly IMeetingGroupRepository _meetingGroupRepository;
private readonly IMeetingGroupProposalRepository _meetingGroupProposalRepository;
internal CreateNewMeetingGroupCommandHandler(
IMeetingGroupRepository meetingGroupRepository,
IMeetingGroupProposalRepository meetingGroupProposalRepository)
{
_meetingGroupRepository = meetingGroupRepository;
_meetingGroupProposalRepository = meetingGroupProposalRepository;
}
public async Task Handle(CreateNewMeetingGroupCommand request, CancellationToken cancellationToken)
{
var meetingGroupProposal = await _meetingGroupProposalRepository.GetByIdAsync(request.MeetingGroupProposalId);
var meetingGroup = meetingGroupProposal.CreateMeetingGroup();
await _meetingGroupRepository.AddAsync(meetingGroup);
}
}
```
Queries are processed using *Read Model* which is implemented by executing raw SQL statements on database views:
```csharp
internal class GetAllMeetingGroupsQueryHandler : IQueryHandler>
{
private readonly ISqlConnectionFactory _sqlConnectionFactory;
internal GetAllMeetingGroupsQueryHandler(ISqlConnectionFactory sqlConnectionFactory)
{
_sqlConnectionFactory = sqlConnectionFactory;
}
public async Task> Handle(GetAllMeetingGroupsQuery request, CancellationToken cancellationToken)
{
var connection = _sqlConnectionFactory.GetOpenConnection();
const string sql = $"""
SELECT
[MeetingGroup].[Id] as [{nameof(MeetingGroupDto.Id)}] ,
[MeetingGroup].[Name] as [{nameof(MeetingGroupDto.Name)}],
[MeetingGroup].[Description] as [{nameof(MeetingGroupDto.Description)}]
[MeetingGroup].[LocationCountryCode] as [{nameof(MeetingGroupDto.LocationCountryCode)}],
[MeetingGroup].[LocationCity] as [{nameof(MeetingGroupDto.LocationCity)}]
FROM [meetings].[v_MeetingGroups] AS [MeetingGroup]
""";
var meetingGroups = await connection.QueryAsync(sql);
return meetingGroups.AsList();
}
}
```
**Key advantages:**
- Solution is appropriate to the problem - reading and writing needs are usually different
- Supports [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle) (SRP) - one handler does one thing
- Supports [Interface Segregation Principle](https://en.wikipedia.org/wiki/Interface_segregation_principle) (ISP) - each handler implements interface with exactly one method
- Supports [Parameter Object pattern](https://refactoring.com/catalog/introduceParameterObject.html) - Commands and Queries are objects which are easy to serialize/deserialize
- Easy way to apply [Decorator pattern](https://en.wikipedia.org/wiki/Decorator_pattern) to handle cross-cutting concerns
- Supports Loose Coupling by use of the [Mediator pattern](https://en.wikipedia.org/wiki/Mediator_pattern) - separates invoker of request from handler of request
**Disadvantage:**
- Mediator pattern introduces extra indirection and is harder to reason about which class handles the request
For more information: [Simple CQRS implementation with raw SQL and DDD](https://www.kamilgrzybek.com/design/simple-cqrs-implementation-with-raw-sql-and-ddd/)
### 3.5 Domain Model Principles and Attributes
The Domain Model, which is the central and most critical part in the system, should be designed with special attention. Here are some key principles and attributes which are applied to Domain Models of each module:
1. **High level of encapsulation**
All members are ``private`` by default, then ``internal`` - only ``public`` at the very edge.
2. **High level of PI (Persistence Ignorance)**
No dependencies to infrastructure, databases, etc. All classes are [POCOs](https://en.wikipedia.org/wiki/Plain_old_CLR_object).
3. **Rich in behavior**
All business logic is located in the Domain Model. No leaks to the application layer or elsewhere.
4. **Low level of Primitive Obsession**
Primitive attributes of Entites grouped together using ValueObjects.
5. **Business language**
All classes, methods and other members are named in business language used in this Bounded Context.
6. **Testable**
The Domain Model is a critical part of the system so it should be easy to test (Testable Design).
```csharp
public class MeetingGroup : Entity, IAggregateRoot
{
public MeetingGroupId Id { get; private set; }
private string _name;
private string _description;
private MeetingGroupLocation _location;
private MemberId _creatorId;
private List _members;
private DateTime _createDate;
private DateTime? _paymentDateTo;
internal static MeetingGroup CreateBasedOnProposal(
MeetingGroupProposalId meetingGroupProposalId,
string name,
string description,
MeetingGroupLocation location, MemberId creatorId)
{
return new MeetingGroup(meetingGroupProposalId, name, description, location, creatorId);
}
public Meeting CreateMeeting(
string title,
MeetingTerm term,
string description,
MeetingLocation location,
int? attendeesLimit,
int guestsLimit,
Term rsvpTerm,
MoneyValue eventFee,
List hostsMembersIds,
MemberId creatorId)
{
this.CheckRule(new MeetingCanBeOrganizedOnlyByPayedGroupRule(_paymentDateTo));
this.CheckRule(new MeetingHostMustBeAMeetingGroupMemberRule(creatorId, hostsMembersIds, _members));
return new Meeting(this.Id,
title,
term,
description,
location,
attendeesLimit,
guestsLimit,
rsvpTerm,
eventFee,
hostsMembersIds,
creatorId);
}
```
### 3.6 Cross-Cutting Concerns
To support [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle) and [Don't Repeat Yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principles, the implementation of cross-cutting concerns is done using the [Decorator Pattern](https://en.wikipedia.org/wiki/Decorator_pattern). Each Command processor is decorated by 3 decorators: logging, validation and unit of work.

**Logging**
The Logging decorator logs execution, arguments and processing of each Command. This way each log inside a processor has the log context of the processing command.
```csharp
internal class LoggingCommandHandlerDecorator : ICommandHandler where T:ICommand
{
private readonly ILogger _logger;
private readonly IExecutionContextAccessor _executionContextAccessor;
private readonly ICommandHandler _decorated;
public LoggingCommandHandlerDecorator(
ILogger logger,
IExecutionContextAccessor executionContextAccessor,
ICommandHandler decorated)
{
_logger = logger;
_executionContextAccessor = executionContextAccessor;
_decorated = decorated;
}
public async Task Handle(T command, CancellationToken cancellationToken)
{
if (command is IRecurringCommand)
{
return await _decorated.Handle(command, cancellationToken);
}
using (
LogContext.Push(
new RequestLogEnricher(_executionContextAccessor),
new CommandLogEnricher(command)))
{
try
{
this._logger.Information(
"Executing command {Command}",
command.GetType().Name);
var result = await _decorated.Handle(command, cancellationToken);
this._logger.Information("Command {Command} processed successful", command.GetType().Name);
return result;
}
catch (Exception exception)
{
this._logger.Error(exception, "Command {Command} processing failed", command.GetType().Name);
throw;
}
}
}
private class CommandLogEnricher : ILogEventEnricher
{
private readonly ICommand _command;
public CommandLogEnricher(ICommand command)
{
_command = command;
}
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddOrUpdateProperty(new LogEventProperty("Context", new ScalarValue($"Command:{_command.Id.ToString()}")));
}
}
private class RequestLogEnricher : ILogEventEnricher
{
private readonly IExecutionContextAccessor _executionContextAccessor;
public RequestLogEnricher(IExecutionContextAccessor executionContextAccessor)
{
_executionContextAccessor = executionContextAccessor;
}
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (_executionContextAccessor.IsAvailable)
{
logEvent.AddOrUpdateProperty(new LogEventProperty("CorrelationId", new ScalarValue(_executionContextAccessor.CorrelationId)));
}
}
}
}
```
**Validation**
The Validation decorator performs Command data validation. It checks rules against Command arguments using the FluentValidation library.
```csharp
internal class ValidationCommandHandlerDecorator : ICommandHandler where T:ICommand
{
private readonly IList> _validators;
private readonly ICommandHandler _decorated;
public ValidationCommandHandlerDecorator(
IList> validators,
ICommandHandler decorated)
{
this._validators = validators;
_decorated = decorated;
}
public Task Handle(T command, CancellationToken cancellationToken)
{
var errors = _validators
.Select(v => v.Validate(command))
.SelectMany(result => result.Errors)
.Where(error => error != null)
.ToList();
if (errors.Any())
{
var errorBuilder = new StringBuilder();
errorBuilder.AppendLine("Invalid command, reason: ");
foreach (var error in errors)
{
errorBuilder.AppendLine(error.ErrorMessage);
}
throw new InvalidCommandException(errorBuilder.ToString(), null);
}
return _decorated.Handle(command, cancellationToken);
}
}
```
**Unit Of Work**
All Command processing has side effects. To avoid calling commit on every handler, `UnitOfWorkCommandHandlerDecorator` is used. It additionally marks `InternalCommand` as processed (if it is Internal Command) and dispatches all Domain Events (as part of [Unit Of Work](https://martinfowler.com/eaaCatalog/unitOfWork.html)).
```csharp
public class UnitOfWorkCommandHandlerDecorator : ICommandHandler where T:ICommand
{
private readonly ICommandHandler _decorated;
private readonly IUnitOfWork _unitOfWork;
private readonly MeetingsContext _meetingContext;
public UnitOfWorkCommandHandlerDecorator(
ICommandHandler decorated,
IUnitOfWork unitOfWork,
MeetingsContext meetingContext)
{
_decorated = decorated;
_unitOfWork = unitOfWork;
_meetingContext = meetingContext;
}
public async Task Handle(T command, CancellationToken cancellationToken)
{
await this._decorated.Handle(command, cancellationToken);
if (command is InternalCommandBase)
{
var internalCommand =
await _meetingContext.InternalCommands.FirstOrDefaultAsync(x => x.Id == command.Id,
cancellationToken: cancellationToken);
if (internalCommand != null)
{
internalCommand.ProcessedDate = DateTime.UtcNow;
}
}
await this._unitOfWork.CommitAsync(cancellationToken);
}
}
```
### 3.7 Modules Integration
Integration between modules is strictly **asynchronous** using Integration Events and the In Memory Event Bus as broker. In this way coupling between modules is minimal and exists only on the structure of Integration Events.
**Modules don't share data** so it is not possible nor desirable to create a transaction which spans more than one module. To ensure maximum reliability, the [Outbox / Inbox pattern](http://www.kamilgrzybek.com/design/the-outbox-pattern/) is used. This pattern provides accordingly *"At-Least-Once delivery"* and *"At-Least-Once processing"*.

The Outbox and Inbox is implemented using two SQL tables and a background worker for each module. The background worker is implemented using the Quartz.NET library.
**Saving to Outbox:**

**Processing Outbox:**

### 3.8 Internal Processing
The main principle of this system is that you can change its state only by calling a specific Command.
Commands can be called not only by the API, but by the processing module itself. The main use case which implements this mechanism is data processing in eventual consistency mode when we want to process something in a different process and transaction. This applies, for example, to Inbox processing because we want to do something (calling a Command) based on an Integration Event from the Inbox.
This idea is taken from Alberto's Brandolini's Event Storming picture called "The picture that explains “almost” everything" which shows that every side effect (domain event) is created by invoking a Command on Aggregate. See [EventStorming cheat sheet](https://xebia.com/blog/eventstorming-cheat-sheet/) article for more details.
Implementation of internal processing is very similar to implementation of the Outbox and Inbox. One SQL table and one background worker for processing. Each internally processing Command must inherit from `InternalCommandBase` class:
```csharp
internal abstract class InternalCommandBase : ICommand
{
public Guid Id { get; }
protected InternalCommandBase(Guid id)
{
this.Id = id;
}
}
```
This is important because the `UnitOfWorkCommandHandlerDecorator` must mark an internal Command as processed during committing:
```csharp
public async Task Handle(T command, CancellationToken cancellationToken)
{
await this._decorated.Handle(command, cancellationToken);
if (command is InternalCommandBase)
{
var internalCommand =
await _meetingContext.InternalCommands.FirstOrDefaultAsync(x => x.Id == command.Id,
cancellationToken: cancellationToken);
if (internalCommand != null)
{
internalCommand.ProcessedDate = DateTime.UtcNow;
}
}
await this._unitOfWork.CommitAsync(cancellationToken);
}
```
### 3.9 Security
**Authentication**
Authentication is implemented using JWT Token and Bearer scheme using IdentityServer. For now, only one authentication method is implemented: forms style authentication (username and password) via the OAuth2 [Resource Owner Password Grant Type](https://www.oauth.com/oauth2-servers/access-tokens/password-grant/). It requires implementation of the `IResourceOwnerPasswordValidator` interface:
```csharp
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
private readonly IUserAccessModule _userAccessModule;
public ResourceOwnerPasswordValidator(IUserAccessModule userAccessModule)
{
_userAccessModule = userAccessModule;
}
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var authenticationResult = await _userAccessModule.ExecuteCommandAsync(new AuthenticateCommand(context.UserName, context.Password));
if (!authenticationResult.IsAuthenticated)
{
context.Result = new GrantValidationResult(
TokenRequestErrors.InvalidGrant,
authenticationResult.AuthenticationError);
return;
}
context.Result = new GrantValidationResult(
authenticationResult.User.Id.ToString(),
"forms",
authenticationResult.User.Claims);
}
}
```
**Authorization**
Authorization is achieved by implementing [RBAC (Role Based Access Control)](https://en.wikipedia.org/wiki/Role-based_access_control) using Permissions. Permissions are more granular and a much better way to secure your application than Roles alone. Each User has a set of Roles and each Role contains one or more Permission. The User's set of Permissions is extracted from all Roles the User belongs to. Permissions are always checked on `Controller` level - never Roles:
```csharp
[HttpPost]
[Route("")]
[HasPermission(MeetingsPermissions.ProposeMeetingGroup)]
public async Task ProposeMeetingGroup(ProposeMeetingGroupRequest request)
{
await _meetingsModule.ExecuteCommandAsync(
new ProposeMeetingGroupCommand(
request.Name,
request.Description,
request.LocationCity,
request.LocationCountryCode));
return Ok();
}
```
### 3.10 Unit Tests
**Definition:**
>A unit test is an automated piece of code that invokes the unit of work being tested, and then checks some assumptions about a single end result of that unit. A unit test is almost always written using a unit testing framework. It can be written easily and runs quickly. It’s trustworthy, readable, and maintainable. It’s consistent in its results as long as production code hasn’t changed. [Art of Unit Testing 2nd Edition](https://www.manning.com/books/the-art-of-unit-testing-second-edition) Roy Osherove
**Attributes of good unit test**
- Automated
- Maintainable
- Runs very fast (in ms)
- Consistent, Deterministic (always the same result)
- Isolated from other tests
- Readable
- Can be executed by anyone
- Testing public API, not internal behavior (overspecification)
- Looks like production code
- Treated as production code
**Implementation**
Unit tests should mainly test business logic (domain model):

Each unit test has 3 standard sections: Arrange, Act and Assert:

**1\. Arrange**
The Arrange section is responsible for preparing the Aggregate for testing the public method that we want to test. This public method is often called (from the unit tests perspective) the SUT (system under test).
Creating an Aggregate ready for testing involves **calling one or more other public constructors/methods** on the Domain Model. At first it may seem that we are testing too many things at the same time, but this is not true. We need to be one hundred percent sure that the Aggregate is in a state exactly as it will be in production. This can only be ensured when we:
- **Use only public API of Domain Model**
- Don't use [InternalsVisibleToAttribute](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute?view=netframework-4.8) class
- This exposes the Domain Model to the Unit Tests library, removing encapsulation so our tests and production code are treated differently and it is a very bad thing
- Don't use [ConditionalAttribute](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=netframework-4.8) classes - it reduces readability and increases complexity
- Don't create any special constructors/factory methods for tests (even with conditional compilation symbols)
- Special constructor/factory method only for unit tests causes duplication of business logic in the test itself and focuses on state - this kind of approach causes the test to be very sensitive to changes and hard to maintain
- Don't remove encapsulation from Domain Model (for example: change keywords from `internal`/`private` to `public`)
- Don't make methods `protected` to inherit from tested class and in this way provide access to internal methods/properties
**Isolation of external dependencies**
There are 2 main concepts - stubs and mocks:
> A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.
>A mock object is a fake object in the system that decides whether the unit test has passed or failed. It does so by verifying whether the object under test called the fake object as expected. There’s usually no more than one mock per test.
>[Art of Unit Testing 2nd Edition](https://www.manning.com/books/the-art-of-unit-testing-second-edition) Roy Osherove
Good advice: use stubs if you need to, but try to avoid mocks. Mocking causes us to test too many internal things and leads to overspecification.
**2\. Act**
This section is very easy - we execute **exactly one** public method on aggregate (SUT).
**3\. Assert**
In this section we check expectations. There are only 2 possible outcomes:
- Method completed and Domain Event(s) published
- Business rule was broken
Simple example:
```csharp
[Test]
public void NewUserRegistration_WithUniqueLogin_IsSuccessful()
{
// Arrange
var usersCounter = Substitute.For();
// Act
var userRegistration =
UserRegistration.RegisterNewUser(
"login", "password", "test@email",
"firstName", "lastName", usersCounter);
// Assert
var newUserRegisteredDomainEvent = AssertPublishedDomainEvent(userRegistration);
Assert.That(newUserRegisteredDomainEvent.UserRegistrationId, Is.EqualTo(userRegistration.Id));
}
[Test]
public void NewUserRegistration_WithoutUniqueLogin_BreaksUserLoginMustBeUniqueRule()
{
// Arrange
var usersCounter = Substitute.For();
usersCounter.CountUsersWithLogin("login").Returns(x => 1);
// Assert
AssertBrokenRule(() =>
{
// Act
UserRegistration.RegisterNewUser(
"login", "password", "test@email",
"firstName", "lastName", usersCounter);
});
}
```
Advanced example:
```csharp
[Test]
public void AddAttendee_WhenMemberIsAlreadyAttendeeOfMeeting_IsNotPossible()
{
// Arrange
var creatorId = new MemberId(Guid.NewGuid());
var meetingTestData = CreateMeetingTestData(new MeetingTestDataOptions
{
CreatorId = creatorId
});
var newMemberId = new MemberId(Guid.NewGuid());
meetingTestData.MeetingGroup.JoinToGroupMember(newMemberId);
meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, newMemberId, 0);
// Assert
AssertBrokenRule(() =>
{
// Act
meetingTestData.Meeting.AddAttendee(meetingTestData.MeetingGroup, newMemberId, 0);
});
}
```
`CreateMeetingTestData` method is an implementation of [SUT Factory](https://blog.ploeh.dk/2009/02/13/SUTFactory/) described by Mark Seemann which allows keeping common creation logic in one place:
```csharp
protected MeetingTestData CreateMeetingTestData(MeetingTestDataOptions options)
{
var proposalMemberId = options.CreatorId ?? new MemberId(Guid.NewGuid());
var meetingProposal = MeetingGroupProposal.ProposeNew(
"name", "description",
new MeetingGroupLocation("Warsaw", "PL"), proposalMemberId);
meetingProposal.Accept();
var meetingGroup = meetingProposal.CreateMeetingGroup();
meetingGroup.UpdatePaymentInfo(DateTime.Now.AddDays(1));
var meetingTerm = options.MeetingTerm ??
new MeetingTerm(DateTime.UtcNow.AddDays(1), DateTime.UtcNow.AddDays(2));
var rsvpTerm = options.RvspTerm ?? Term.NoTerm;
var meeting = meetingGroup.CreateMeeting("title",
meetingTerm,
"description",
new MeetingLocation("Name", "Address", "PostalCode", "City"),
options.AttendeesLimit,
options.GuestsLimit,
rsvpTerm,
MoneyValue.Zero,
new List(),
proposalMemberId);
DomainEventsTestHelper.ClearAllDomainEvents(meetingGroup);
return new MeetingTestData(meetingGroup, meeting);
}
```
### 3.11 Architecture Decision Log
All Architectural Decisions (AD) are documented in the [Architecture Decision Log (ADL)](docs/architecture-decision-log).
More information about documenting architecture-related decisions in this way : [https://github.com/joelparkerhenderson/architecture_decision_record](https://github.com/joelparkerhenderson/architecture_decision_record)
### 3.12 Architecture Unit Tests
In some cases it is not possible to enforce the application architecture, design or established conventions using compiler (compile-time). For this reason, code implementations can diverge from the original design and architecture. We want to minimize this behavior, not only by code review.
To do this, unit tests of system architecture, design, major conventions and assumptions have been written. In .NET there is special library for this task: [NetArchTest](https://github.com/BenMorris/NetArchTest). This library has been written based on the very popular JAVA architecture unit tests library - [ArchUnit](https://www.archunit.org/).
Using this kind of tests we can test proper layering of our application, dependencies, encapsulation, immutability, DDD correct implementation, naming, conventions and so on - everything what we need to test. Example:

More information about architecture unit tests here: [https://blogs.oracle.com/javamagazine/unit-test-your-architecture-with-archunit](https://blogs.oracle.com/javamagazine/unit-test-your-architecture-with-archunit)
### 3.13 Integration Tests
#### Definition
"Integration Test" term is blurred. It can mean test between classes, modules, services, even systems - see [this](https://martinfowler.com/bliki/IntegrationTest.html) article (by Martin Fowler).
For this reason, the definition of integration test in this project is as follows:
- it verifies how system works in integration with "out-of-process" dependencies - database, messaging system, file system or external API
- it tests particular use case
- it can be slow (as opposed to Unit Test)
#### Approach
- **Do not mock dependencies over which you have full control** (like database). Full control dependency means you can always revert all changes (remove side-effects) and no one can notice it. They are not visible to others. See next point, please.
- **Use "production", normal, real database version**. Some use e.g. in memory repository, some use light databases instead "production" version. This is still mocking. Testing makes sense if we have full confidence in testing. You can't trust the test if you know that the infrastructure in the production environment will vary. Be always as close to production environment as possible.
- **Mock dependencies over which you don't have control**. No control dependency means you can't remove side-effects after interaction with this dependency (external API, messaging system, SMTP server etc.). They can be visible to others.
#### Implementation
Integration test should test exactly one use case. One use case is represented by one Command/Query processing so CommandHandler/QueryHandler in Application layer is perfect starting point for running the Integration Test:

For each test, the following preparation steps must be performed:
1. Clear database
2. Prepare mocks
3. Initialize testing module
```csharp
[SetUp]
public async Task BeforeEachTest()
{
const string connectionStringEnvironmentVariable =
"ASPNETCORE_MyMeetings_IntegrationTests_ConnectionString";
ConnectionString = Environment.GetEnvironmentVariable(connectionStringEnvironmentVariable, EnvironmentVariableTarget.Machine);
if (ConnectionString == null)
{
throw new ApplicationException(
$"Define connection string to integration tests database using environment variable: {connectionStringEnvironmentVariable}");
}
using (var sqlConnection = new SqlConnection(ConnectionString))
{
await ClearDatabase(sqlConnection);
}
Logger = Substitute.For();
EmailSender = Substitute.For();
EventsBus = new EventsBusMock();
ExecutionContext = new ExecutionContextMock(Guid.NewGuid());
PaymentsStartup.Initialize(
ConnectionString,
ExecutionContext,
Logger,
EventsBus,
false);
PaymentsModule = new PaymentsModule();
}
```
After preparation, test is performed on clear database. Usually, it is the execution of some (or many) Commands and:
a) running a Query or/and
b) verifying mocks
to check the result.
```csharp
[TestFixture]
public class MeetingPaymentTests : TestBase
{
[Test]
public async Task CreateMeetingPayment_Test()
{
PayerId payerId = new PayerId(Guid.NewGuid());
MeetingId meetingId = new MeetingId(Guid.NewGuid());
decimal value = 100;
string currency = "EUR";
await PaymentsModule.ExecuteCommandAsync(new CreateMeetingPaymentCommand(Guid.NewGuid(),
payerId, meetingId, value, currency));
var payment = await PaymentsModule.ExecuteQueryAsync(new GetMeetingPaymentQuery(meetingId.Value, payerId.Value));
Assert.That(payment.PayerId, Is.EqualTo(payerId.Value));
Assert.That(payment.MeetingId, Is.EqualTo(meetingId.Value));
Assert.That(payment.FeeValue, Is.EqualTo(value));
Assert.That(payment.FeeCurrency, Is.EqualTo(currency));
}
}
```
Each Command/Query processing is a separate execution (with different object graph resolution, context, database connection etc.) thanks to Composition Root of each module. This behavior is important and desirable.
### 3.14 System Integration Testing
#### Definition
[System Integration Testing (SIT)](https://en.wikipedia.org/wiki/System_integration_testing) is performed to verify the interactions between the modules of a software system. It involves the overall testing of a complete system of many subsystem components or elements.
#### Implementation
Implementation of system integration tests is based on approach of integration testing of modules in isolation (invoking commands and queries) described in the previous section.
The problem is that in this case we are dealing with **asynchronous communication**. Due to asynchrony, our **test must wait for the result** at certain times.
To correctly implement such tests, the **Sampling** technique and implementation described in the [Growing Object-Oriented Software, Guided by Tests](https://www.amazon.com/Growing-Object-Oriented-Software-Guided-Tests/dp/0321503627) book was used:
>An asynchronous test must wait for success and use timeouts to detect failure. This implies that every tested activity must have an observable effect: a test must affect the system so that its observable state becomes different. This sounds obvious but it drives how we think about writing asynchronous tests. If an activity has no observable effect, there is nothing the test can wait for, and therefore no way for the test to synchronize with the system it is testing. There are two ways a test can observe the system: by sampling its observable state or by listening for events that it sends out.

Test below:
1. Creates Meeting Group Proposal in Meetings module
2. Waits until Meeting Group Proposal to verification will be available in Administration module with 10 seconds timeout
3. Accepts Meeting Group Proposal in Administration module
4. Waits until Meeting Group is created in Meetings module with 15 seconds timeout
```csharp
public class CreateMeetingGroupTests : TestBase
{
[Test]
public async Task CreateMeetingGroupScenario_WhenProposalIsAccepted()
{
var meetingGroupId = await MeetingsModule.ExecuteCommandAsync(
new ProposeMeetingGroupCommand("Name",
"Description",
"Location",
"PL"));
AssertEventually(
new GetMeetingGroupProposalFromAdministrationProbe(meetingGroupId, AdministrationModule),
10000);
await AdministrationModule.ExecuteCommandAsync(new AcceptMeetingGroupProposalCommand(meetingGroupId));
AssertEventually(
new GetCreatedMeetingGroupFromMeetingsProbe(meetingGroupId, MeetingsModule),
15000);
}
private class GetCreatedMeetingGroupFromMeetingsProbe : IProbe
{
private readonly Guid _expectedMeetingGroupId;
private readonly IMeetingsModule _meetingsModule;
private List _allMeetingGroups;
public GetCreatedMeetingGroupFromMeetingsProbe(
Guid expectedMeetingGroupId,
IMeetingsModule meetingsModule)
{
_expectedMeetingGroupId = expectedMeetingGroupId;
_meetingsModule = meetingsModule;
}
public bool IsSatisfied()
{
return _allMeetingGroups != null &&
_allMeetingGroups.Any(x => x.Id == _expectedMeetingGroupId);
}
public async Task SampleAsync()
{
_allMeetingGroups = await _meetingsModule.ExecuteQueryAsync(new GetAllMeetingGroupsQuery());
}
public string DescribeFailureTo()
=> $"Meeting group with ID: {_expectedMeetingGroupId} is not created";
}
private class GetMeetingGroupProposalFromAdministrationProbe : IProbe
{
private readonly Guid _expectedMeetingGroupProposalId;
private MeetingGroupProposalDto _meetingGroupProposal;
private readonly IAdministrationModule _administrationModule;
public GetMeetingGroupProposalFromAdministrationProbe(Guid expectedMeetingGroupProposalId, IAdministrationModule administrationModule)
{
_expectedMeetingGroupProposalId = expectedMeetingGroupProposalId;
_administrationModule = administrationModule;
}
public bool IsSatisfied()
{
if (_meetingGroupProposal == null)
{
return false;
}
if (_meetingGroupProposal.Id == _expectedMeetingGroupProposalId &&
_meetingGroupProposal.StatusCode == MeetingGroupProposalStatus.ToVerify.Value)
{
return true;
}
return false;
}
public async Task SampleAsync()
{
try
{
_meetingGroupProposal =
await _administrationModule.ExecuteQueryAsync(
new GetMeetingGroupProposalQuery(_expectedMeetingGroupProposalId));
}
catch
{
// ignored
}
}
public string DescribeFailureTo()
=> $"Meeting group proposal with ID: {_expectedMeetingGroupProposalId} to verification not created";
}
}
```
Poller class implementation (based on example in the book):
```csharp
public class Poller
{
private readonly int _timeoutMillis;
private readonly int _pollDelayMillis;
public Poller(int timeoutMillis)
{
_timeoutMillis = timeoutMillis;
_pollDelayMillis = 1000;
}
public void Check(IProbe probe)
{
var timeout = new Timeout(_timeoutMillis);
while (!probe.IsSatisfied())
{
if (timeout.HasTimedOut())
{
throw new AssertErrorException(DescribeFailureOf(probe));
}
Thread.Sleep(_pollDelayMillis);
probe.SampleAsync();
}
}
private static string DescribeFailureOf(IProbe probe)
{
return probe.DescribeFailureTo();
}
}
```
### 3.15 Event Sourcing
#### Theory
During the implementation of the Payment module, *Event Sourcing* was used. *Event Sourcing* is a way of preserving the state of our system by recording a sequence of events. No less, no more.
It is important here to really restore the state of our application from events. If we collect events only for auditing purposes, it is an [Audit Log/Trail](https://en.wikipedia.org/wiki/Audit_trail) - not the *Event Sourcing*.
The main elements of *Event Sourcing* are as follows:
- Events Stream
- Objects that are restored based on events. There are 2 types of such objects depending on the purpose:
-- Objects responsible for the change of state. In Domain-Driven Design they will be *Aggregates*.
-- *Projections*: read models prepared for a specific purpose
- *Subscriptions* : a way to receive information about new events
- *Snapshots*: from time to time, objects saved in the traditional way for performance purposes. Mainly used if there are many events to restore the object from the entire event history. (Note: there is currently no snapshot implementation in the project)

#### Tool
In order not to reinvent the wheel, the *SQL Stream Store* library was used. As the [documentation](https://sqlstreamstore.readthedocs.io/en/latest/) says:
*SQL Stream Store is a .NET library to assist with developing applications that use event sourcing or wish to use stream based patterns over a relational database and existing operational infrastructure.*
Like every library, it has its limitations and assumptions (I recommend the linked documentation chapter "Things you need to know before adopting"). For me, the most important 2 points from this chapter are:
1. *"Subscriptions (and thus projections) are **eventually consistent** and always will be."* This means that there will always be an inconsistency time from saving the event to the stream and processing the event by the projector(s).
2. *"No support for ambient System.Transaction scopes enforcing the concept of the stream as the consistency and transactional boundary."* This means that if we save the event to a events stream and want to save something **in the same transaction**, we must use [TransactionScope](https://learn.microsoft.com/en-us/dotnet/api/system.transactions.transactionscope?view=net-8.0). If we cannot use *TransactionScope* for some reason, we must accept the Eventual Consistency also in this case.
Other popular tools:
- [EventStore](https://eventstore.com/) *"An industrial-strength database solution built from the ground up for event sourcing."*
- [Marten](https://martendb.io/) *".NET Transactional Document DB and Event Store on PostgreSQL"*
#### Implementation
There are 2 main "flows" to handle:
- Command handling: change of state - adding new events to stream (writing)
- Projection of events to create read models
##### Command Handling
The whole process looks like this:

1. We create / update an aggregate by creating an event
2. We add changes to the Aggregate Store. This is the class responsible for writing / loading our aggregates. We are not saving changes yet.
3. As part of Unit Of Work a) Aggregate Store adds events to the stream b) messages are added to the Outbox
Command Handler:
```csharp
public class BuySubscriptionCommandHandler : ICommandHandler
{
private readonly IAggregateStore _aggregateStore;
private readonly IPayerContext _payerContext;
private readonly ISqlConnectionFactory _sqlConnectionFactory;
public BuySubscriptionCommandHandler(
IAggregateStore aggregateStore,
IPayerContext payerContext,
ISqlConnectionFactory sqlConnectionFactory)
{
_aggregateStore = aggregateStore;
_payerContext = payerContext;
_sqlConnectionFactory = sqlConnectionFactory;
}
public async Task Handle(BuySubscriptionCommand command, CancellationToken cancellationToken)
{
var priceList = await PriceListProvider.GetPriceList(_sqlConnectionFactory.GetOpenConnection());
var subscriptionPayment = SubscriptionPayment.Buy(
_payerContext.PayerId,
SubscriptionPeriod.Of(command.SubscriptionTypeCode),
command.CountryCode,
MoneyValue.Of(command.Value, command.Currency),
priceList);
_aggregateStore.AppendChanges(subscriptionPayment);
return subscriptionPayment.Id;
}
}
```
`SubscriptionPayment` Aggregate:
```csharp
public class SubscriptionPayment : AggregateRoot
{
private PayerId _payerId;
private SubscriptionPeriod _subscriptionPeriod;
private string _countryCode;
private SubscriptionPaymentStatus _subscriptionPaymentStatus;
private MoneyValue _value;
protected override void Apply(IDomainEvent @event)
{
this.When((dynamic)@event);
}
public static SubscriptionPayment Buy(
PayerId payerId,
SubscriptionPeriod period,
string countryCode,
MoneyValue priceOffer,
PriceList priceList)
{
var priceInPriceList = priceList.GetPrice(countryCode, period, PriceListItemCategory.New);
CheckRule(new PriceOfferMustMatchPriceInPriceListRule(priceOffer, priceInPriceList));
var subscriptionPayment = new SubscriptionPayment();
var subscriptionPaymentCreated = new SubscriptionPaymentCreatedDomainEvent(
Guid.NewGuid(),
payerId.Value,
period.Code,
countryCode,
SubscriptionPaymentStatus.WaitingForPayment.Code,
priceOffer.Value,
priceOffer.Currency);
subscriptionPayment.Apply(subscriptionPaymentCreated);
subscriptionPayment.AddDomainEvent(subscriptionPaymentCreated);
return subscriptionPayment;
}
private void When(SubscriptionPaymentCreatedDomainEvent @event)
{
this.Id = @event.SubscriptionPaymentId;
_payerId = new PayerId(@event.PayerId);
_subscriptionPeriod = SubscriptionPeriod.Of(@event.SubscriptionPeriodCode);
_countryCode = @event.CountryCode;
_subscriptionPaymentStatus = SubscriptionPaymentStatus.Of(@event.Status);
_value = MoneyValue.Of(@event.Value, @event.Currency);
}
```
`AggregateRoot` base class:
```csharp
public abstract class AggregateRoot
{
public Guid Id { get; protected set; }
public int Version { get; private set; }
private readonly List _domainEvents;
protected AggregateRoot()
{
_domainEvents = new List();
Version = -1;
}
protected void AddDomainEvent(IDomainEvent @event)
{
_domainEvents.Add(@event);
}
public IReadOnlyCollection GetDomainEvents() => _domainEvents.AsReadOnly();
public void Load(IEnumerable history)
{
foreach (var e in history)
{
Apply(e);
Version++;
}
}
protected abstract void Apply(IDomainEvent @event);
protected static void CheckRule(IBusinessRule rule)
{
if (rule.IsBroken())
{
throw new BusinessRuleValidationException(rule);
}
}
}
```
Aggregate Store implementation with SQL Stream Store library usage:
```csharp
public class SqlStreamAggregateStore : IAggregateStore
{
private readonly IStreamStore _streamStore;
private readonly List _appendedChanges;
private readonly List _aggregatesToSave;
public SqlStreamAggregateStore(
ISqlConnectionFactory sqlConnectionFactory)
{
_appendedChanges = new List();
_streamStore =
new MsSqlStreamStore(
new MsSqlStreamStoreSettings(sqlConnectionFactory.GetConnectionString())
{
Schema = DatabaseSchema.Name
});
_aggregatesToSave = new List();
}
public async Task Save()
{
foreach (var aggregateToSave in _aggregatesToSave)
{
await _streamStore.AppendToStream(
GetStreamId(aggregateToSave.Aggregate),
aggregateToSave.Aggregate.Version,
aggregateToSave.Messages.ToArray());
}
_aggregatesToSave.Clear();
}
public async Task Load(AggregateId aggregateId) where T : AggregateRoot
{
var streamId = GetStreamId(aggregateId);
IList domainEvents = new List();
ReadStreamPage readStreamPage;
do
{
readStreamPage = await _streamStore.ReadStreamForwards(streamId, StreamVersion.Start, maxCount: 100);
var messages = readStreamPage.Messages;
foreach (var streamMessage in messages)
{
Type type = DomainEventTypeMappings.Dictionary[streamMessage.Type];
var jsonData = await streamMessage.GetJsonData();
var domainEvent = JsonConvert.DeserializeObject(jsonData, type) as IDomainEvent;
domainEvents.Add(domainEvent);
}
} while (!readStreamPage.IsEnd);
var aggregate = (T)Activator.CreateInstance(typeof(T), true);
aggregate.Load(domainEvents);
return aggregate;
}
```
##### Events Projection
The whole process looks like this:

1. Special class `Subscriptions Manager` subscribes to Events Store (using SQL Store Stream library)
2. Events Store raises `StreamMessageRecievedEvent`
3. `Subscriptions Manager` invokes all projectors
4. If projector know how to handle given event, it updates particular read model. In current implementation it updates special table in SQL database.
`SubscriptionsManager` class implementation:
```csharp
public class SubscriptionsManager
{
private readonly IStreamStore _streamStore;
public SubscriptionsManager(
IStreamStore streamStore)
{
_streamStore = streamStore;
}
public void Start()
{
long? actualPosition;
using (var scope = PaymentsCompositionRoot.BeginLifetimeScope())
{
var checkpointStore = scope.Resolve();
actualPosition = checkpointStore.GetCheckpoint(SubscriptionCode.All);
}
_streamStore.SubscribeToAll(actualPosition, StreamMessageReceived);
}
public void Stop()
{
_streamStore.Dispose();
}
private static async Task StreamMessageReceived(
IAllStreamSubscription subscription, StreamMessage streamMessage, CancellationToken cancellationToken)
{
var type = DomainEventTypeMappings.Dictionary[streamMessage.Type];
var jsonData = await streamMessage.GetJsonData(cancellationToken);
var domainEvent = JsonConvert.DeserializeObject(jsonData, type) as IDomainEvent;
using var scope = PaymentsCompositionRoot.BeginLifetimeScope();
var projectors = scope.Resolve>();
var tasks = projectors
.Select(async projector =>
{
await projector.Project(domainEvent);
});
await Task.WhenAll(tasks);
var checkpointStore = scope.Resolve();
await checkpointStore.StoreCheckpoint(SubscriptionCode.All, streamMessage.Position);
}
}
```
Example projector:
```csharp
internal class SubscriptionDetailsProjector : ProjectorBase, IProjector
{
private readonly IDbConnection _connection;
public SubscriptionDetailsProjector(ISqlConnectionFactory sqlConnectionFactory)
{
_connection = sqlConnectionFactory.GetOpenConnection();
}
public async Task Project(IDomainEvent @event)
{
await When((dynamic) @event);
}
private async Task When(SubscriptionRenewedDomainEvent subscriptionRenewed)
{
var period = SubscriptionPeriod.GetName(subscriptionRenewed.SubscriptionPeriodCode);
await _connection.ExecuteScalarAsync("UPDATE payments.SubscriptionDetails " +
"SET " +
"[Status] = @Status, " +
"[ExpirationDate] = @ExpirationDate, " +
"[Period] = @Period " +
"WHERE [Id] = @SubscriptionId",
new
{
subscriptionRenewed.SubscriptionId,
subscriptionRenewed.Status,
subscriptionRenewed.ExpirationDate,
period
});
}
private async Task When(SubscriptionExpiredDomainEvent subscriptionExpired)
{
await _connection.ExecuteScalarAsync("UPDATE payments.SubscriptionDetails " +
"SET " +
"[Status] = @Status " +
"WHERE [Id] = @SubscriptionId",
new
{
subscriptionExpired.SubscriptionId,
subscriptionExpired.Status
});
}
private async Task When(SubscriptionCreatedDomainEvent subscriptionCreated)
{
var period = SubscriptionPeriod.GetName(subscriptionCreated.SubscriptionPeriodCode);
await _connection.ExecuteScalarAsync("INSERT INTO payments.SubscriptionDetails " +
"([Id], [Period], [Status], [CountryCode], [ExpirationDate]) " +
"VALUES (@SubscriptionId, @Period, @Status, @CountryCode, @ExpirationDate)",
new
{
subscriptionCreated.SubscriptionId,
period,
subscriptionCreated.Status,
subscriptionCreated.CountryCode,
subscriptionCreated.ExpirationDate
});
}
}
```
#### Sample view of Event Store
Sample *Event Store* view after execution of SubscriptionLifecycleTests Integration Test which includes following steps:
1. Creating Price List
2. Buying Subscription
3. Renewing Subscription
4. Expiring Subscription
looks like this (*SQL Stream Store* table - *payments.Messages*):

### 3.16 Database Change Management
Database change management is accomplished by *migrations/transitions* versioning. Additionally, the current state of the database structure is also versioned.
Migrations are applied using a simple [DatabaseMigrator](src/Database/DatabaseMigrator) console application that uses the [DbUp](https://dbup.readthedocs.io/en/latest/) library. The current state of the database structure is kept in the [SSDT Database Project](https://docs.microsoft.com/en-us/sql/ssdt/how-to-create-a-new-database-project).
The database update is performed by running the following command:
```shell
dotnet DatabaseMigrator.dll "connection_string" "scripts_directory_path"
```
The entire solution is described in detail in the following articles:
1. [Database change management](https://www.kamilgrzybek.com/database/database-change-management/) (theory)
2. [Using database project and DbUp for database management](https://www.kamilgrzybek.com/database/using-database-project-and-dbup-for-database-management/) (implementation)
### 3.17 Continuous Integration
#### Definition
As defined on [Martin Fowler's website](https://martinfowler.com/articles/continuousIntegration.html):
> *Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily - leading to multiple integrations per day. Each integration is verified by an automated build (including test) to detect integration errors as quickly as possible.*
#### YAML Implementation [OBSOLETE]
*Originally the build was implemented using yaml and GitHub Actions functionality. Currently, the build is implemented with NUKE (see next section). See [buildPipeline.yml](.github/workflows/buildPipeline.yml)* file history.
##### Pipeline description
CI was implemented using [GitHub Actions](https://docs.github.com/en/actions/getting-started-with-github-actions/about-github-actions). For this purpose, one workflow, which triggers on Pull Request to *master* branch or Push to *master* branch was created. It contains 2 jobs:
- build test, execute Unit Tests and Architecture Tests
- execute Integration Tests

**Steps description**
a) Checkout repository - clean checkout of git repository
b) Setup .NET - install .NET 8.0 SDK
c) Install dependencies - resolve NuGet packages
d) Build - build solution
e) Run Unit Tests - run automated Unit Tests (see section 3.10)
f) Run Architecture Tests - run automated Architecture Tests (see section 3.12)
g) Initialize containers - setup Docker container for MS SQL Server
h) Wait for SQL Server initialization - after container initialization MS SQL Server is not ready, initialization of server itself takes some time so 30 seconds timeout before execution of next step is needed
i) Create Database - create and initialize database
j) Migrate Database - execute database upgrade using *DatabaseMigrator* application (see 3.16 section)
k) Run Integration Tests - perform Integration and System Integration Testing (see section 3.13 and 3.14)
##### Workflow definition
Workflow definition: [buildPipeline.yml](.github/workflows/buildPipeline.yml)
##### Example workflow execution
Example workflow output:


#### NUKE
[Nuke](https://nuke.build/) is *the cross-platform build automation solution for .NET with C# DSL.*
The 2 main advantages of its use over pure yaml defined in GitHub actions are as follows:
- You run the same code on local machine and in the build server. See [buildPipeline.yml](.github/workflows/buildPipeline.yml)
- You use C# with all the goodness (debugging, compilation, packages, refactoring and so on)
This is how one of the stage definition looks like (execute Build, Unit Tests, Architecture Tests) [Build.cs](build/Build.cs):
```csharp
partial class Build : NukeBuild
{
/// Support plugins are available for:
/// - JetBrains ReSharper https://nuke.build/resharper
/// - JetBrains Rider https://nuke.build/rider
/// - Microsoft VisualStudio https://nuke.build/visualstudio
/// - Microsoft VSCode https://nuke.build/vscode
public static int Main () => Execute(x => x.Compile);
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Solution] readonly Solution Solution;
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
EnsureCleanDirectory(WorkingDirectory);
});
Target Restore => _ => _
.Executes(() =>
{
DotNetRestore(s => s
.SetProjectFile(Solution));
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
DotNetBuild(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.EnableNoRestore());
});
Target UnitTests => _ => _
.DependsOn(Compile)
.Executes(() =>
{
DotNetTest(s => s
.SetProjectFile(Solution)
.SetFilter("UnitTests")
.SetConfiguration(Configuration)
.EnableNoRestore()
.EnableNoBuild());
});
Target ArchitectureTests => _ => _
.DependsOn(UnitTests)
.Executes(() =>
{
DotNetTest(s => s
.SetProjectFile(Solution)
.SetFilter("ArchTests")
.SetConfiguration(Configuration)
.EnableNoRestore()
.EnableNoBuild());
});
Target BuildAndUnitTests => _ => _
.Triggers(ArchitectureTests)
.Executes(() =>
{
});
}
```
If you want to see more complex scenario when integration tests are executed (with SQL Server database creation using docker) see [BuildIntegrationTests.cs](build/BuildIntegrationTests.cs) file.
#### SQL Server database project build
Currently, compilation of database projects is not supported by the .NET Core and dotnet tool. For this reason, the [MSBuild.Sdk.SqlProj](https://github.com/rr-wfm/MSBuild.Sdk.SqlProj/) library was used. In order to do that, you need to create .NET standard library, change SDK and create links to scripts folders. Final [database project](src/Database/CompanyName.MyMeetings.Database.Build/CompanyName.MyMeetings.Database.Build.csproj) looks as follows:
```xml
netstandard2.0
```
### 3.18 Static code analysis
In order to standardize the appearance of the code and increase its readability, the [StyleCopAnalyzers](https://github.com/DotNetAnalyzers/StyleCopAnalyzers) library was used. This library implements StyleCop rules using the .NET Compiler Platform and is responsible for the static code analysis.
Using this library is trivial - it is just added as a NuGet package to all projects. There are many ways to configure rules, but currently the best way to do this is to edit the [.editorconfig](src/.editorconfig) file. More information can be found at the link above.
**Note! Static code analysis works best when the following points are met:**
1. Each developer has an IDE that respects the rules and helps to follow them
2. The rules are checked during the project build process as part of Continuous Integration
3. The rules are set to *help your system grow*. **Static analysis is not a value in itself.** Some rules may not make complete sense and should be turned off. Other rules may have higher priority. It all depends on the project, company standards and people involved in the project. Be pragmatic.
### 3.19 System Under Test SUT
There is always a need to prepare the entire system in a specific state, e.g. for manual, exploratory, UX / UI tests. The fact that the tests are performed manually does not mean that we cannot automate the preparation phase (Given / Arrange). Thanks to the automation of system state preparation ([System Under Test](https://en.wikipedia.org/wiki/System_under_test)), we are able to recreate exactly the same state in any environment. In addition, such automation can be used later to automate the entire test (e.g. through an [3.13 Integration Tests](#313-integration-tests)).
The implementation of such automation based on the use of NUKE and the test framework is presented below. As in the case of integration testing, we use the public API of modules.

Below is a SUT whose task is to go through the whole process - from setting up a *Meeting Group*, through its *Payment*, adding a new *Meeting* and signing up for it by another user.
```csharp
public class CreateMeeting : TestBase
{
protected override bool PerformDatabaseCleanup => true;
[Test]
public async Task Prepare()
{
await UsersFactory.GivenAdmin(
UserAccessModule,
"testAdmin@mail.com",
"testAdminPass",
"Jane Doe",
"Jane",
"Doe",
"testAdmin@mail.com");
var userId = await UsersFactory.GivenUser(
UserAccessModule,
ConnectionString,
"adamSmith@mail.com",
"adamSmithPass",
"Adam",
"Smith",
"adamSmith@mail.com");
ExecutionContextAccessor.SetUserId(userId);
var meetingGroupId = await MeetingGroupsFactory.GivenMeetingGroup(
MeetingsModule,
AdministrationModule,
ConnectionString,
"Software Craft",
"Group for software craft passionates",
"Warsaw",
"PL");
await TestPriceListManager.AddPriceListItems(PaymentsModule, ConnectionString);
await TestPaymentsManager.BuySubscription(
PaymentsModule,
ExecutionContextAccessor);
SetDate(new DateTime(2022, 7, 1, 10, 0, 0));
var meetingId = await TestMeetingFactory.GivenMeeting(
MeetingsModule,
meetingGroupId,
"Tactical DDD",
new DateTime(2022, 7, 10, 18, 0, 0),
new DateTime(2022, 7, 10, 20, 0, 0),
"Meeting about Tactical DDD patterns",
"Location Name",
"Location Address",
"01-755",
"Warsaw",
50,
0,
null,
null,
0,
null,
new List()
);
var attendeeUserId = await UsersFactory.GivenUser(
UserAccessModule,
ConnectionString,
"rickmorty@mail.com",
"rickmortyPass",
"Rick",
"Morty",
"rickmorty@mail.com");
ExecutionContextAccessor.SetUserId(attendeeUserId);
await TestMeetingGroupManager.JoinToGroup(MeetingsModule, meetingGroupId);
await TestMeetingManager.AddAttendee(MeetingsModule, meetingId, guestsNumber: 1);
}
}
```
You can create this SUT using following *NUKE* target providing connection string and particular test name:
```shell
.\build PrepareSUT --DatabaseConnectionString "connection_string" --SUTTestName CreateMeeting
```
### 3.20 Mutation Testing
#### Description
Mutation testing is an approach to test and evaluate our existing tests. During mutation testing a special framework modifies pieces of our code and runs our tests. These modifications are called *mutations* or *mutants*. If a given *mutation* does not cause a failure of at least once test, it means that the mutant has *survived* so our tests are probably not sufficient.
#### Example
In this repository, the [Stryker.NET](https://stryker-mutator.io/docs/stryker-net/Introduction) framework was used for mutation testing. In the simplest use, after installation, all you need to do is enter the directory of tests that you want to mutate and run the following command:
```shell
dotnet stryker
```
The result of this command is the *mutation report file*. Assuming we want to test the unit tests of the Meetings module, such a [report](docs/mutation-tests-reports/mutation-report.html) has been generated. This is its first page:

Let us analyze one of the places where the mutant survived. This is the *AddNotAttendee* method of the *Meeting* class. This method is used to add a *Member* to the list of people who have decided not to attend the meeting. According to the logic, if the same person previously indicated that he was going to the *Meeting* and later changed his mind, then if there is someone on the *Waiting List*, he should be added to the attendees. Based on requirements, this should be the person who signed up on the *Waiting List* **first** (based on **SignUpDate**).

As you can see, the mutation framework changed our sorting in linq query (from default ascending to descending). However, each test was successful, so it means that mutant survived so we don't have a test that checks the correct sort based on *SignUpDate*.
From the example above, one more important thing can be deduced - **code coverage is insufficient**. In the given example, this code is covered, but our tests do not check the given requirement, therefore our code may have errors. Mutation testing allow to detect such situations. Of course, as with any tool, we should use it wisely, as not every case requires our attention.
## 4. Technology
List of technologies, frameworks and libraries used for implementation:
- [.NET 8.0](https://dotnet.microsoft.com/download) (platform). Note for Visual Studio users: **VS 2019** is required.
- [MS SQL Server Express](https://www.microsoft.com/en-us/sql-server/sql-server-editions-express) (database)
- [Entity Framework Core 8.0](https://docs.microsoft.com/en-us/ef/core/) (ORM Write Model implementation for DDD)
- [Autofac](https://autofac.org/) (Inversion of Control Container)
- [IdentityServer4](http://docs.identityserver.io) (Authentication and Authorization)
- [Serilog](https://serilog.net/) (structured logging)
- [Hellang.Middleware.ProblemDetails](https://github.com/khellang/Middleware/tree/master/src/ProblemDetails) (API Problem Details support)
- [Swashbuckle](https://github.com/domaindrivendev/Swashbuckle) (Swagger automated documentation)
- [Dapper](https://github.com/StackExchange/Dapper) (micro ORM for Read Model)
- [Newtonsoft.Json](https://www.newtonsoft.com/json) (serialization/deserialization to/from JSON)
- [Quartz.NET](https://www.quartz-scheduler.net/) (background processing)
- [FluentValidation](https://fluentvalidation.net/) (data validation)
- [MediatR](https://github.com/jbogard/MediatR) (mediator implementation)
- [Postman](https://www.getpostman.com/) (API tests)
- [NUnit](https://nunit.org/) (Testing framework)
- [NSubstitute](https://nsubstitute.github.io/) (Testing isolation framework)
- [Visual Paradigm Community Edition](https://www.visual-paradigm.com/download/community.jsp) (CASE tool for modeling and documentation)
- [NetArchTest](https://github.com/BenMorris/NetArchTest) (Architecture Unit Tests library)
- [Polly](https://github.com/App-vNext/Polly) (Resilience and transient-fault-handling library)
- [SQL Stream Store](https://github.com/SQLStreamStore) (Library to assist with Event Sourcing)
- [DbUp](https://dbup.readthedocs.io/en/latest/) (Database migrations deployment)
- [SSDT Database Project](https://docs.microsoft.com/en-us/sql/ssdt/how-to-create-a-new-database-project) (Database structure versioning)
- [GitHub Actions](https://docs.github.com/en/actions) (Continuous Integration workflows implementation)
- [StyleCopAnalyzers](https://github.com/DotNetAnalyzers/StyleCopAnalyzers) (Static code analysis library)
- [PlantUML](https://plantuml.com) (UML diagrams from textual description, diagrams as text)
- [C4 Model](https://c4model.com/) (Model for visualising software architecture)
- [C4-PlantUML](https://github.com/plantuml-stdlib/C4-PlantUML) (C4 Model for PlantUML plugin)
- [NUKE](https://nuke.build/) (Build automation system)
- [MSBuild.Sdk.SqlProj](https://github.com/rr-wfm/MSBuild.Sdk.SqlProj/) (Database project compilation)
- [Stryker.NET](https://stryker-mutator.io/docs/stryker-net/Introduction) (Mutation Testing framework)
## 5. How to Run
### Install .NET 8.0 SDK
- [Download](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) and install .NET 8.0 SDK
### Create database
- Download and install MS SQL Server Express or other
- Create an empty database using [CreateDatabase_Windows.sql](src/Database/CompanyName.MyMeetings.Database/Scripts/CreateDatabase_Windows.sql) or [CreateDatabase_Linux.sql](src/Database/CompanyName.MyMeetings.Database/Scripts/CreateDatabase_Linux.sql). Script adds **app** schema which is needed for migrations journal table. Change database file path if needed.
- Run database migrations using **MigrateDatabase** NUKE target by executing the build.sh script present in the root folder:
```shell
.\build MigrateDatabase --DatabaseConnectionString "connection_string"
```
*"connection_string"* - connection string to your database
### Seed database
- Execute [SeedDatabase.sql](src/Database/CompanyName.MyMeetings.Database/Scripts/SeedDatabase.sql) script
- 2 test users will be created - check the script for usernames and passwords
### Configure connection string
Set a database connection string called `MeetingsConnectionString` in the root of the API project's appsettings.json or use [Secrets](https://blogs.msdn.microsoft.com/mihansen/2017/09/10/managing-secrets-in-net-core-2-0-apps/)
Example config setting in appsettings.json for a database called `MyMeetings`:
```json
{
"MeetingsConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MyMeetings;Trusted_Connection=True;"
}
```
### Configure startup in IDE
- Set the Startup Item in your IDE to the API Project, not IIS Express
### Authenticate
- Once it is running you'll need a token to make API calls. This is done via OAuth2 [Resource Owner Password Grant Type](https://www.oauth.com/oauth2-servers/access-tokens/password-grant/). By default IdentityServer is configured with the following:
- `client_id = ro.client`
- `client_secret = secret` **(this is literally the value - not a statement that this value is secret!)**
- `scope = myMeetingsAPI openid profile`
- `grant_type = password`
Include the credentials of a test user created in the [SeedDatabase.sql](src/Database/CompanyName.MyMeetings.Database/Scripts/SeedDatabase.sql) script - for example:
- `username = testMember@mail.com`
- `password = testMemberPass`
**Example HTTP Request for an Access Token:**
```http
POST /connect/token HTTP/1.1
Host: localhost:5000
grant_type=password
&username=testMember@mail.com
&password=testMemberPass
&client_id=ro.client
&client_secret=secret
```
This will fetch an access token for this user to make authorized API requests using the HTTP request header `Authorization: Bearer `
If you use a tool such as Postman to test your API, the token can be fetched and stored within the tool itself and appended to all API calls. Check your tool documentation for instructions.
### Run using Docker Compose
You can run whole application using [docker compose](https://docs.docker.com/compose/) from root folder:
```shell
docker-compose up
```
It will create following services:
- MS SQL Server Database
- Database Migrator
- Application
### Run Integration Tests in Docker
You can run all Integration Tests in Docker (exactly the same process is executed on CI) using **RunAllIntegrationTests** NUKE target:
```shell
.\build RunAllIntegrationTests
```
## 6. Contribution
This project is still under analysis and development. I assume its maintenance for a long time and I would appreciate your contribution to it. Please let me know by creating an Issue or Pull Request.
## 7. Roadmap
List of features/tasks/approaches to add:
| Name | Status | Release date |
|------------------------------------| -------- |--------------|
| Domain Model Unit Tests |Completed | 2019-09-10 |
| Architecture Decision Log update | Completed | 2019-11-09 |
| Integration automated tests | Completed | 2020-02-24 |
| Migration to .NET Core 3.1 |Completed | 2020-03-04 |
| System Integration Testing | Completed | 2020-03-28 |
| More advanced Payments module | Completed | 2020-07-11 |
| Event Sourcing implementation | Completed | 2020-07-11 |
| Database Change Management | Completed | 2020-08-23 |
| Continuous Integration | Completed | 2020-09-01 |
| StyleCop Static Code Analysis | Completed | 2020-09-05 |
| FrontEnd SPA application | Completed | 2020-11-08 |
| Docker support | Completed | 2020-11-26 |
| PlantUML Conceptual Model | Completed | 2021-03-22 |
| C4 Model | Completed | 2021-03-29 |
| Meeting comments feature | Completed | 2021-03-30 |
| NUKE build automation | Completed | 2021-06-15 |
| Database project compilation on CI | Completed | 2021-06-15 |
| System Under Test implementation | Completed | 2022-07-17 |
| Mutation Testing | Completed | 2022-08-23 |
| Migration to .NET 8.0 | Completed | 2023-12-09 |
NOTE: Please don't hesitate to suggest something else or a change to the existing code. All proposals will be considered.
## 8. Authors
Kamil Grzybek
Blog: [https://kamilgrzybek.com](https://kamilgrzybek.com)
Twitter: [https://twitter.com/kamgrzybek](https://twitter.com/kamgrzybek)
LinkedIn: [https://www.linkedin.com/in/kamilgrzybek/](https://www.linkedin.com/in/kamilgrzybek/)
GitHub: [https://github.com/kgrzybek](https://github.com/kgrzybek)
### 8.1 Main contributors
- [Andrei Ganichev](https://github.com/AndreiGanichev)
- [Bela Istok](https://github.com/bistok)
- [Almar Aubel](https://github.com/AlmarAubel)
## 9. License
The project is under [MIT license](https://opensource.org/licenses/MIT).
## 10. Inspirations and Recommendations
### Modular Monolith
- ["Modular Monolith: A Primer"](https://www.kamilgrzybek.com/design/modular-monolith-primer/) Modular Monolith architecture article series, Kamil Grzybek
- ["Modular Monolith Architecture: One to rule them all"](https://www.youtube.com/watch?v=njDSXUWeik0) presentation, Kamil Grzybek
- ["Modular Monoliths"](https://www.youtube.com/watch?v=5OjqD-ow8GE) presentation, Simon Brown
- ["Majestic Modular Monoliths"](https://www.youtube.com/watch?v=BOvxJaklcr0) presentation, Axel Fontaine
- ["Building Better Monoliths – Modulithic Applications with Spring Boot"](https://speakerdeck.com/olivergierke/building-better-monoliths-modulithic-applications-with-spring-boot-cd16e6ec-d334-497d-b9f6-3f92d5db035a) slides, Oliver Drotbohm
- ["MonolithFirst"](https://martinfowler.com/bliki/MonolithFirst.html) article, Martin Fowler
- ["Pattern: Monolithic Architecture"](https://microservices.io/patterns/monolithic.html) pattern description, Chris Richardson
### Domain-Driven Design
- ["Domain-Driven Design: Tackling Complexity in the Heart of Software"](https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215) book, Eric Evans
- ["Implementing Domain-Driven Design"](https://www.amazon.com/Implementing-Domain-Driven-Design-Vaughn-Vernon/dp/0321834577) book, Vaughn Vernon
- ["Domain-Driven Design Distilled"](https://www.amazon.com/dp/0134434420) book, Vaughn Vernon
- ["Patterns, Principles, and Practices of Domain-Driven Design"](https://www.amazon.com/Patterns-Principles-Practices-Domain-Driven-Design-ebook/dp/B00XLYUA0W) book, Scott Millett, Nick Tune
- ["Secure By Design"](https://www.amazon.com/Secure-Design-Daniel-Deogun/dp/1617294357) book, Daniel Deogun, Dan Bergh Johnsson, Daniel Sawano
- ["Hands-On Domain-Driven Design with .NET Core: Tackling complexity in the heart of software by putting DDD principles into practice"](https://www.amazon.com/Hands-Domain-Driven-Design-NET-ebook/dp/B07C5WSR9B) book, Alexey Zimarev
- ["Domain Modeling Made Functional: Tackle Software Complexity with Domain-Driven Design and F#"](https://www.amazon.com/Domain-Modeling-Made-Functional-Domain-Driven-ebook/dp/B07B44BPFB) book, Scott Wlaschin
- ["DDD by examples - library"](https://github.com/ddd-by-examples/library) GH repository, Jakub Pilimon, Bartłomiej Słota
- ["IDDD_Samples"](https://github.com/VaughnVernon/IDDD_Samples) GH repository, Vaughn Vernon
- ["IDDD_Samples_NET"](https://github.com/VaughnVernon/IDDD_Samples_NET) GH repository, Vaughn Vernon
- ["Awesome Domain-Driven Design"](https://github.com/heynickc/awesome-ddd) GH repository, Nick Chamberlain
### Application Architecture
- ["Patterns of Enterprise Application Architecture"](https://martinfowler.com/books/eaa.html) book, Martin Fowler
- ["Dependency Injection Principles, Practices, and Patterns"](https://www.manning.com/books/dependency-injection-principles-practices-patterns) book, Steven van Deursen, Mark Seemann
- ["Clean Architecture: A Craftsman's Guide to Software Structure and Design (Robert C. Martin Series"](https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164) book, Robert C. Martin
- ["The Clean Architecture"](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) article, Robert C. Martin
- ["The Onion Architecture"](https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/) article series, Jeffrey Palermo
- ["Hexagonal/Ports & Adapters Architecture"](https://web.archive.org/web/20180822100852/http://alistair.cockburn.us/Hexagonal+architecture) article, Alistair Cockburn
- ["DDD, Hexagonal, Onion, Clean, CQRS, … How I put it all together"](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/) article, Herberto Graca
### Software Architecture
- ["Software Architecture in Practice (3rd Edition)"](https://www.amazon.com/Software-Architecture-Practice-3rd-Engineering/dp/0321815734) book, Len Bass, Paul Clements, Rick Kazman
- ["Software Architecture for Developers Vol 1 & 2"](https://softwarearchitecturefordevelopers.com/) book, Simon Brown
- ["Just Enough Software Architecture: A Risk-Driven Approach"](https://www.amazon.com/Just-Enough-Software-Architecture-Risk-Driven/dp/0984618104) book, George H. Fairbanks
- ["Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives (2nd Edition)"](https://www.amazon.com/Software-Systems-Architecture-Stakeholders-Perspectives/dp/032171833X/) book, Nick Rozanski, Eóin Woods
- ["Design It!: From Programmer to Software Architect (The Pragmatic Programmers)"](https://www.amazon.com/Design-Programmer-Architect-Pragmatic-Programmers/dp/1680502093) book, Michael Keeling
### System Architecture
- ["Enterprise Integration Patterns : Designing, Building, and Deploying Messaging Solutions"](https://www.enterpriseintegrationpatterns.com/) book and catalogue, Gregor Hohpe, Bobby Woolf
- ["Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems "](https://www.amazon.com/Designing-Data-Intensive-Applications-Reliable-Maintainable/dp/1449373321) book, Martin Kleppman
- ["Building Evolutionary Architectures: Support Constant Change"](https://www.amazon.com/Building-Evolutionary-Architectures-Support-Constant/dp/1491986360) book, Neal Ford
- ["Building Microservices: Designing Fine-Grained Systems"](https://www.amazon.com/Building-Microservices-Designing-Fine-Grained-Systems/dp/1491950358) book, Sam Newman
### Design
- ["Refactoring: Improving the Design of Existing Code"](https://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672) book, Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts
- ["Clean Code: A Handbook of Agile Software Craftsmanship"](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) book, Robert C. Martin
- ["Agile Principles, Patterns, and Practices in C#"](https://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258) book, Robert C. Martin
- ["Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition)"](https://www.amazon.com/Applying-UML-Patterns-Introduction-Object-Oriented/dp/0131489062) book, Craig Larman
- ["Working Effectively with Legacy Code"](https://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052) book, Michael Feathers
- ["Code Complete: A Practical Handbook of Software Construction, Second Edition"](https://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670) book, Steve McConnell
- ["Design Patterns: Elements of Reusable Object-Oriented Software"](https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) book, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
### Craftsmanship
- ["The Clean Coder: A Code of Conduct for Professional Programmers"](https://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073) book, Robert C. Martin
- ["The Pragmatic Programmer: From Journeyman to Master"](https://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X) book, Andrew Hunt
### Testing
- ["The Art of Unit Testing: with examples in C#"](https://www.amazon.com/Art-Unit-Testing-examples/dp/1617290890) book, Roy Osherove
- ["Unit Test Your Architecture with ArchUnit"](https://blogs.oracle.com/javamagazine/unit-test-your-architecture-with-archunit) article, Jonas Havers
- ["Unit Testing Principles, Practices, and Patterns"](https://www.amazon.com/Unit-Testing-Principles-Practices-Patterns/dp/1617296279) book, Vladimir Khorikov
- ["Growing Object-Oriented Software, Guided by Tests"](https://www.amazon.com/Growing-Object-Oriented-Software-Guided-Tests/dp/0321503627) book, Steve Freeman, Nat Pryce
- [Automated Tests](https://www.kamilgrzybek.com/blog/series/automated-tests) article series, Kamil Grzybek
### UML
- ["UML Distilled: A Brief Guide to the Standard Object Modeling Language (3rd Edition)"](https://www.amazon.com/UML-Distilled-Standard-Modeling-Language/dp/0321193687) book, Martin Fowler
### Event Storming
- ["Introducing EventStorming"](https://leanpub.com/introducing_eventstorming) book, Alberto Brandolini
- ["Awesome EventStorming"](https://github.com/mariuszgil/awesome-eventstorming) GH repository, Mariusz Gil
### Event Sourcing
- ["Hands-On Domain-Driven Design with .NET Core: Tackling complexity in the heart of software by putting DDD principles into practice"](https://www.amazon.com/Hands-Domain-Driven-Design-NET-ebook/dp/B07C5WSR9B) book, Alexey Zimarev
- ["Versioning in an Event Sourced System"](https://leanpub.com/esversioning) book, Greg Young
- [Hands-On-Domain-Driven-Design-with-.NET-Core](https://github.com/PacktPublishing/Hands-On-Domain-Driven-Design-with-.NET-Core) GH repository, Alexey Zimarev
- [EventSourcing.NetCore](https://github.com/oskardudycz/EventSourcing.NetCore) GH repository, Oskar Dudycz
================================================
FILE: azure-pipelines.yml
================================================
# ASP.NET Core (.NET Framework)
# Build and test ASP.NET Core projects targeting the full .NET Framework.
# Add steps that publish symbols, save build artifacts, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/dotnet-core
trigger:
- master
pool:
vmImage: 'windows-latest'
variables:
solution: '**/*.sln'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'
steps:
- task: NuGetToolInstaller@1
- task: NuGetCommand@2
inputs:
restoreSolution: '$(solution)'
- task: VSBuild@1
inputs:
solution: '$(solution)'
msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:DesktopBuildPackageLocation="$(build.artifactStagingDirectory)\WebApp.zip" /p:DeployIisAppPath="Default Web Site"'
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
- task: VSTest@2
inputs:
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
================================================
FILE: build/.editorconfig
================================================
[*.cs]
dotnet_style_qualification_for_field = false:warning
dotnet_style_qualification_for_property = false:warning
dotnet_style_qualification_for_method = false:warning
dotnet_style_qualification_for_event = false:warning
dotnet_style_require_accessibility_modifiers = never:warning
csharp_style_expression_bodied_methods = true:silent
csharp_style_expression_bodied_properties = true:warning
csharp_style_expression_bodied_indexers = true:warning
csharp_style_expression_bodied_accessors = true:warning
================================================
FILE: build/Build.cs
================================================
using Nuke.Common;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tools.DotNet;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
partial class Build : NukeBuild
{
/// Support plugins are available for:
/// - JetBrains ReSharper https://nuke.build/resharper
/// - JetBrains Rider https://nuke.build/rider
/// - Microsoft VisualStudio https://nuke.build/visualstudio
/// - Microsoft VSCode https://nuke.build/vscode
public static int Main () => Execute(x => x.Compile);
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Solution] readonly Solution Solution;
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
AbsolutePath.Create(WorkingDirectory).CreateOrCleanDirectory();
});
Target Restore => _ => _
.Executes(() =>
{
DotNetRestore(s => s
.SetProjectFile(Solution));
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
DotNetBuild(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.EnableNoRestore());
});
Target UnitTests => _ => _
.DependsOn(Compile)
.Executes(() =>
{
DotNetTest(s => s
.SetProjectFile(Solution)
.SetFilter("UnitTests")
.SetConfiguration(Configuration)
.EnableNoRestore()
.EnableNoBuild());
});
Target ArchitectureTests => _ => _
.DependsOn(UnitTests)
.Executes(() =>
{
DotNetTest(s => s
.SetProjectFile(Solution)
.SetFilter("ArchTests")
.SetConfiguration(Configuration)
.EnableNoRestore()
.EnableNoBuild());
});
Target BuildAndUnitTests => _ => _
.Triggers(ArchitectureTests)
.Executes(() =>
{
});
}
================================================
FILE: build/BuildIntegrationTests.cs
================================================
using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.IO;
using Nuke.Common.Tools.Docker;
using Nuke.Common.Tools.DotNet;
using Utils;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
public partial class Build
{
static AbsolutePath WorkingDirectory => RootDirectory / ".nuke-working-directory";
static AbsolutePath OutputDirectory => WorkingDirectory / "output";
static AbsolutePath OutputDbUbMigratorBuildDirectory => OutputDirectory / "dbUpMigrator";
static AbsolutePath InputFilesDirectory => WorkingDirectory / "input-files";
static AbsolutePath DatabaseDirectory =>
RootDirectory / "src" / "Database" / "CompanyName.MyMeetings.Database" / "Scripts";
const string CreateDatabaseScriptName = "CreateDatabase_Linux.sql";
const string InputFilesDirectoryName = "input-files";
Target PrepareInputFiles => _ => _
.DependsOn(Clean)
.Executes(() =>
{
string createDatabaseFile = DatabaseDirectory / CreateDatabaseScriptName;
string createDatabaseFileTarget = InputFilesDirectory / CreateDatabaseScriptName;
CopyFile(createDatabaseFile, createDatabaseFileTarget, FileExistsPolicy.Overwrite);
});
const string SqlServerPassword = "123qwe!@#QWE";
const string SqlServerUser = "sa";
const string SqlServerPort = "1401";
Target PrepareSqlServer => _ => _
.DependsOn(PrepareInputFiles)
.Executes(() =>
{
DockerTasks.DockerRun(s => s
.EnableRm()
.SetName("sql-server-db")
.SetImage("mcr.microsoft.com/mssql/server")
.SetEnv(
$"SA_PASSWORD={SqlServerPassword}",
"ACCEPT_EULA=Y",
"MSSQL_PID=Express")
.SetPublish($"{SqlServerPort}:1433")
.SetMount($"type=bind,source=\"{InputFilesDirectory}\",target=/{InputFilesDirectoryName},readonly")
.EnableDetach());
SqlReadinessChecker.WaitForSqlSever(
$"Server=127.0.0.1,{SqlServerPort};Database=master;User={SqlServerUser};Password={SqlServerPassword};Encrypt=False;");
});
Target CreateDatabase => _ => _
.DependsOn(PrepareSqlServer)
.Executes(() =>
{
DockerTasks.DockerExec(s => s
.EnableInteractive()
.SetContainer("sql-server-db")
.SetCommand("/bin/sh")
.SetArgs("-c", $"./opt/mssql-tools/bin/sqlcmd -d master -i ./{InputFilesDirectoryName}/{CreateDatabaseScriptName} -U {SqlServerUser} -P {SqlServerPassword}"));
});
Target CompileDbUpMigratorForIntegrationTests => _ => _
.DependsOn(CreateDatabase)
.Executes(() =>
{
var dbUpMigratorProject = Solution.GetAllProjects("DatabaseMigrator").First();
DotNetBuild(s => s
.SetProjectFile(dbUpMigratorProject)
.SetConfiguration(Configuration)
.SetOutputDirectory(OutputDbUbMigratorBuildDirectory)
);
});
AbsolutePath DbUpMigratorPath => OutputDbUbMigratorBuildDirectory / "DatabaseMigrator.dll";
readonly string MyMeetingsDatabaseConnectionString = $"Server=127.0.0.1,{SqlServerPort};Database=MyMeetings;User={SqlServerUser};Password={SqlServerPassword};Encrypt=False;";
Target RunDatabaseMigrations => _ => _
.DependsOn(CompileDbUpMigratorForIntegrationTests)
.Executes(() =>
{
AbsolutePath migrationsPath = DatabaseDirectory / "Migrations";
DotNet($"{DbUpMigratorPath} {MyMeetingsDatabaseConnectionString} {migrationsPath}");
});
const string MeetingsModuleIntegrationTestsAssemblyName = "CompanyName.MyMeetings.Modules.Meetings.IntegrationTests";
Target BuildMeetingsModuleIntegrationTests => _ => _
.DependsOn(RunDatabaseMigrations)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(MeetingsModuleIntegrationTestsAssemblyName).First();
DotNetBuild(s => s
.SetProjectFile(integrationTest)
.DisableNoRestore());
});
const string MyMeetingsDatabaseEnvName = "ASPNETCORE_MyMeetings_IntegrationTests_ConnectionString";
Target RunMeetingsModuleIntegrationTests => _ => _
.DependsOn(BuildMeetingsModuleIntegrationTests)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(MeetingsModuleIntegrationTestsAssemblyName).First();
Environment.SetEnvironmentVariable(
MyMeetingsDatabaseEnvName,
MyMeetingsDatabaseConnectionString);
DotNetTest(s => s
.EnableNoBuild()
.SetProjectFile(integrationTest));
});
const string AdministrationModuleIntegrationTestsAssemblyName = "CompanyName.MyMeetings.Modules.Administration.IntegrationTests";
Target BuildAdministrationModuleIntegrationTests => _ => _
.DependsOn(RunDatabaseMigrations)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(AdministrationModuleIntegrationTestsAssemblyName).First();
DotNetBuild(s => s
.SetProjectFile(integrationTest)
.DisableNoRestore());
});
Target RunAdministrationModuleIntegrationTests => _ => _
.DependsOn(BuildAdministrationModuleIntegrationTests)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(AdministrationModuleIntegrationTestsAssemblyName).First();
Environment.SetEnvironmentVariable(
MyMeetingsDatabaseEnvName,
MyMeetingsDatabaseConnectionString);
DotNetTest(s => s
.EnableNoBuild()
.SetProjectFile(integrationTest));
});
const string UserAccessModuleIntegrationTestsAssemblyName = "CompanyNames.MyMeetings.Modules.UserAccess.IntegrationTests";
Target BuildUserAccessModuleIntegrationTests => _ => _
.DependsOn(RunDatabaseMigrations)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(UserAccessModuleIntegrationTestsAssemblyName).First();
DotNetBuild(s => s
.SetProjectFile(integrationTest)
.DisableNoRestore());
});
Target RunUserAccessModuleIntegrationTests => _ => _
.DependsOn(BuildUserAccessModuleIntegrationTests)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(UserAccessModuleIntegrationTestsAssemblyName).First();
Environment.SetEnvironmentVariable(
MyMeetingsDatabaseEnvName,
MyMeetingsDatabaseConnectionString);
DotNetTest(s => s
.EnableNoBuild()
.SetProjectFile(integrationTest));
});
const string PaymentsModuleIntegrationTestsAssemblyName = "CompanyName.MyMeetings.Modules.Payments.IntegrationTests";
Target BuildPaymentsModuleIntegrationTests => _ => _
.DependsOn(RunDatabaseMigrations)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(PaymentsModuleIntegrationTestsAssemblyName).First();
DotNetBuild(s => s
.SetProjectFile(integrationTest)
.DisableNoRestore());
});
Target RunPaymentsModuleIntegrationTests => _ => _
.DependsOn(BuildPaymentsModuleIntegrationTests)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(PaymentsModuleIntegrationTestsAssemblyName).First();
Environment.SetEnvironmentVariable(
MyMeetingsDatabaseEnvName,
MyMeetingsDatabaseConnectionString);
DotNetTest(s => s
.EnableNoBuild()
.SetProjectFile(integrationTest));
});
const string SystemIntegrationTestsAssemblyName = "CompanyName.MyMeetings.IntegrationTests";
Target BuildSystemIntegrationTests => _ => _
.DependsOn(RunDatabaseMigrations)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(SystemIntegrationTestsAssemblyName).First();
DotNetBuild(s => s
.SetProjectFile(integrationTest)
.DisableNoRestore());
});
Target RunSystemIntegrationTests => _ => _
.DependsOn(BuildSystemIntegrationTests)
.Executes(() =>
{
var integrationTest = Solution.GetAllProjects(SystemIntegrationTestsAssemblyName).First();
Environment.SetEnvironmentVariable(
MyMeetingsDatabaseEnvName,
MyMeetingsDatabaseConnectionString);
DotNetTest(s => s
.EnableNoBuild()
.SetProjectFile(integrationTest));
});
Target RunAllIntegrationTests => _ => _
.DependsOn(
RunAdministrationModuleIntegrationTests,
RunMeetingsModuleIntegrationTests,
RunPaymentsModuleIntegrationTests,
RunUserAccessModuleIntegrationTests,
RunSystemIntegrationTests)
.Executes(() =>
{
});
}
================================================
FILE: build/Configuration.cs
================================================
using System.ComponentModel;
using Nuke.Common.Tooling;
[TypeConverter(typeof(TypeConverter))]
public class Configuration : Enumeration
{
public static Configuration Debug = new Configuration { Value = nameof(Debug) };
public static Configuration Release = new Configuration { Value = nameof(Release) };
public static implicit operator string(Configuration configuration)
{
return configuration.Value;
}
}
================================================
FILE: build/Database.cs
================================================
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.DotNet;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
public partial class Build
{
Target CompileDbUpMigrator => _ => _
.Executes(() =>
{
var dbUpMigratorProject = Solution.GetAllProjects("DatabaseMigrator").First();
DotNetBuild(s => s
.SetProjectFile(dbUpMigratorProject)
.SetConfiguration(Configuration)
.SetOutputDirectory(OutputDbUbMigratorBuildDirectory)
);
});
[Parameter("Modular Monolith database connection string")] readonly string DatabaseConnectionString;
Target MigrateDatabase => _ => _
.Requires(() => DatabaseConnectionString != null)
.DependsOn(CompileDbUpMigrator)
.Executes(() =>
{
var migrationsPath = DatabaseDirectory / "Migrations";
DotNet($"{DbUpMigratorPath} {DatabaseConnectionString} {migrationsPath}");
});
}
================================================
FILE: build/Directory.Build.props
================================================
================================================
FILE: build/Directory.Build.targets
================================================
================================================
FILE: build/SUTCreator.cs
================================================
using System;
using System.Collections.Generic;
using Nuke.Common;
using Nuke.Common.Tools.DotNet;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
public partial class Build
{
[Parameter("SUT creator test name to execute")] readonly string SUTTestName;
readonly IDictionary TestCasesMap = new Dictionary
{
{"CleanDatabase", "CompanyName.MyMeetings.SUT.TestCases.CleanDatabaseTestCase.Prepare"},
{"OnlyAdmin", "CompanyName.MyMeetings.SUT.TestCases.OnlyAdminTestCase.Prepare"},
{"CreateMeeting", "CompanyName.MyMeetings.SUT.TestCases.CreateMeeting.Prepare"}
};
Target PrepareSUT => _ => _
.Requires(() => SUTTestName != null)
.Requires(() => DatabaseConnectionString != null)
.Executes(() =>
{
Environment.SetEnvironmentVariable(
"MyMeetings_SUTDatabaseConnectionString",
DatabaseConnectionString,
EnvironmentVariableTarget.Process);
var sutTestProject = Solution.GetProject("CompanyName.MyMeetings.SUT");
var fullyQualifiedName = TestCasesMap[SUTTestName];
DotNetTest(s => s
.SetProjectFile(sutTestProject)
.SetFilter($"FullyQualifiedName={fullyQualifiedName}"));
});
}
================================================
FILE: build/Utils/SqlReadinessChecker.cs
================================================
using System;
using System.Threading;
using Dapper;
using System.Data.SqlClient;
namespace Utils
{
public static class SqlReadinessChecker
{
public static void WaitForSqlSever(string connectionString)
{
using var connection = new SqlConnection(connectionString);
const int maxTryCounts = 30;
var tryCounts = 0;
while (true)
{
tryCounts++;
try
{
connection.QuerySingle("SELECT @@Version");
Serilog.Log.Information("Sql Server started");
break;
}
catch
{
Serilog.Log.Information("Sql Server not ready");
if (tryCounts > maxTryCounts)
{
throw new Exception("Sql Server cannot start.");
}
}
Thread.Sleep(2000);
}
}
}
}
================================================
FILE: build/_build.csproj
================================================
Exe
net8.0
CS0649;CS0169
..
..
1
true
================================================
FILE: build/_build.csproj.DotSettings
================================================
DO_NOT_SHOW
DO_NOT_SHOW
DO_NOT_SHOW
DO_NOT_SHOW
Implicit
Implicit
ExpressionBody
0
NEXT_LINE
True
False
120
IF_OWNER_IS_SINGLE_LINE
WRAP_IF_LONG
False
<Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" />
<Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" />
True
True
True
True
True
True
True
True
True
================================================
FILE: build.cmd
================================================
:; set -eo pipefail
:; SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)
:; ${SCRIPT_DIR}/build.sh "$@"
:; exit $?
@ECHO OFF
powershell -ExecutionPolicy ByPass -NoProfile -File "%~dp0build.ps1" %*
================================================
FILE: build.ps1
================================================
[CmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
[string[]]$BuildArguments
)
Write-Output "PowerShell $($PSVersionTable.PSEdition) version $($PSVersionTable.PSVersion)"
Set-StrictMode -Version 2.0; $ErrorActionPreference = "Stop"; $ConfirmPreference = "None"; trap { Write-Error $_ -ErrorAction Continue; exit 1 }
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
###########################################################################
# CONFIGURATION
###########################################################################
$BuildProjectFile = "$PSScriptRoot\build\_build.csproj"
$TempDirectory = "$PSScriptRoot\\.nuke\temp"
$DotNetGlobalFile = "$PSScriptRoot\\global.json"
$DotNetInstallUrl = "https://dot.net/v1/dotnet-install.ps1"
$DotNetChannel = "Current"
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = 1
$env:DOTNET_CLI_TELEMETRY_OPTOUT = 1
$env:DOTNET_MULTILEVEL_LOOKUP = 0
###########################################################################
# EXECUTION
###########################################################################
function ExecSafe([scriptblock] $cmd) {
& $cmd
if ($LASTEXITCODE) { exit $LASTEXITCODE }
}
# If dotnet CLI is installed globally and it matches requested version, use for execution
if ($null -ne (Get-Command "dotnet" -ErrorAction SilentlyContinue) -and `
$(dotnet --version) -and $LASTEXITCODE -eq 0) {
$env:DOTNET_EXE = (Get-Command "dotnet").Path
}
else {
# Download install script
$DotNetInstallFile = "$TempDirectory\dotnet-install.ps1"
New-Item -ItemType Directory -Path $TempDirectory -Force | Out-Null
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
(New-Object System.Net.WebClient).DownloadFile($DotNetInstallUrl, $DotNetInstallFile)
# If global.json exists, load expected version
if (Test-Path $DotNetGlobalFile) {
$DotNetGlobal = $(Get-Content $DotNetGlobalFile | Out-String | ConvertFrom-Json)
if ($DotNetGlobal.PSObject.Properties["sdk"] -and $DotNetGlobal.sdk.PSObject.Properties["version"]) {
$DotNetVersion = $DotNetGlobal.sdk.version
}
}
# Install by channel or version
$DotNetDirectory = "$TempDirectory\dotnet-win"
if (!(Test-Path variable:DotNetVersion)) {
ExecSafe { & $DotNetInstallFile -InstallDir $DotNetDirectory -Channel $DotNetChannel -NoPath }
} else {
ExecSafe { & $DotNetInstallFile -InstallDir $DotNetDirectory -Version $DotNetVersion -NoPath }
}
$env:DOTNET_EXE = "$DotNetDirectory\dotnet.exe"
}
Write-Output "Microsoft (R) .NET SDK version $(& $env:DOTNET_EXE --version)"
ExecSafe { & $env:DOTNET_EXE build $BuildProjectFile /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet }
ExecSafe { & $env:DOTNET_EXE run --project $BuildProjectFile --no-build -- $BuildArguments }
================================================
FILE: build.sh
================================================
#!/usr/bin/env bash
bash --version 2>&1 | head -n 1
set -eo pipefail
SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)
###########################################################################
# CONFIGURATION
###########################################################################
BUILD_PROJECT_FILE="$SCRIPT_DIR/build/_build.csproj"
TEMP_DIRECTORY="$SCRIPT_DIR//.nuke/temp"
DOTNET_GLOBAL_FILE="$SCRIPT_DIR//global.json"
DOTNET_INSTALL_URL="https://dot.net/v1/dotnet-install.sh"
DOTNET_CHANNEL="Current"
export DOTNET_CLI_TELEMETRY_OPTOUT=1
export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
export DOTNET_MULTILEVEL_LOOKUP=0
###########################################################################
# EXECUTION
###########################################################################
function FirstJsonValue {
perl -nle 'print $1 if m{"'"$1"'": "([^"]+)",?}' <<< "${@:2}"
}
# If dotnet CLI is installed globally and it matches requested version, use for execution
if [ -x "$(command -v dotnet)" ] && dotnet --version &>/dev/null; then
export DOTNET_EXE="$(command -v dotnet)"
else
# Download install script
DOTNET_INSTALL_FILE="$TEMP_DIRECTORY/dotnet-install.sh"
mkdir -p "$TEMP_DIRECTORY"
curl -Lsfo "$DOTNET_INSTALL_FILE" "$DOTNET_INSTALL_URL"
chmod +x "$DOTNET_INSTALL_FILE"
# If global.json exists, load expected version
if [[ -f "$DOTNET_GLOBAL_FILE" ]]; then
DOTNET_VERSION=$(FirstJsonValue "version" "$(cat "$DOTNET_GLOBAL_FILE")")
if [[ "$DOTNET_VERSION" == "" ]]; then
unset DOTNET_VERSION
fi
fi
# Install by channel or version
DOTNET_DIRECTORY="$TEMP_DIRECTORY/dotnet-unix"
if [[ -z ${DOTNET_VERSION+x} ]]; then
"$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --channel "$DOTNET_CHANNEL" --no-path
else
"$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --version "$DOTNET_VERSION" --no-path
fi
export DOTNET_EXE="$DOTNET_DIRECTORY/dotnet"
fi
echo "Microsoft (R) .NET Core SDK version $("$DOTNET_EXE" --version)"
"$DOTNET_EXE" build "$BUILD_PROJECT_FILE" /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet
"$DOTNET_EXE" run --project "$BUILD_PROJECT_FILE" --no-build -- "$@"
================================================
FILE: docker-compose.yml
================================================
version: '3.4'
services:
backend:
container_name: mymeetings_backend
build:
context: ./src/
ports:
- "5000:8080"
networks:
- starfish-crm-network
environment:
- Meetings_MeetingsConnectionString=Server=mymeetingsdb,1433;Database=MyMeetings;User=sa;Password=Test@12345;Encrypt=False;
depends_on:
- migrator
restart: on-failure
mymeetingsdb:
build: ./src/Database/
platform: linux/amd64
ports:
- 1445:1433
networks:
- starfish-crm-network
migrator:
container_name: mymeetings_db_migrator
build:
context: ./src/
dockerfile: ./Database/Dockerfile_DatabaseMigrator
networks:
- starfish-crm-network
environment:
- ASPNETCORE_MyMeetings_IntegrationTests_ConnectionString=Server=mymeetingsdb,1433;Database=MyMeetings;User=sa;Password=Test@12345;Encrypt=False;
command:
[
"./wait-for-it.sh",
"mymeetingsdb:1433",
"--timeout=60",
"--",
"/bin/bash",
"/entrypoint_DatabaseMigrator.sh"
]
restart: on-failure
networks:
starfish-crm-network:
================================================
FILE: docs/C4/c1_system_context.puml
================================================
@startuml C1 System Context
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Context.puml
Person(memberPerson, "Member", "Organizer of meeting groups, meetings, member of group, meeting attendee")
Person(adminPerson, "Administrator", "Administrator of the system")
System(myMeetingsSystem, "My Meetings")
System_Ext(emailSystem, "Email Service")
System_Ext(paymentGatewaySystem, "Payment Gateway")
Rel(memberPerson, myMeetingsSystem, "Organize meeting groups and participate in meetings")
Rel(adminPerson, myMeetingsSystem, "Manage members, meeting groups, meetings")
Rel(myMeetingsSystem, emailSystem, "Request email send")
Rel(emailSystem, memberPerson, "Send email")
Rel(emailSystem, adminPerson, "Send email")
Rel(myMeetingsSystem, paymentGatewaySystem, "Delegate the payment")
Rel(paymentGatewaySystem, myMeetingsSystem , "Return info about payment")
Rel(memberPerson, paymentGatewaySystem , "Pay in")
LAYOUT_WITH_LEGEND()
@enduml
================================================
FILE: docs/C4/c2_container.puml
================================================
@startuml C2 Containers
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml
Person(memberPerson, "Member", "Organizer of meeting groups, meetings, member of group, meeting attendee")
Person(adminPerson, "Administrator", "Administrator of the system")
System_Boundary(c1, "My Meetings System") {
Container(spa, "SPA", "ReactJS", "GUI for the application")
Container(api, "My Meetings API", ".NET Core", "Backend")
ContainerDb(database, "Database", "Microsoft SQL", "Data about meeting groups, members, meetings etc", "msql_server")
}
System_Ext(emailSystem, "Email System", "3rd party SMTP server")
System_Ext(paymentGateway, "Payment Gateway", "3rd party payment service")
Rel(memberPerson, spa, "Uses", "HTTP")
Rel(adminPerson, spa, "Uses", "HTTP")
Rel(spa, api, "Uses", "HTTP")
Rel_R(api, database, "Reads/Writes", "SQL")
Rel_L(api, emailSystem, "Sends email using", "SMTP")
Rel_D(api, paymentGateway, "Delegate the payment", "HTTP")
Rel(memberPerson, paymentGateway, "Make payment via", "HTTP")
LAYOUT_WITH_LEGEND()
@enduml
================================================
FILE: docs/C4/c3_components.puml
================================================
@startuml C3 Components
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Component.puml
System_Boundary(c1, "My Meetings System") {
Container(spa, "SPA", "ReactJS", "GUI for the application")
Boundary(myMeetingsApi, "My Meetings API") {
Component(api, "API", ".NET Core API")
Component(meetingsModule, "Meetings", ".NET Libraries")
Component(administrationModule, "Administration", ".NET Libraries")
Component(userAccessModule, "User Access", ".NET Libraries")
Component(paymentsModule, "Payments", ".NET Libraries")
Component(registrationsModule, "Registrations", ".NET Libraries")
ComponentQueue(eventsBus, "Events Bus", "In memory")
Boundary(database, "Database") {
ComponentDb(meetingsModuleData, "Meetings data", "schema")
ComponentDb(administrationData, "Administration data", "schema")
ComponentDb(userAccessData, "User Access data", "schema")
ComponentDb(paymentsData, "Payments data", "schema")
ComponentDb(registrationsData, "Registrations data", "schema")
}
}
}
Rel(spa, api, "Uses", "HTTP")
Rel(api, meetingsModule, "Uses")
Rel(api, administrationModule, "Uses")
Rel(api, userAccessModule, "Uses")
Rel(api, paymentsModule, "Uses")
Rel(api, registrationsModule, "Uses")
Rel(meetingsModule, eventsBus, "Publishes event to / subscribes")
Rel(administrationModule, eventsBus, "Publishes event to / subscribes")
Rel(userAccessModule, eventsBus, "Publishes event to / subscribes")
Rel(paymentsModule, eventsBus, "Publishes event to / subscribes")
Rel(registrationsModule, eventsBus, "Publishes event to / subscribes")
Rel(meetingsModule, meetingsModuleData, "Store / retrieve")
Rel(administrationModule, administrationData, "Store / retrieve")
Rel(userAccessModule, userAccessData, "Store / retrieve")
Rel(paymentsModule, paymentsData, "Store / retrieve")
Rel(registrationsModule, registrationsData, "Store / retrieve")
Rel_R(registrationsModule, userAccessModule, "Uses")
LAYOUT_WITH_LEGEND()
@enduml
================================================
FILE: docs/C4/c3_components_module.puml
================================================
@startuml C3 Components Module (zoom-in)
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Component.puml
AddComponentTag("meetings", $bgColor="#4ce065")
AddComponentTag("administration", $bgColor="#e3b868")
AddComponentTag("eventsBus", $bgColor="#29118a", $fontColor="#ffffff")
System_Boundary(c1, "My Meetings System") {
Boundary(myMeetingsApi, "My Meetings API") {
Component(api, "API", ".NET Core API")
Boundary(meetingsModule, "Meetings Module") {
Component(meetingsInfrastructure, "Meetings.Infrastructure", ".NET Library", $tags="meetings")
Component(meetingsApplication, "Meetings.Application", ".NET Library", $tags="meetings")
Component(meetingsDomain, "Meetings.Domain", ".NET Library", $tags="meetings")
Component(meetingsIntegrationEvents, "Meetings.IntegrationEvents", ".NET Library", $tags="meetings")
ComponentDb(meetingsData, "Meetings data", "schema", $tags="meetings")
}
Boundary(administrationModule, "Administration Module") {
Component(administrationInfrastructure, "Administration.Infrastructure", ".NET Library", $tags="administration")
Component(administrationApplication, "Administration.Application", ".NET Library", $tags="administration")
Component(administrationDomain, "Administration.Domain", ".NET Library", $tags="administration")
Component(administrationIntegrationEvents, "Administration.IntegrationEvents", ".NET Library", $tags="administration")
ComponentDb(administrationData, "Administration data", "schema", $tags="administration")
}
ComponentQueue(eventsBus, "Events Bus", "In memory", $tags="eventsBus")
}
}
Rel(api, meetingsInfrastructure, "Uses")
Rel(api, meetingsApplication, "Uses")
Rel(meetingsInfrastructure, meetingsApplication, "Uses")
Rel(meetingsInfrastructure, meetingsDomain, "Uses")
Rel(meetingsApplication, meetingsDomain, "Uses")
Rel(meetingsApplication, meetingsIntegrationEvents, "Uses")
Rel(meetingsInfrastructure, meetingsData, "Uses")
Rel(meetingsInfrastructure, eventsBus, "Uses")
Rel(api, administrationInfrastructure, "Uses")
Rel(api, administrationApplication, "Uses")
Rel(administrationInfrastructure, administrationApplication, "Uses")
Rel(administrationInfrastructure, administrationDomain, "Uses")
Rel(administrationApplication, administrationDomain, "Uses")
Rel(administrationApplication, administrationIntegrationEvents, "Uses")
Rel(administrationInfrastructure, administrationData, "Uses")
Rel(administrationInfrastructure, eventsBus, "Uses")
Rel(administrationApplication, meetingsIntegrationEvents, "Uses")
Rel(meetingsApplication, administrationIntegrationEvents, "Uses")
@enduml
================================================
FILE: docs/C4/c4_class.puml
================================================
@startuml C4 Code
package "Meeting Groups Aggregate" <> {
class "MeetingGroupId" << VO >> {
}
class "MeetingGroup" << Entity, AR >> {
-string: _description
-DateTime: _createDate
-DateTime: _paymentDateTo
{static} MeetingGroup CreateBasedOnProposal()
Meeting CreateMeeting(..)
void SetExpirationDate(DateTime dateTo)
void JoinToGroupMember(MemberId memberId)
void LeaveGroup(MemberId memberId)
void EditGeneralAttributes(...)
bool IsMemberOfGroup(MemberId attendeeId)
bool IsOrganizer(MemberId memberId)
}
class "MeetingGroupLocation" << VO >> {
string City
string CountryCode
{static} MeetingGroupLocation Create(...)
}
class "MeetingGroupMember" << Entity >> {
~DateTime JoinedDate
-bool _isActive
-DateTime? _leaveDate
{static} MeetingGroupMember CreateNew(...)
void Leave()
~bool IsMember(MemberId memberId)
~bool IsOrganizer(MemberId memberId)
}
class "MemberId" << VO >> {
}
class "MeetingGroupMemberRole" << VO >> {
string Value
}
}
class "Member" << Entity, AR >> {
}
"MeetingGroup" *-- "MeetingGroupId" : of
"MeetingGroup" *-- "MeetingGroupLocation" : for
"MeetingGroup" "1" *-- "0..*" "MeetingGroupMember" : member of
"MeetingGroupMember" *-- "MemberId" : assigned to
"MeetingGroupMemberRole" --* "MeetingGroupMember" : is assigned to
"Member" o-- "MemberId" : of
@enduml
================================================
FILE: docs/PlantUML/Commenting_Conceptual_Model.puml
================================================
@startuml
object "Meeting" as Meeting
object "Member" as Member
object "Meeting Commenting Configuration" as MeetingCommentingConfiguration
object "Meeting Comment" as MeetingComment
object "Meeting Member Comment Like" as MeetingMemberCommentLike
Meeting "1"-->"0..*" MeetingComment : has
MeetingCommentingConfiguration "1"-->"1" Meeting : enables\ncommenting\nof
MeetingComment "1"-->"0..*" MeetingMemberCommentLike : has
MeetingComment "1"-->"0..*" MeetingComment : is reply to
Member --> Meeting : comments
Member --> MeetingComment : replies to,\nlikes
Member --> MeetingCommentingConfiguration : configures
@enduml
================================================
FILE: docs/PlantUML/Conceptual_Model.puml
================================================
@startuml
scale max 2000 width
package "User Access" #f3e8f8 {
object Permission
object "User Role" as UserRole
object User
object "User Registration" as UserRegistration
enum "User Registration Status" as UserRegistrationStatus
{
WaitingForConfirmation
Confirmed
Expired
}
User "1"-->"0..*" UserRole : has
User --> UserRegistration : created for
UserRole "1..*"-->"1..*" Permission : has
UserRegistration --> UserRegistrationStatus : is in
}
package "Administration" #ffeddb {
object Administrator
object "Meeting Group Proposal" as Administration.MeetingGroupProposal
enum "Meeting Group Proposal Decision" as MeetingGroupProposalDecision
{
Accept
Reject
}
enum "Meeting Group Proposal Status" as Administration.MeetingGroupProposalDecisionStatus
{
Accepted
InVerification
Rejected
}
Administrator "1"-->"0..*" MeetingGroupProposalDecision : makes
MeetingGroupProposalDecision --> Administration.MeetingGroupProposal : for
Administration.MeetingGroupProposal --> Administration.MeetingGroupProposalDecisionStatus: is in
Administrator --> User : is a
}
package "Meetings" #e4f7e4 {
object "Meeting" as Meeting
object "Member" as Member
object "Meeting Group Proposal" as Meeting.MeetingGroupProposal
object "Meeting Attendee" as MeetingAttendee
object "Meeting Group" as MeetingGroup
object "Meeting Not Attendee" as MeetingNotAttendee
object "Meeting Waitlist Member" as MeetingWaitlistMember
object "Meeting Location" as MeetingLocation
object "Member Subscription" as Meeting.MemberSubscription
enum "Meeting Group Proposal Status" as Meeting.MeetingGroupProposalStatus
{
InVerification
Accepted
Rejected
}
Member --> Meeting.MeetingGroupProposal : proposes
Member "1"-->"0..*" MeetingAttendee : is a
Member "1"-->"0..*" MeetingNotAttendee : is a
Member "1"-->"0..*" MeetingWaitlistMember : is a
Member --> Meeting.MemberSubscription : has
Meeting "1"-->"1..*" MeetingAttendee : attendees
Meeting "1"-->"0..*" MeetingNotAttendee : not attendees
Meeting --> MeetingLocation : has
Meeting.MeetingGroupProposal --> Meeting.MeetingGroupProposalStatus : is in
MeetingGroup "1"-->"0..*" Meetings : organizes
MeetingGroup "0..1"-->"1" Meeting.MeetingGroupProposal : created after acceptance of
MeetingWaitlistMember "0..*"-->"1" Meeting : waits for place for
Meeting.MemberSubscription --> MeetingGroup : covers
Member --> User: is a
Meeting.MeetingGroupProposal --> Administration.MeetingGroupProposal : sent to verification
}
package "Payments" #ffc1c1 {
object "Payer" as Payer
object "Meeting Fee" as MeetingFee
object "Meeting Fee Payment" as MeetingFeePayment
object "Subscription" as Payments.Subscription
object "Subscription Payment" as SubscriptionPayment
object "Subscription Renewal Payment" as SubscriptionRenewalPayment
object "Price List" as PriceList
object "Price List Item" as PriceListItem
enum "Subscription Status" as SubscriptionStatus
{
Active
Expired
}
enum "Subscription Payment Status" as SubscriptionPaymentStatus
{
WaitingForPayment
Paid
Expired
}
enum "Subscription Renewal Payment Status" as SubscriptionRenewalPaymentStatus
{
WaitingForPayment
Paid
Expired
}
enum "Meeting Fee Payment Status" as MeetingFeePaymentStatus
{
WaitingForPayment
Paid
Expired
}
enum "Price List Item Category" as PriceListItemCategory
{
New
Renewal
}
enum "Subscription Period" as SubscriptionPeriod
{
Month
HalfYear
}
Payer "1"-->"0..*" MeetingFee : pays for
Payer "1"--> "0..*" Payments.Subscription : buys
MeetingFeePayment "0..*"-->"1" MeetingFee : for
MeetingFeePayment --> MeetingFeePaymentStatus : is in
Payments.Subscription "1"-->"0..*" SubscriptionRenewalPayment: extended by
Payments.Subscription --> SubscriptionStatus : is in
Payments.Subscription --> SubscriptionPeriod : is for
SubscriptionPayment "1..*"-->"1" Payments.Subscription : is for
SubscriptionPayment --> SubscriptionPaymentStatus : is in
SubscriptionPayment --> SubscriptionPeriod : is for
SubscriptionRenewalPayment --> SubscriptionRenewalPaymentStatus: is in
SubscriptionRenewalPayment --> SubscriptionPeriod : is for
PriceListItem --> SubscriptionPeriod : is for
PriceListItem "0..*"-->"1" Country: is for
PriceListItem --> PriceListItemCategory : is for
PriceList "1"-->"1..*" PriceListItem : contains
Payer --> Member: is a
Payer --> User: is a
Payments.Subscription -- Meeting.MemberSubscription
}
@enduml
================================================
FILE: docs/architecture-decision-log/0001-record-architecture-decisions.md
================================================
# 1. Record architecture decisions
Date: 2019-10-28
## Status
Accepted
## Context
As the project is an example of a more advanced monolith architecture, it is necessary to save all architectural decisions in one place.
## Decision
For all architectural decisions Architecture Decision Log (ADL) is created. All decisions will be recorded as Architecture Decision Records (ADR).
Each ADR will be recorded using [Michael Nygard template](http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions), which contains following sections: Status, Context, Decision and Consequences.
## Consequences
All architectural decisions should be recorded in log. Old decisions should be recorded as well with an approximate decision date. New decisions should be recorded on a regular basis.
================================================
FILE: docs/architecture-decision-log/0002-use_modular-monolith-system-architecture.md
================================================
# 2. Use Modular Monolith System Architecture
Date: 2019-07-01
Log date: 2019-10-28
## Status
Accepted
## Context
An advanced example of Modular Monolith architecture and tactical DDD implementation in .NET is missing on the internet.
## Decision
I decided to create nontrivial application using Modular Monolith architecture and Domain-Driven Design tactical patterns.
## Consequences
- All modules must run in one single process as single application (Monolith)
- All modules should have maximum autonomy (Modular)
- DDD Bounded Contexts will be used to divide monolith into modules
- DDD tactical patterns will be used to implement most of modules
================================================
FILE: docs/architecture-decision-log/0003-use_dotnetcore_and_csharp.md
================================================
# 3. Use .NET Core and C# language
Date: 2019-07-01
Log date: 2019-10-28
## Status
Accepted
## Context
As it is monolith, only one language (or platform) must be selected for implementation.
## Decision
I decided to use:
- .NET Core platform - it is new generation multi-platform, fully supported by Microsoft and open-source community, optimized and designed to replace old .NET Framework
- C# language - most popuplar language in .NET ecosystem, I have 12 years commercial experience
- F# will not be used, I don't have commercial experience with it
## Consequences
- Whole application will be implemented in C# object-oriented language in .NET Core framework
- .NET Core applications can be executed on Windows, MacOS, Linux
================================================
FILE: docs/architecture-decision-log/0004-divide-the-system-into-4-modules.md
================================================
# 4. Divide the system into 4 modules
Date: 2019-07-01
Log date: 2019-11-02
## Status
Accepted
## Context
The MyMeetings domain contains 4 main subdomains: Meetings (core domain), Administration (supporting subdomain), Payments (supporting subdomain) and User Access (generic domain).
We use Modular Monolith architecture so we need to implement one application which solves all requirements from all domains listed above.
We need to modularize our system.
## Possible solutions
1. Create one "MyMeetings" module and divide it into sub-modules. This solution is simpler to implement at the beginning. We do not have to set module boundaries and think how to communicate between them. On the other hand, this causes a lack of autonomy and can lead to Big Ball Of Mud anti-pattern.
2. Create 4 modules based on Bounded Contexts which in this scenario maps 1:1 to domains. This solution is more difficult at the beginning. We need to set modules boundaries, communication strategy between modules and have more advanced infrastructure code. It is a more complex solution. On the other hand, it supports autonomy, maintainability, readability. We can develop our Domain Models in all of the Bounded Contexts independently.
## Decision
Solution 2.
We created 4 modules: Meetings, Administration, Payments, User Access. The key factor here is module autonomy and maintainability. We want to develop each module independently. This is more cleaner solution. It involves more work at the beginning but we want to invest.
## Consequences
- We can implement each module/Bounded Context independently.
- We need to set clear boundaries between modules and communication strategy between modules (and implement them)
- We need to define the API of each module
- The API/GUI layer needs to know about all of the modules
- We need to create shared libraries/classes to limit boilerplate code which will be the same in all modules
- Complexity of the whole solution will increase
- Complexity of each module will decrease
- We will have clear separation of concerns
- In addition to the application, we must divide the data
- We will have business concepts modeled in a proper way - without "godclasses" which do everything
- We can delegate development of particular module to defined team, work should be done without any conflicts on codebase
================================================
FILE: docs/architecture-decision-log/0005-create-one-rest-api-module.md
================================================
# 5. Create one REST API module
Date: 2019-07-01
Log date: 2019-11-04
## Status
Accepted
## Context
We need to expose the API of our application to the outside world. For now, we expect one client of our application - FrontEnd SPA application.
## Possible solutions
1. Create one .NET Core MVC host application which contains all endpoints. This host application will have references to all business modules and communicates with them directly:
Host/API references:
Administration module
Meetings module
Payments module
User Access module
2. Create one .NET Core MVC host application and multiple APIs projects per module. Each API project should have endpoints which are handled by particular business module:
Host references:
Administration API references Administration module
Meetings API references Meetings module
Payments API references Payments module
User Access API references User Access module
## Decision
Solution 1.
Creating separate API projects for each module will add complexity and little value. Grouping endpoints for a particular business module in a special directory is enough. Another layer on top of the module is unnecessary.
## Consequences
- We will have only one API layer/module
- Each controller has responsibility to delegate Command/Query processing to appropriate module
- We don't need to scan other projects than host for controllers, routes and other MVC mechanisms
- API configuration is easier
- Overall complexity of API layer is lower
- Complexity of each controller is a little bit higher
- Build time will be shorter (less projects)
================================================
FILE: docs/architecture-decision-log/0006-create-facade-between-api-and-business-module.md
================================================
# 6. Create façade between API and business module
Date: 2019-07-01
Log date: 2019-11-04
## Status
Accepted
## Context
Our API layer should communicate with business modules to fulfill client requests. To support the maximum level of autonomy, each module should expose a minimal set of operations (the module API/contract/interface).
## Decision
Each module will provide implementation for one interface with 3 methods:
```csharp
Task ExecuteCommandAsync(ICommand command);
Task ExecuteCommandAsync(ICommand command);
Task ExecuteQueryAsync(IQuery query);
```
This interface will act as a façade (Façade pattern) between API and module. Only Commands, Queries and returned objects (which are part of this interface) should be visible to the API. Everything else should be hidden behind the façade (module encapsulation).
## Consequences
- API can communicate with the module only by façade (the interface).
- Implementation of API is simpler
- We can change module implementation and API does not require change if the interface is not changed
- We need to focus on module encapsulation, sometimes it involves additional work (like instantiation using internal constructors)
================================================
FILE: docs/architecture-decision-log/0007-use-cqrs-architectural-style.md
================================================
# 7. Use CQRS architectural style
Date: 2019-07-01
Log date: 2019-11-04
## Status
Accepted
## Context
Our application should handle 2 types of requests - reading and writing.
For now, it looks like:
- for reading, we need data model in relational form to return data in tabular/flattened way (tables, lists, dictionaries).
- for writing, we need to have a graph of objects to perform more sophisticated work like validations, business rules checks, calculations.
## Decision
We applied the CQRS architectural style/pattern for each business module. Each module will have a separate model for reading and writing. For now, it will be the simplest CQRS implementation when the read model is immediate consistent. This kind of separation is useful even in simple modules like User Access.
## Consequences
- Façade method of each module should take as parameter only Command or Query object
- We have optimized models for writes and reads (SRP principle).
- We can process Commands and Queries in different ways
- As Command or Query is an object, we can easily serialize them and save/log them.
================================================
FILE: docs/architecture-decision-log/0008-allow-return-result-after-command-processing.md
================================================
# 8. Allow return result after command processing
Date: 2019-07-01
Log date: 2019-11-04
## Status
Accepted
## Context
The theory of the CQRS and the CQS principle says that we should not return any information as the result of Command processing. The result should be always "void". However, sometimes we need to return some data immediately as part of the same request.
## Decision
We decided to allow in some cases return results after command processing. Especially, when we create something and we need to return the ID of created object or don't know if request is Command or Query (like Authentication).
## Consequences
- We will have two definitions of Commands and CommandHandlers - with and without result
- It will add some complexity to processing commands (like implementation of decorators)
- We can immediately return the ID of created object/resource. We don't need a second call (query) to retrieve this ID.
- We should be careful to not overuse this approach (sticking as much as possible to the CQRS)
================================================
FILE: docs/architecture-decision-log/0009-use-2-layered-architectural-style-for-reads.md
================================================
# 9. Use 2 layered architectural style for reads
Date: 2019-07-01
Log date: 2019-11-04
## Status
Accepted
## Context
We applied the CQRS style (see [ADR 7. Use CQRS architectural style](007-use-cqrs-architectural-style.md)), now we need to decide how to handle reading (querying) requests.
## Decision
We will use 2 layered architecture to handle queries: API layer and Application Service layer. As we applied the CQRS and created a separated read model, querying should be straightforward so 2 layers are enough. The API layer is responsible for Query creation based on HTTP request and the module Application layer is responsible for query handling.
## Consequences
- Whole query handling logic is in Application Service layer
- Application Service layer is coupled to the database and querying framework
- Solution is simple, easy to understand
- We don't abstract over database
- Performance is better (no object mapping between layers, querying database almost immediately)
================================================
FILE: docs/architecture-decision-log/0010-use-clean-architecture-for-writes.md
================================================
# 10. Use Clean Architecture for writes
Date: 2019-07-01
Log date: 2019-11-05
## Status
Accepted
## Context
We applied the CQRS style (see [ADR #7](0007-use-cqrs-architectural-style.md)), now we need to decide how to handle writing operations (Commands).
## Decision
We will use **Clean Architecture** to handle commands with 4 layers: **API layer**, **Application Service layer**, **Infrastructure layer** and **Domain layer**.
We need to add Domain layer because domain logic will be complex and we want to isolate this logic from other stuff like infrastructure or API. Isolation of domain logic supports testing, maintainability and readability.
## Consequences
- Complexity of the whole solution is higher - we need to add two more layers - domain and infrastructure
- Complexity of implementation of business logic will be smaller - we can focus only on business concerns on this layer
- Complexity of implementation of infrastructure will be smaller - we can focus only on infrastructure concerns on this layer
- Business logic will be testable (no references to other layers)
- Business logic will be independent of persistence (to some level)
- In the Domain layer, we will have the same level of abstraction (close to business)
- Application layer will have louse coupling to the Domain layer and Infrastructure layer (depend on abstractions only)
- We use one of the most popular application architecture - developers are familiar with it
================================================
FILE: docs/architecture-decision-log/0011-create-rich-domain-models.md
================================================
# 11. Create rich Domain Models
Date: 2019-07-01
Log date: 2019-11-05
## Status
Accepted
## Context
We need to create Domain Models for all of the modules. Each Domain Model should represent a solution that solves a particular set of Domain problems (implements business logic).
## Possible solutions
1. Create Anemic Domain Model (Data Model) and implement *Transaction Script* pattern together with *Active Record* pattern
2. Put all business logic to database in stored procedures
3. Create a Rich Domain Model
## Decision
Solution number 3 - Rich Domain Model
1 - no, because the procedural style of coding will not be enough. We want to focus on behavior, not on the data.
2 - no, keeping business logic in the database is not a good idea in that case, object-oriented programming is better than T-SQL to model our domain and we don't have performance architectural drivers to resign from OOD.
We expect complex business logic with different rules, calculations and processing so we want to get as much as possible from Object-Oriented Design principles like abstraction, encapsulation, polymorphism. We want to mutate the state of our objects only through methods (abstraction) to encapsulate all logic and hide implementation details from the client (the Application Service Layer and Unit Tests).
## Consequences
- All objects should be encapsulated (private by default principle)
- Encapsulation of objects implies more work in infrastructure (mapping to private fields, collections is harder)
- Encapsulation of objects decreases to some level testability of these objects (Object-Oriented Design vs Testable Design)
- All public methods of domain objects create Domain Model API
- Implementation details of business logic are hidden
- Clients of Domain Model are easier to implement
- Better object-oriented programming skills are required to implement Rich Domain Model
- Is easier to protect business rules/invariants using Rich Domain Model
================================================
FILE: docs/architecture-decision-log/0012-use-domain-driven-design-tactical-patterns.md
================================================
# 12. Use Domain-Driven Design tactical patterns
Date: 2019-07-01
Log date: 2019-11-05
## Status
Accepted
## Context
We decided to use the Clean Architecture ([ADR #10](0010-use-clean-architecture-for-writes.md)) and create Rich Domain Models ([ADR #11](0011-create-rich-domain-models.md)) for each module. We need to define or use some construction elements / building blocks to implement our architecture and business logic.
## Decision
We decided to use **Domain-Driven Design** tactical patterns. They focus on the Domain Model implementation. Especially we will use the following building blocks:
- Command - public method on Aggregate (behavior)
- Domain Event - the immutable class which represents important fact occurred on a special point of time (behavior)
- Entity - class with identity (identity cannot change) with mutable attributes which represents concept from domain
- Value Object - immutable class without an identity which represents concept from domain
- Aggregate - cluster of domain objects (Entities, Value Objects) with one class entry point (Entity as Aggregate Root) which defines the boundary of transaction/consistency and protects business rules and invariants
- Repository - collection-like abstraction to persist and load particular Aggregate
- Domain Service - stateless service to execute some business logic which does not belong to any of Entity/Value Object
## Consequences
- We need to define entities and value objects
- We need to define aggregates boundaries
- We need to add repositories for each aggregate
- We can invoke only public methods on Aggregate Roots, everything else should be hidden
- Developers need to be familiar with DDD tactical patterns
================================================
FILE: docs/architecture-decision-log/0013-protect-business-invariants-using-exceptions.md
================================================
# 13. Protect business invariants using exceptions
Date: 2019-07-01
Log date: 2019-11-05
## Status
Accepted
## Context
Aggregates should check business invariants. When the invariant is broken, we should stop processing and return an error immediately to the client.
## Possible solutions
### 1. Use exceptions
#### Pros
- we can stop processing immediately (fail-fast)
- popular approach in C#
- we don't need to check the result of each method (if-else statements)
- we can catch all Business Exceptions in one place and translate them (for example in the API layer to some HTTP response code).
#### Cons
- indirection
- little performance impact
- for special cases, we need to add a specific catch.
### 2. Return Result object
#### Pros
- no indirection
- no performance impact
- signature method is more descriptive.
### Cons
- we need to add checks result of each method (if-else statements)
- approach is less-known in the C# world
- it needs a library or more coding to support Results
## Decision
Solution number 1 - Use exceptions.
Performance cost of throwing an exception is irrelevant, we don't want too many if/else statements in entities, more familiar with exceptions approach.
## Consequences
- We need to add special *BusinessException* class to separate business rules validation exceptions from other exceptions
- We need to create different business exceptions for each business rule
- We will have a small performance impact (throwing exceptions)
- We will have generic mechanism which catches *BusinessException*
- We will not have a lot of if/else statements in Entities/Value Objects to check method results
- Some monitoring tools logs automatically each exception. If we want to use one of this tool we should be aware of this and figure it out proper solution
================================================
FILE: docs/architecture-decision-log/0014-event-driven-communication-between-modules.md
================================================
# 14. Event-driven communication between modules
Date: 2019-07-15
Log date: 2019-11-09
## Status
Accepted
## Context
Each module should be autonomous. However, communication between them must take place. We have to decide what will be the preferred way of communication and integration between modules.
## Possible solutions
### 1. Direct method call (synchronous)
Each Module will expose a set of methods (interface, module API) which can be called by other modules directly.
#### Pros
- easier implementation
- no indirection
- more natural in the monolith architecture
- supports immediate consistency
#### Cons
- less autonomy
- strong coupling between modules
- direct method call is blocking
- module has a dependency on another module
### 2. Event-driven (asynchronous)
Each module will publish a specific set of events. Other modules can subscribe to specific events. It is the implementation of _Publish/Subscribe_ pattern.
#### Pros
- more autonomy
- coupling is only to middleware/broker of events
- no blocking communication
- stronger modules boundaries
- module does not have a dependency on another module
#### Cons
- indirection
- more complex solution
- middleware/broker is needed
- does not support immediate consistency
## Decision
Solution number 2 - Event-driven (asynchronous)
We want to achieve the maximum level of autonomy and loose coupling between modules. Moreover, we don't want dependencies between modules. We allow direct calls in the future, but this should be an exception, not a rule.
## Consequences
- We need to implement the Publish/Subscribe pattern
- Solution will be more complex
- Modules will have more autonomy
- Modules will have coupling to broker/middleware
- During modules integration, eventual consistency will occur (asynchronous communication)
- Events become Published Language of our Bounded Contexts (modules)
- Events structure should be stable as much as possible
================================================
FILE: docs/architecture-decision-log/0015-use-in-memory-events-bus.md
================================================
# 15. Use In-Memory Events Bus
Date: 2019-07-15
Log date: 2019-11-09
## Status
Accepted
## Context
As we want to base inter-modular communication on asynchronous communication in the form of event-driven architecture, we need some "events bus" to do that.
## Possible solutions
### 1. In Memory Events Bus
In memory Publish/Subscribe implementation without any external component.
#### Pros
- very easy to implement
- no network communication needed
- performance (it depends)
- no need to learn anything
- simple solution
#### Cons
- does not support more advanced integration scenarios, everything needs to be implemented
- does not have configuration
- does not have other features (who have messaging brokers)
### 2. Message Broker
External middleware component. It could be a low-level broker (like RabbitMQ) or a high-level broker (like MassTransit, NServiceBus).
#### Pros
- only integration with platform code needed
- more advanced integration scenarios
- richness of configuration
- a lot of features
#### Cons
- complex solution
- network communication
- new platform learning needed
- performance (it depends)
## Decision
Solution number 1 - In Memory Events Bus
At that moment we don't see more advanced integration scenarios in our system than simple publish/subscribe scenario. We decided to follow the simplest scenario and if it will be necessary - move to more advanced.
## Consequences
- We need to implement Publish/Subscribe in memory
- All modules will have dependency to In Memory Events Bus to publish events/subscribe to events
- if we ever want to separate a module to another process (microservices architecture), we will need to switch to middleware
================================================
FILE: docs/architecture-decision-log/0016-create-ioc-container-per-module.md
================================================
# 16. Create an IoC Container per module
Date: 2019-07-15
Log date: 2019-11-09
## Status
Accepted
## Context
For each module, when we process particular Command or Query, we need to resolve a graph of objects. We need to decide how dependencies of objects will be resolved.
## Possible solutions
### 1. One IoC Container for whole application
One IoC container located in the host project.
#### Pros
- standard approach
- dependencies configured in one place
#### Cons
- couples host application with all of projects, libraries
- modules autonomy decreases
- strong coupling
### 2. IoC Container per module
Multiple IoC containers per modules.
#### Pros
- module autonomy
- loose coupling
- host application has dependency only to Application Service Layer
#### Cons
- duplicated code
- non-standard approach
## Decision
Solution number 2 - IoC Container per module
IoC Container per module supports the autonomy of the module and louse coupling so this is a more important aspect for us than duplicated code in some places.
## Consequences
- Create and maintain an IoC Container for each module
- Implementation is not standard, but still acceptable easy
- We can add dependencies to module and other modules are intact
================================================
FILE: docs/architecture-decision-log/0017-implement-archictecture-tests.md
================================================
# 17. Implement Architecture Tests
Date: 2019-11-16
## Status
Accepted
## Context
In some cases it is not possible to enforce the application architecture, design or established conventions using compiler (compile-time). For this reason, code implementations can diverge from the original design and architecture. We want to minimize this behavior, not only by code review.
## Decision
We decided to implement Unit Tests for our architecture.
We will implement tests for each module separately and one tests library for general architecture. We will use _NetArchTest_ library which was created exactly for this purpose.
## Consequences
- We will have quick feedback about breaking the design rules
- Unit tests for architecture are documenting our architecture to some level
- We will have dependency to external library
- We need to implement some _"reflection-based"_ code to check some rules, because library does not provide everything what we need
- This kind of tests are a bit slower than normal unit tests (because of reflection)
- More tests to maintain
================================================
FILE: docs/catalog-of-terms/Aggregate-DDD/README.md
================================================
# Aggregate (DDD)
## Definition
*Cluster ENTITES and VALUE OBJECTS into AGGREGATES and define boundaries around each. Choose one ENTITY to be the root of each AGGREGATE, and control all access to the objects inside the boundary through the root. Transient references to internal members can be passed out for use within a single operation only. Because the root controls access, it cannot be blindsided by changes to the internals. This arrangement makes it practical to enforce all invariants for objects in the AGGREGATE and for the AGGREGATE as a whole in any state change.*
Source: [Domain-Driven Design: Tackling Complexity in the Heart of Software, Eric Evans](https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215)
## Example
### Model

### Code
```csharp
public class MeetingGroup : Entity, IAggregateRoot
{
public MeetingGroupId Id { get; private set; }
private string _name;
private string _description;
private MeetingGroupLocation _location;
private MemberId _creatorId;
private List _members;
private DateTime _createDate;
private DateTime? _paymentDateTo;
internal static MeetingGroup CreateBasedOnProposal(
MeetingGroupProposalId meetingGroupProposalId,
string name,
string description,
MeetingGroupLocation location,
MemberId creatorId)
{
return new MeetingGroup(meetingGroupProposalId, name, description, location, creatorId);
}
private MeetingGroup()
{
// Only for EF.
}
private MeetingGroup(MeetingGroupProposalId meetingGroupProposalId, string name, string description, MeetingGroupLocation location, MemberId creatorId)
{
this.Id = new MeetingGroupId(meetingGroupProposalId.Value);
this._name = name;
this._description = description;
this._creatorId = creatorId;
this._location = location;
this._createDate = SystemClock.Now;
this.AddDomainEvent(new MeetingGroupCreatedDomainEvent(this.Id, creatorId));
this._members = new List();
this._members.Add(MeetingGroupMember.CreateNew(this.Id, this._creatorId, MeetingGroupMemberRole.Organizer));
}
public void EditGeneralAttributes(string name, string description, MeetingGroupLocation location)
{
this._name = name;
this._description = description;
this._location = location;
this.AddDomainEvent(new MeetingGroupGeneralAttributesEditedDomainEvent(this._name, this._description, this._location));
}
public void JoinToGroupMember(MemberId memberId)
{
this.CheckRule(new MeetingGroupMemberCannotBeAddedTwiceRule(_members, memberId));
this._members.Add(MeetingGroupMember.CreateNew(this.Id, memberId, MeetingGroupMemberRole.Member));
}
public void LeaveGroup(MemberId memberId)
{
this.CheckRule(new NotActualGroupMemberCannotLeaveGroupRule(_members, memberId));
var member = this._members.Single(x => x.IsMember(memberId));
member.Leave();
}
public void SetExpirationDate(DateTime dateTo)
{
_paymentDateTo = dateTo;
this.AddDomainEvent(new MeetingGroupPaymentInfoUpdatedDomainEvent(this.Id, _paymentDateTo.Value));
}
public Meeting CreateMeeting(
string title,
MeetingTerm term,
string description,
MeetingLocation location,
int? attendeesLimit,
int guestsLimit,
Term rsvpTerm,
MoneyValue eventFee,
List hostsMembersIds,
MemberId creatorId)
{
this.CheckRule(new MeetingCanBeOrganizedOnlyByPayedGroupRule(_paymentDateTo));
this.CheckRule(new MeetingHostMustBeAMeetingGroupMemberRule(creatorId, hostsMembersIds, _members));
return Meeting.CreateNew(
this.Id,
title,
term,
description,
location,
MeetingLimits.Create(attendeesLimit, guestsLimit),
rsvpTerm,
eventFee,
hostsMembersIds,
creatorId);
}
internal bool IsMemberOfGroup(MemberId attendeeId)
{
return _members.Any(x => x.IsMember(attendeeId));
}
internal bool IsOrganizer(MemberId memberId)
{
return _members.Any(x => x.IsOrganizer(memberId));
}
}
```
### Description
Classes `MeetingGroup`, `MeetingGroupLocation`, `MeetingGroupId`, `MeetingGroupMember', 'MeetingGroupMemberRole` form the **Aggregate**. `MeetingGroup` acts as the **AggregateRoot** (*Choose one ENTITY to be the root of each AGGREGATE*). AggregateRoot has a global identifier (`Id`) and public methods to change state of the *Aggregate*. The rest is encapsulated (*Because the root controls access, it cannot be blindsided by changes to the internals*). For each public method, the invariants are checked first (`CheckRule`) (*This arrangement makes it practical to enforce all invariants for objects in the AGGREGATE and for the AGGREGATE as a whole in any state change*).
## Additional References
- [DDD_Aggregate (Martin Fowler)](https://martinfowler.com/bliki/DDD_Aggregate.html)
================================================
FILE: docs/catalog-of-terms/Aggregate-DDD/aggregate-ddd.puml
================================================
@startuml Aggregate
package "Meeting Groups Aggregate" <> {
class "MeetingGroupId" << VO >> {
}
class "MeetingGroup" << Entity, AR >> {
-string: _description
-DateTime: _createDate
-DateTime: _paymentDateTo
{static} MeetingGroup CreateBasedOnProposal()
Meeting CreateMeeting(..)
void SetExpirationDate(DateTime dateTo)
void JoinToGroupMember(MemberId memberId)
void LeaveGroup(MemberId memberId)
void EditGeneralAttributes(...)
bool IsMemberOfGroup(MemberId attendeeId)
bool IsOrganizer(MemberId memberId)
}
class "MeetingGroupLocation" << VO >> {
string City
string CountryCode
{static} MeetingGroupLocation Create(...)
}
class "MeetingGroupMember" << Entity >> {
~DateTime JoinedDate
-bool _isActive
-DateTime? _leaveDate
{static} MeetingGroupMember CreateNew(...)
void Leave()
~bool IsMember(MemberId memberId)
~bool IsOrganizer(MemberId memberId)
}
class "MemberId" << VO >> {
}
class "MeetingGroupMemberRole" << VO >> {
string Value
}
}
class "Member" << Entity, AR >> {
}
"MeetingGroup" *-- "MeetingGroupId" : of
"MeetingGroup" *-- "MeetingGroupLocation" : for
"MeetingGroup" "1" *-- "0..*" "MeetingGroupMember" : member of
"MeetingGroupMember" *-- "MemberId" : assigned to
"MeetingGroupMemberRole" --* "MeetingGroupMember" : is assigned to
"Member" o-- "MemberId" : of
@enduml
================================================
FILE: docs/catalog-of-terms/Command/README.md
================================================
# Command
## Definition
*A command is a request made to do something. A command represents the intention of a system’s user regarding what the system will do to change its state.*
*Command characteristics:*
- *The result of a command can be either success or failure; the result is an [Event(s)](../Event/)*
- *In case of success, state change(s) must have occurred somewhere (otherwise nothing happened)*
- *Commands should be named with a verb, in the present tense or infinitive, and a nominal group coming from the domain (entity of aggregate type)*
Source: [Open Agile Architecture](https://pubs.opengroup.org/architecture/o-aa-standard/#KLP-EDA-event-command)
## Example
### Model
### Code
`Meeting` class in [Domain Model](../Domain-Model/):
```csharp
public void Cancel(MemberId cancelMemberId)
{
this.CheckRule(new MeetingCannotBeChangedAfterStartRule(_term));
if (!_isCanceled)
{
_isCanceled = true;
_cancelDate = SystemClock.Now;
_cancelMemberId = cancelMemberId;
this.AddDomainEvent(new MeetingCanceledDomainEvent(this.Id, _cancelMemberId, _cancelDate.Value));
}
}
```
`CancelMeetingCommand` class in [Application Layer](../Application-Layer/)
```csharp
public class CancelMeetingCommand : CommandBase
{
public CancelMeetingCommand(Guid meetingId)
{
MeetingId = meetingId;
}
public Guid MeetingId { get; }
}
internal class CancelMeetingCommandHandler : ICommandHandler
{
private readonly IMeetingRepository _meetingRepository;
private readonly IMemberContext _memberContext;
internal CancelMeetingCommandHandler(IMeetingRepository meetingRepository, IMemberContext memberContext)
{
_meetingRepository = meetingRepository;
_memberContext = memberContext;
}
public async Task Handle(CancelMeetingCommand request, CancellationToken cancellationToken)
{
var meeting = await _meetingRepository.GetByIdAsync(new MeetingId(request.MeetingId));
meeting.Cancel(_memberContext.MemberId);
return Unit.Value;
}
}
```
### Description
In the example above, we can distinguish between 2 types of Commands:
- as an object in the application layer [Parameter Object Pattern](../Parameter-Object-Pattern/)
- in the form of a method on the object (in DDD on the [Aggregate](../Aggregate-DDD/)
The most important thing is that the Command can be rejected until the state changes. In both the `CommandHandler` (invalid MeetingId) and the `Cancel` method (business rule broken), an exception can be thrown and the Command is then rejected and all uncomitted changes are rolled back (state does not change).
================================================
FILE: docs/catalog-of-terms/Command/command.puml
================================================
@startuml Command
class CancelMeetingCommand {
MeetingGroupId: Id
}
note top of CancelMeetingCommand : Command as part of Application Layer
class Meeting {
void Cancel(MemberId cancelMemberId)
}
note top of Meeting : Command defined in Domain Model (on an Aggregate)
@enduml
================================================
FILE: docs/catalog-of-terms/Decorator-Pattern/README.md
================================================
# Decorator Pattern
## Definition
*In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the [Single Responsibility Principle](../Single-Responsibility-Principle/), as it allows functionality to be divided between classes with unique areas of concern.*
Source: [Wikipedia](https://en.wikipedia.org/wiki/Decorator_pattern)
## Example
### Model

### Code
```csharp
internal class LoggingCommandHandlerDecorator : ICommandHandler where T:ICommand
{
private readonly ILogger _logger;
private readonly IExecutionContextAccessor _executionContextAccessor;
private readonly ICommandHandler _decorated;
public LoggingCommandHandlerDecorator(
ILogger logger,
IExecutionContextAccessor executionContextAccessor,
ICommandHandler decorated)
{
_logger = logger;
_executionContextAccessor = executionContextAccessor;
_decorated = decorated;
}
public async Task Handle(T command, CancellationToken cancellationToken)
{
if (command is IRecurringCommand)
{
return await _decorated.Handle(command, cancellationToken);
}
using (
LogContext.Push(
new RequestLogEnricher(_executionContextAccessor),
new CommandLogEnricher(command)))
{
try
{
this._logger.Information(
"Executing command {Command}",
command.GetType().Name);
var result = await _decorated.Handle(command, cancellationToken);
this._logger.Information("Command {Command} processed successful", command.GetType().Name);
return result;
}
catch (Exception exception)
{
this._logger.Error(exception, "Command {Command} processing failed", command.GetType().Name);
throw;
}
}
}
private class CommandLogEnricher : ILogEventEnricher
{
private readonly ICommand _command;
public CommandLogEnricher(ICommand command)
{
_command = command;
}
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddOrUpdateProperty(new LogEventProperty("Context", new ScalarValue($"Command:{_command.Id.ToString()}")));
}
}
private class RequestLogEnricher : ILogEventEnricher
{
private readonly IExecutionContextAccessor _executionContextAccessor;
public RequestLogEnricher(IExecutionContextAccessor executionContextAccessor)
{
_executionContextAccessor = executionContextAccessor;
}
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (_executionContextAccessor.IsAvailable)
{
logEvent.AddOrUpdateProperty(new LogEventProperty("CorrelationId", new ScalarValue(_executionContextAccessor.CorrelationId)));
}
}
}
}
```
### Description
The Logging decorator logs execution, arguments and processing of each Command. This way each log inside a processor has the log context of the processing command.
A unique trade of a decorator is that it does both:
* It implements `ICommandHandler` (known also as the *component*).
* It accepts an implementation of `ICommandHandler` (known also as the *concrete component*). Usually that is done via [Dependency Injection](../Dependency-Injection/).
The decorator builds on top of existing functionality provided by the injected `ICommandHandler`, but it does not change the behavior of it.
---
Decorator should not be confused with [Strategy](../Strategy-Pattern/)!!!
*A decorator lets you change the skin of an object, while Strategy lets you change the guts.*
================================================
FILE: docs/catalog-of-terms/Decorator-Pattern/decorator-pattern.puml
================================================
@startuml
class MeetingsController {
+AddMeetingAttendee()
+RemoveMeetingAttendee()
}
class AddMeetingAttendeeCommand
class RemoveMeetingAttendeeCommand
class Mediator {
+Send()
}
interface ICommandHandler {
+Handle(TCommand, CancellationToken)
}
~class AddMeetingAttendeeCommandHandler {
+Handle(AddMeetingAttendeeCommand, CancellationToken)
}
~class RemoveMeetingAttendeeCommandHandler {
+Handle(RemoveMeetingAttendeeCommand, CancellationToken)
}
~class LoggingCommandHandlerDecorator {
+Handle(T, CancellationToken)
-Log()
}
note left of LoggingCommandHandlerDecorator::Log
Performs logging, but doesn't
change how Handle operates
end note
hide empty members
MeetingsController -down-> Mediator: informs
MeetingsController -down-> Mediator: informs
Mediator -down-> AddMeetingAttendeeCommand: sends
Mediator -down-> RemoveMeetingAttendeeCommand: sends
AddMeetingAttendeeCommandHandler -up-> AddMeetingAttendeeCommand: handles
RemoveMeetingAttendeeCommandHandler -up-> RemoveMeetingAttendeeCommand: handles
AddMeetingAttendeeCommandHandler .right.|> ICommandHandler: implements
RemoveMeetingAttendeeCommandHandler .right.|> ICommandHandler: implements
LoggingCommandHandlerDecorator ..|> ICommandHandler: implements
LoggingCommandHandlerDecorator *..|> ICommandHandler: decorates
@enduml
================================================
FILE: docs/catalog-of-terms/Dependency-Injection/README.md
================================================
# Dependency Injection
## Definition
*Dependency Injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies.*
Source: [Wikipedia](https://en.wikipedia.org/wiki/Dependency_injection)
## Example
### Model

### Code
```csharp
internal class CancelMeetingCommandHandler : ICommandHandler
{
private readonly IMeetingRepository _meetingRepository;
private readonly IMemberContext _memberContext;
internal CancelMeetingCommandHandler(IMeetingRepository meetingRepository, IMemberContext memberContext)
{
_meetingRepository = meetingRepository;
_memberContext = memberContext;
}
public async Task Handle(CancelMeetingCommand request, CancellationToken cancellationToken)
{
var meeting = await _meetingRepository.GetByIdAsync(new MeetingId(request.MeetingId));
meeting.Cancel(_memberContext.MemberId);
return Unit.Value;
}
}
```
### Description
A `CancelMeetingCommandHandler` needs two collaborators (dependencies) to fulfill its job - repository of meetings (`IMeetingRepository`) and information about member context (`IMemberContext`). It doesn't instance implementation of these interfaces itself - they are provided (injected) via construction (*Constructor Injection*).
================================================
FILE: docs/catalog-of-terms/Dependency-Injection/dependency-injection.puml
================================================
@startuml Dependency Injection
class "CancelMeetingCommandHandler" {
CancelMeetingCommandHandler(IMeetingRepository meetingRepository, IMemberContext memberContext)
}
interface "IMeetingRepository" {
}
interface "IMemberContext" {
}
"CancelMeetingCommandHandler" -> "IMeetingRepository" : uses
"CancelMeetingCommandHandler" -> "IMemberContext" : uses
@enduml
================================================
FILE: docs/catalog-of-terms/Domain-Event/README.md
================================================
# Domain Event
## Definition
*An event is something that has happened in the past. A **domain event** is, something that happened in the domain that you want other parts of the same domain (in-process) to be aware of. The notified parts usually react somehow to the events.*
Source: [Domain events: design and implementation](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation)
## Example
### Model

### Code
```csharp
public class SubscriptionPaymentCreatedDomainEvent : DomainEventBase
{
public SubscriptionPaymentCreatedDomainEvent(
Guid subscriptionPaymentId,
Guid payerId,
string subscriptionPeriodCode,
string countryCode,
string status,
decimal value,
string currency)
{
SubscriptionPaymentId = subscriptionPaymentId;
PayerId = payerId;
SubscriptionPeriodCode = subscriptionPeriodCode;
CountryCode = countryCode;
Status = status;
Value = value;
Currency = currency;
}
public Guid SubscriptionPaymentId { get; }
public Guid PayerId { get; }
public string SubscriptionPeriodCode { get; }
public string CountryCode { get; }
public string Status { get; }
public decimal Value { get; }
public string Currency { get; }
}
public class DomainEventBase : IDomainEvent
{
public Guid Id { get; }
public DateTime OccurredOn { get; }
public DomainEventBase()
{
this.Id = Guid.NewGuid();
this.OccurredOn = DateTime.UtcNow;
}
}
```
### Description
A `SubscriptionPaymentCreatedDomainEvent` gets fired within the `SubscriptionPayment` aggregate root. This happens whenever a `Member` who is also a `Payer`, issues a command to buy a `Subscription`.
All properties are `get` only, because an event is something that has happened in the past, and you can not change the past.
Event details:
* `SubscriptionPaymentId` - Auto generated unique Id for the subscription payment.
* `PayerId` - The Id of the payer wanting to buy a subscription.
* `SubscriptionPeriodCode` - The period of validity for this subscription:
* 1 Month
* 6 Months
* Custom
* `CountryCode` - The code of the country that the payer is issuing from.
* `Status` - Automatically set to *WaitingForPayment*.
* `Value` - The amount to be paid for the chosen subscription period.
* `Currecy` - The currency of choice of the payer.
---
Business domain events extend `DomainEventBase` which in-turn implements the `IDomainEvent` interface.
Base event details:
* `Id` - Auto generated unique Id for the event itself.
* `OccurredOn` - The point-in-time when the event happened.
================================================
FILE: docs/catalog-of-terms/Domain-Event/domain-event.puml
================================================
@startuml
class SubscriptionPaymentCreatedDomainEvent {
+SubscriptionPaymentId
+PayerId
+SubscriptionPeriodCode
+CountryCode
+Status
+Value
+Currency
}
class DomainEventBase
interface IDomainEvent {
+Id
+OccurredOn
}
IDomainEvent <|-- DomainEventBase: implements
DomainEventBase <|-- SubscriptionPaymentCreatedDomainEvent: extends
@enduml
================================================
FILE: docs/catalog-of-terms/Entity-DDD/README.md
================================================
# Entity (DDD)
## Definition
*When an object is distinguished by its identity, rather than its attributes, make this primary to its definition in the model. Keep the class definition simple and focused on life cycle continuity and identity. Define a means of distinguishing each object regardless of its form or history.*
Source: [Domain-Driven Design: Tackling Complexity in the Heart of Software, Eric Evans](https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215)
## Example
### Model

### Code
```csharp
public class MeetingGroup : Entity, IAggregateRoot
{
public MeetingGroupId Id { get; private set; }
private string _name;
private string _description;
private MeetingGroupLocation _location;
private MemberId _creatorId;
private List _members;
private DateTime _createDate;
private DateTime? _paymentDateTo;
internal static MeetingGroup CreateBasedOnProposal(
MeetingGroupProposalId meetingGroupProposalId,
string name,
string description,
MeetingGroupLocation location,
MemberId creatorId)
{
return new MeetingGroup(meetingGroupProposalId, name, description, location, creatorId);
}
private MeetingGroup()
{
// Only for EF.
}
private MeetingGroup(MeetingGroupProposalId meetingGroupProposalId, string name, string description, MeetingGroupLocation location, MemberId creatorId)
{
this.Id = new MeetingGroupId(meetingGroupProposalId.Value);
this._name = name;
this._description = description;
this._creatorId = creatorId;
this._location = location;
this._createDate = SystemClock.Now;
this.AddDomainEvent(new MeetingGroupCreatedDomainEvent(this.Id, creatorId));
this._members = new List();
this._members.Add(MeetingGroupMember.CreateNew(this.Id, this._creatorId, MeetingGroupMemberRole.Organizer));
}
public void EditGeneralAttributes(string name, string description, MeetingGroupLocation location)
{
this._name = name;
this._description = description;
this._location = location;
this.AddDomainEvent(new MeetingGroupGeneralAttributesEditedDomainEvent(this._name, this._description, this._location));
}
public void JoinToGroupMember(MemberId memberId)
{
this.CheckRule(new MeetingGroupMemberCannotBeAddedTwiceRule(_members, memberId));
this._members.Add(MeetingGroupMember.CreateNew(this.Id, memberId, MeetingGroupMemberRole.Member));
}
public void LeaveGroup(MemberId memberId)
{
this.CheckRule(new NotActualGroupMemberCannotLeaveGroupRule(_members, memberId));
var member = this._members.Single(x => x.IsMember(memberId));
member.Leave();
}
public void SetExpirationDate(DateTime dateTo)
{
_paymentDateTo = dateTo;
this.AddDomainEvent(new MeetingGroupPaymentInfoUpdatedDomainEvent(this.Id, _paymentDateTo.Value));
}
public Meeting CreateMeeting(
string title,
MeetingTerm term,
string description,
MeetingLocation location,
int? attendeesLimit,
int guestsLimit,
Term rsvpTerm,
MoneyValue eventFee,
List hostsMembersIds,
MemberId creatorId)
{
this.CheckRule(new MeetingCanBeOrganizedOnlyByPayedGroupRule(_paymentDateTo));
this.CheckRule(new MeetingHostMustBeAMeetingGroupMemberRule(creatorId, hostsMembersIds, _members));
return Meeting.CreateNew(
this.Id,
title,
term,
description,
location,
MeetingLimits.Create(attendeesLimit, guestsLimit),
rsvpTerm,
eventFee,
hostsMembersIds,
creatorId);
}
internal bool IsMemberOfGroup(MemberId attendeeId)
{
return _members.Any(x => x.IsMember(attendeeId));
}
internal bool IsOrganizer(MemberId memberId)
{
return _members.Any(x => x.IsOrganizer(memberId));
}
}
```
### Description
A *Meeting Group* is something we want to follow in time (it has a life cycle). For this reason, it has its unique identifier (`Id`). Is should be fully encapsulated - you can only mutate its state via exposed *behavior* (no setters).
================================================
FILE: docs/catalog-of-terms/Entity-DDD/entity-ddd.puml
================================================
@startuml Entity
class "MeetingGroup" << Entity >> {
MeetingGroupId: Id
-string: _description
-DateTime: _createDate
-DateTime: _paymentDateTo
{static} MeetingGroup CreateBasedOnProposal()
Meeting CreateMeeting(..)
void SetExpirationDate(DateTime dateTo)
void JoinToGroupMember(MemberId memberId)
void LeaveGroup(MemberId memberId)
void EditGeneralAttributes(...)
bool IsMemberOfGroup(MemberId attendeeId)
bool IsOrganizer(MemberId memberId)
}
@enduml
================================================
FILE: docs/catalog-of-terms/Event/README.md
================================================
# Event
## Definition
*An event is something that has happened in the past.*
Source: [Domain events: design and implementation](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation)
## Example
For examples, see specific kind of events:
- [Domain Event](../Domain-Event/)
- [Integration Event](../Integration-Event/)
## Related
- [Event Driven Architecture](../Event-Driven-Architecture/)
- [Event Storming](../Event-Storming/)
- [Event Sourcing](../Event-Sourcing/)
================================================
FILE: docs/catalog-of-terms/Event-Driven-Architecture/README.md
================================================
# Event Driven Architecture
TODO
================================================
FILE: docs/catalog-of-terms/Event-Sourcing/README.md
================================================
# Event Sourcing
TODO
================================================
FILE: docs/catalog-of-terms/Event-Storming/README.md
================================================
# Event Storming
TODO
================================================
FILE: docs/catalog-of-terms/Integration-Event/README.md
================================================
# Integration Event
TODO
================================================
FILE: docs/catalog-of-terms/README.md
================================================
# Catalog of terms
- Act/Arrange/Assert
- Actor (Event Storming)
- API
- Application Layer
- [Aggregate (DDD)](Aggregate-DDD/)
- Architecture Decision Record (ADR)
- Architecture Test
- Asynchronous Communication
- Audit Log/Trail
- Authentication
- Authorization
- Bounded Context (DDD)
- C4 Model
- Chain Of Command Pattern
- [Command](Command/)
- Composition Root
- Continuous Integration
- Contract
- CQRS
- Database Change Management
- [Decorator Pattern](Decorator-Pattern/)
- [Dependency Injection](Dependency-Injection/)
- Dependency Inversion
- Diagram as text
- Domain Centric Architecture
- [Domain Event](Domain-Event/)
- Domain Layer
- Domain Model
- Domain Primitive
- Domain Services (DDD)
- Don't Repeat Yourself Principle
- Encapsulation
- [Entity (DDD)](Entity-DDD/)
- [Event](Event/)
- Eventual Consistency
- [Event Driven Architecture](Event-Driven-Architecture/)
- [Event Sourcing](Event-Sourcing/)
- [Event Storming](Event-Storming/)
- Events Stream
- External System (Event Storming)
- Facade Pattern
- Factory Pattern
- Given When Then
- Layered Architecture
- Mediator Pattern
- Message (Messaging)
- Mock
- Modularity
- Module
- Monolith
- Idempotency
- Immediate Consistency
- Immutability
- Infrastructure Layer
- [Integration Event](Integration-Event/)
- Interface
- Interface Segregation Principle
- Inversion Of Control
- Integration Test
- Outbox Pattern (aka Store And Forward)
- Parameter Object Pattern
- Persistence Ignorance
- POCO
- Policy (EventStorming)
- Projection (EventSourcing)
- Pure Function
- Rich Domain Model
- Role-based Access Control
- Query
- Read Model
- Repositories (DDD)
- Single Responsibility Principle
- [Strategy Pattern](Strategy-Pattern/)
- Stub
- Synchronous Communication
- Transaction (Database)
- Ubiquitous Language (DDD)
- Unit Of Work Pattern
- Unit Test
- Write Model
- [ValueObject (DDD)](ValueObject-DDD/)
================================================
FILE: docs/catalog-of-terms/Strategy-Pattern/README.md
================================================
# Strategy Pattern
## Definition
*The strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.*
Source: [Wikipedia](https://en.wikipedia.org/wiki/Strategy_pattern)
## Example
### Model

### Code
```csharp
internal class BuySubscriptionCommandHandler : ICommandHandler
{
private readonly IAggregateStore _aggregateStore;
private readonly IPayerContext _payerContext;
private readonly ISqlConnectionFactory _sqlConnectionFactory;
internal BuySubscriptionCommandHandler(
IAggregateStore aggregateStore,
IPayerContext payerContext,
ISqlConnectionFactory sqlConnectionFactory)
{
_aggregateStore = aggregateStore;
_payerContext = payerContext;
_sqlConnectionFactory = sqlConnectionFactory;
}
public async Task Handle(BuySubscriptionCommand command, CancellationToken cancellationToken)
{
var priceList = await PriceListFactory.CreatePriceList(_sqlConnectionFactory.GetOpenConnection());
var subscription = SubscriptionPayment.Buy(
_payerContext.PayerId,
SubscriptionPeriod.Of(command.SubscriptionTypeCode),
command.CountryCode,
MoneyValue.Of(command.Value, command.Currency),
priceList);
_aggregateStore.AppendChanges(subscription);
return subscription.Id;
}
}
public static class PriceListFactory
{
public static async Task CreatePriceList(IDbConnection connection)
{
var priceListItemList = await GetPriceListItems(connection);
var priceListItems = priceListItemList
.Select(x =>
new PriceListItemData(
x.CountryCode,
SubscriptionPeriod.Of(x.SubscriptionPeriodCode),
MoneyValue.Of(x.MoneyValue, x.MoneyCurrency),
PriceListItemCategory.Of(x.CategoryCode)))
.ToList();
// This is place for selecting pricing strategy based on provided data and the system state.
IPricingStrategy pricingStrategy = new DirectValueFromPriceListPricingStrategy(priceListItems);
return PriceList.Create(
priceListItems,
pricingStrategy);
}
public static async Task> GetPriceListItems(IDbConnection connection)
{
var priceListItems = await connection.QueryAsync("SELECT " +
$"[PriceListItem].[CountryCode] AS [{nameof(PriceListItemDto.CountryCode)}], " +
$"[PriceListItem].[SubscriptionPeriodCode] AS [{nameof(PriceListItemDto.SubscriptionPeriodCode)}], " +
$"[PriceListItem].[MoneyValue] AS [{nameof(PriceListItemDto.MoneyValue)}], " +
$"[PriceListItem].[MoneyCurrency] AS [{nameof(PriceListItemDto.MoneyCurrency)}], " +
$"[PriceListItem].[CategoryCode] AS [{nameof(PriceListItemDto.CategoryCode)}] " +
"FROM [payments].[PriceListItems] AS [PriceListItem] " +
"WHERE [PriceListItem].[IsActive] = 1");
var priceListItemList = priceListItems.AsList();
return priceListItemList;
}
}
public class PriceList : ValueObject
{
private readonly List _items;
private readonly IPricingStrategy _pricingStrategy;
private PriceList(
List items,
IPricingStrategy pricingStrategy)
{
_items = items;
_pricingStrategy = pricingStrategy;
}
public static PriceList Create(
List items,
IPricingStrategy pricingStrategy)
{
return new PriceList(items, pricingStrategy);
}
public MoneyValue GetPrice(
string countryCode,
SubscriptionPeriod subscriptionPeriod,
PriceListItemCategory category)
{
CheckRule(new PriceForSubscriptionMustBeDefinedRule(countryCode, subscriptionPeriod, _items, category));
return _pricingStrategy.GetPrice(countryCode, subscriptionPeriod, category);
}
}
public interface IPricingStrategy
{
MoneyValue GetPrice(
string countryCode,
SubscriptionPeriod subscriptionPeriod,
PriceListItemCategory category);
}
public class DiscountedValueFromPriceListPricingStrategy : IPricingStrategy
{
private readonly List _items;
private readonly MoneyValue _discountValue;
public DiscountedValueFromPriceListPricingStrategy(
List items,
MoneyValue discountValue)
{
_items = items;
_discountValue = discountValue;
}
public MoneyValue GetPrice(string countryCode, SubscriptionPeriod subscriptionPeriod, PriceListItemCategory category)
{
var priceListItem = _items.Single(x =>
x.CountryCode == countryCode && x.SubscriptionPeriod == subscriptionPeriod &&
x.Category == category);
return priceListItem.Value - _discountValue;
}
}
public class DirectValuePricingStrategy : IPricingStrategy
{
private readonly MoneyValue _directValue;
public DirectValuePricingStrategy(MoneyValue directValue)
{
_directValue = directValue;
}
public MoneyValue GetPrice(string countryCode, SubscriptionPeriod subscriptionPeriod, PriceListItemCategory category)
{
return _directValue;
}
}
public class DirectValueFromPriceListPricingStrategy : IPricingStrategy
{
private readonly List _items;
public DirectValueFromPriceListPricingStrategy(List items)
{
_items = items;
}
public MoneyValue GetPrice(
string countryCode,
SubscriptionPeriod subscriptionPeriod,
PriceListItemCategory category)
{
var priceListItem = _items.Single(x =>
x.CountryCode == countryCode && x.SubscriptionPeriod == subscriptionPeriod &&
x.Category == category);
return priceListItem.Value;
}
}
```
### Description
Let's introduce the concepts of the strategy pattern, so we can understand how the above example fits this pattern.
* **Client** - The calling code.
* **Context** - An object which maintains a reference to one of the *concrete strategies* and communicates with the *client*.
* **Strategy interface** - An interface or abstract class that the *client* can use to set a concrete strategy at run-time, through the *context*.
* **Concrete strategies** - One or more implementations of the *strategy interface*.
---
If we have a close look at our example of buying a `Subscription`, we can notice the elements of the strategy pattern.
* `BuySubscriptionCommandHandler` is the calling code! Also the handler, indirectly via the `PriceListFactory` sets the current *strategy* of `PriceList`, so their combined interaction represents the **Client**.
* `PriceList` is the object which maintains a reference to a pricing strategy, so it represents the **Context**.
* `IPricingStrategy` represents the **Strategy interface**.
* `DiscountedValueFromPriceListPricingStrategy`, `DirectValueFromPriceListPricingStrategy` and `DirectValuePricingStrategy` are the implementations of `IPricingStrategy` so they represent the **Concrete strategies**.
---
The interaction of the `BuySubscriptionCommandHandler` and `PriceListFactory` is a good example of leveraging multiple design patterns. Check out [Factory Pattern](../Factory-Pattern/) to learn more.
Strategy should not be confused with [Decorator](../Decorator-Pattern/)!!!
*A strategy lets you change the guts of an object, while decorator lets you change the skin.*
================================================
FILE: docs/catalog-of-terms/Strategy-Pattern/strategy-pattern.puml
================================================
@startuml
package "Generic" #DDDDDD {
class Client {
- context
}
class Context {
- strategy
+ setStrategy(strategy)
+ do()
}
interface Strategy {
+ execute()
}
class ConcreteStrategyA {
+ execute()
}
class ConcreteStrategyB {
+ execute()
}
}
package "BuySubscription" #DDDDDD {
class BuySubscriptionCommandHandler {
- connection
- PriceListFactory.CreatePriceList(connection)
}
class PriceList {
- _pricingStrategy
+ Create(items, pricingStrategy)
+ GetPrice(countryCode, subscriptionPeriod, category)
}
interface IPricingStrategy {
+ GetPrice(countryCode, subscriptionPeriod, category)
}
class DirectValueFromPriceListPricingStrategy {
+ GetPrice(countryCode, subscriptionPeriod, category)
}
class DirectValuePricingStrategy {
+ GetPrice(countryCode, subscriptionPeriod, category)
}
class DiscountedValueFromPriceListPricingStrategy {
+ GetPrice(countryCode, subscriptionPeriod, category)
}
}
hide empty members
Client -down-|> Context
Context *-- Strategy
Strategy <|-- ConcreteStrategyA
Strategy <|-- ConcreteStrategyB
note left of Context::do
Calls strategy.execute()
end note
BuySubscriptionCommandHandler -down-> PriceList
PriceList *-- IPricingStrategy
IPricingStrategy <|-- DirectValueFromPriceListPricingStrategy
IPricingStrategy <|-- DirectValuePricingStrategy
IPricingStrategy <|-- DiscountedValueFromPriceListPricingStrategy
note left of PriceList::GetPrice
Calls _pricingStrategy.GetPrice(...)
end note
@enduml
================================================
FILE: docs/catalog-of-terms/ValueObject-DDD/README.md
================================================
# ValueObject (DDD)
## Definition
*When you care only about the attributes of an element of the model, classify it as a VALUE OBJECT. Make it express the meaning of the attributes it conveys and give it related functionality. Treat the VALUE OBJECT as immutable. Don't give it any identity and avoid the design complexities necessary to maintain ENTITIES.*
Source: [Domain-Driven Design: Tackling Complexity in the Heart of Software, Eric Evans](https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215)
## Example
### Model

### Code
```csharp
public class MoneyValue : ValueObject
{
public decimal Value { get; }
public string Currency { get; }
private MoneyValue(decimal value, string currency)
{
this.Value = value;
this.Currency = currency;
}
public static MoneyValue Of(decimal value, string currency)
{
CheckRule(new ValueOfMoneyMustNotBeNegativeRule(value));
return new MoneyValue(value, currency);
}
public static bool operator >(decimal left, MoneyValue right) => left > right.Value;
public static bool operator <(decimal left, MoneyValue right) => left < right.Value;
public static bool operator >=(decimal left, MoneyValue right) => left >= right.Value;
public static bool operator <=(decimal left, MoneyValue right) => left <= right.Value;
public static bool operator >(MoneyValue left, decimal right) => left.Value > right;
public static bool operator <(MoneyValue left, decimal right) => left.Value < right;
public static bool operator >=(MoneyValue left, decimal right) => left.Value >= right;
public static bool operator <=(MoneyValue left, decimal right) => left.Value <= right;
}
```
### Description
A *Money Value* class represents concept of money. In our Domain, we don't want to follow money in time (it does not have a life cycle). It does not have an identity either. Whole object is **immutable** (`Value` and `Currency` defined as readonly). The comparison is done by comparing attribute values, not identifiers (see `ValueObject` abstract class).
================================================
FILE: docs/catalog-of-terms/ValueObject-DDD/value-object-ddd.puml
================================================
@startuml ValueObject
class "MeetingGroup" << ValueObject >> {
decimal: Value {readonly}
string: Currency {readonly}
}
@enduml
================================================
FILE: docs/mutation-tests-reports/mutation-report.html
================================================
Your browser doesn't support custom elements.
Please use a latest version of an evergreen browser (Firefox, Chrome, Safari, Opera, etc).
================================================
FILE: runIntegrationTests.cmd
================================================
@ECHO OFF
SETLOCAL
SET CONTAINER_ID=
FOR /f %%i IN ('docker ps -q -f name^=myMeetings-integration-db') DO SET CONTAINER_ID=%%i
IF "%CONTAINER_ID%"=="" (
ECHO "not found"
) ELSE (
docker rm --force myMeetings-integration-db
)
docker run --rm --name myMeetings-integration-db -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=61cD4gE6!" -e "MSSQL_PID=Express" -p 1439:1433 -d mcr.microsoft.com/mssql/server:2017-latest-ubuntu
TIMEOUT 30
docker cp ./src/Database/CompanyName.MyMeetings.Database/Scripts/CreateDatabase_Linux.sql myMeetings-integration-db:/
docker exec -i myMeetings-integration-db sh -c "/opt/mssql-tools/bin/sqlcmd -d master -i /CreateDatabase_Linux.sql -U sa -P 61cD4gE6!"
dotnet build src/ --configuration Release --no-restore
SET ASPNETCORE_MyMeetings_IntegrationTests_ConnectionString=Server=localhost,1439;Database=MyMeetings;User=sa;Password=61cD4gE6!
dotnet "src/Database/DatabaseMigrator/bin/Release/netcoreapp3.1/DatabaseMigrator.dll" %ASPNETCORE_MyMeetings_IntegrationTests_ConnectionString% "src/Database/CompanyName.MyMeetings.Database/Scripts/Migrations"
dotnet test --configuration Release --no-build --verbosity normal src/Modules/Administration/Tests/IntegrationTests/CompanyName.MyMeetings.Modules.Administration.IntegrationTests.csproj
dotnet test --configuration Release --no-build --verbosity normal src/Modules/Payments/Tests/IntegrationTests/CompanyName.MyMeetings.Modules.Payments.IntegrationTests.csproj
dotnet test --configuration Release --no-build --verbosity normal src/Modules/UserAccess/Tests/IntegrationTests/CompanyNames.MyMeetings.Modules.UserAccess.IntegrationTests.csproj
dotnet test --configuration Release --no-build --verbosity normal src/Modules/Meetings/Tests/IntegrationTests/CompanyName.MyMeetings.Modules.Meetings.IntegrationTests.csproj
dotnet test --configuration Release --no-build --verbosity normal src/Tests/IntegrationTests/CompanyName.MyMeetings.IntegrationTests.csproj
================================================
FILE: src/.dockerignore
================================================
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
================================================
FILE: src/.editorconfig
================================================
[*.cs]
# SA1309: Field names should not begin with underscore
dotnet_diagnostic.SA1309.severity = none
# SA1600: Elements should be documented
dotnet_diagnostic.SA1600.severity = none
# SA1633: File should have header
dotnet_diagnostic.SA1633.severity = none
# SA1200: Using directives should be placed correctly
dotnet_diagnostic.SA1200.severity = none
# SA1402: File may only contain a single type
dotnet_diagnostic.SA1402.severity = suggestion
# SA1101: Prefix local calls with this
dotnet_diagnostic.SA1101.severity = none
# SA0001: All diagnostics of XML documentation comments has been disabled due to the current project configuration.
dotnet_diagnostic.SA0001.severity = none
# SA1201: Elements should appear in the correct order
dotnet_diagnostic.SA1201.severity = none
# SA1204: Static elements should appear before instance elements
dotnet_diagnostic.SA1204.severity = none
# SA1413: Use trailing comma in multi-line initializers
dotnet_diagnostic.SA1413.severity = none
# SA1623: Property summary documentation should match accessors
dotnet_diagnostic.SA1623.severity = none
================================================
FILE: src/API/CompanyName.MyMeetings.API/CompanyName.MyMeetings.API.csproj
================================================
true
InProcess
2b9855d3-f073-44d2-aa45-b15e896794b9
Linux
..\..
bin\Debug\CompanyName.MyMeetings.API.xml
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Authorization/AttributeAuthorizationHandler.cs
================================================
using Microsoft.AspNetCore.Authorization;
namespace CompanyName.MyMeetings.API.Configuration.Authorization
{
public abstract class AttributeAuthorizationHandler
: AuthorizationHandler
where TRequirement : IAuthorizationRequirement
where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var endpoint = (context.Resource as HttpContext).GetEndpoint() as RouteEndpoint;
var attribute = endpoint?.Metadata.GetMetadata();
return HandleRequirementAsync(context, requirement, attribute);
}
protected abstract Task HandleRequirementAsync(
AuthorizationHandlerContext context,
TRequirement requirement,
TAttribute attribute);
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Authorization/AuthorizationChecker.cs
================================================
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Configuration.Authorization
{
public static class AuthorizationChecker
{
public static void CheckAllEndpoints()
{
var assembly = typeof(Startup).Assembly;
var allControllerTypes = assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(ControllerBase)));
List notProtectedActionMethods = [];
foreach (var controllerType in allControllerTypes)
{
var controllerHasPermissionAttribute = controllerType.GetCustomAttribute();
if (controllerHasPermissionAttribute != null)
{
continue;
}
var actionMethods = controllerType.GetMethods()
.Where(x => x.IsPublic && x.DeclaringType == controllerType)
.ToList();
foreach (var publicMethod in actionMethods)
{
var hasPermissionAttribute = publicMethod.GetCustomAttribute();
if (hasPermissionAttribute == null)
{
var noPermissionRequired = publicMethod.GetCustomAttribute();
if (noPermissionRequired == null)
{
notProtectedActionMethods.Add($"{controllerType.Name}.{publicMethod.Name}");
}
}
}
}
if (notProtectedActionMethods.Any())
{
var errorBuilder = new StringBuilder();
errorBuilder.AppendLine("Invalid authorization configuration: ");
foreach (var notProtectedActionMethod in notProtectedActionMethods)
{
errorBuilder.AppendLine($"Method {notProtectedActionMethod} is not protected. ");
}
throw new ApplicationException(errorBuilder.ToString());
}
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Authorization/HasPermissionAttribute.cs
================================================
using Microsoft.AspNetCore.Authorization;
namespace CompanyName.MyMeetings.API.Configuration.Authorization
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
internal class HasPermissionAttribute : AuthorizeAttribute
{
internal const string HasPermissionPolicyName = "HasPermission";
public HasPermissionAttribute(string name)
: base(HasPermissionPolicyName)
{
Name = name;
}
public string Name { get; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Authorization/HasPermissionAuthorizationHandler.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Application;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Authorization.GetUserPermissions;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Contracts;
using Microsoft.AspNetCore.Authorization;
namespace CompanyName.MyMeetings.API.Configuration.Authorization
{
internal class HasPermissionAuthorizationHandler : AttributeAuthorizationHandler<
HasPermissionAuthorizationRequirement, HasPermissionAttribute>
{
private readonly IExecutionContextAccessor _executionContextAccessor;
private readonly IUserAccessModule _userAccessModule;
public HasPermissionAuthorizationHandler(
IExecutionContextAccessor executionContextAccessor,
IUserAccessModule userAccessModule)
{
_executionContextAccessor = executionContextAccessor;
_userAccessModule = userAccessModule;
}
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context,
HasPermissionAuthorizationRequirement requirement,
HasPermissionAttribute attribute)
{
var permissions = await _userAccessModule.ExecuteQueryAsync(new GetUserPermissionsQuery(_executionContextAccessor.UserId));
if (!await AuthorizeAsync(attribute.Name, permissions))
{
context.Fail();
return;
}
context.Succeed(requirement);
}
private Task AuthorizeAsync(string permission, List permissions)
{
#if !DEBUG
return Task.FromResult(true);
#endif
#pragma warning disable CS0162 // Unreachable code detected
return Task.FromResult(permissions.Any(x => x.Code == permission));
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Authorization/HasPermissionAuthorizationRequirement.cs
================================================
using Microsoft.AspNetCore.Authorization;
namespace CompanyName.MyMeetings.API.Configuration.Authorization
{
public class HasPermissionAuthorizationRequirement : IAuthorizationRequirement
{
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Authorization/NoPermissionRequiredAttribute.cs
================================================
namespace CompanyName.MyMeetings.API.Configuration.Authorization
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class NoPermissionRequiredAttribute : Attribute
{
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/ExecutionContext/CorrelationMiddleware.cs
================================================
namespace CompanyName.MyMeetings.API.Configuration.ExecutionContext
{
internal class CorrelationMiddleware
{
internal const string CorrelationHeaderKey = "CorrelationId";
private readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var correlationId = Guid.NewGuid();
context.Request?.Headers.Append(CorrelationHeaderKey, correlationId.ToString());
await _next.Invoke(context);
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/ExecutionContext/ExecutionContextAccessor.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Application;
namespace CompanyName.MyMeetings.API.Configuration.ExecutionContext
{
public class ExecutionContextAccessor : IExecutionContextAccessor
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ExecutionContextAccessor(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public Guid UserId
{
get
{
if (_httpContextAccessor
.HttpContext?
.User?
.Claims?
.SingleOrDefault(x => x.Type == "sub")?
.Value != null)
{
return Guid.Parse(_httpContextAccessor.HttpContext.User.Claims.Single(
x => x.Type == "sub").Value);
}
throw new ApplicationException("User context is not available");
}
}
public Guid CorrelationId
{
get
{
if (IsAvailable && _httpContextAccessor.HttpContext.Request.Headers.Keys.Any(
x => x == CorrelationMiddleware.CorrelationHeaderKey))
{
return Guid.Parse(
_httpContextAccessor.HttpContext.Request.Headers[CorrelationMiddleware.CorrelationHeaderKey]);
}
throw new ApplicationException("Http context and correlation id is not available");
}
}
public bool IsAvailable => _httpContextAccessor.HttpContext != null;
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Extensions/SwaggerExtensions.cs
================================================
using System.Reflection;
using Microsoft.OpenApi.Models;
namespace CompanyName.MyMeetings.API.Configuration.Extensions
{
internal static class SwaggerExtensions
{
internal static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services)
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "MyMeetings API",
Version = "v1",
Description = "MyMeetings API for modular monolith .NET application."
});
options.CustomSchemaIds(t => t.ToString());
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var commentsFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var commentsFile = Path.Combine(baseDirectory, commentsFileName);
options.IncludeXmlComments(commentsFile);
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description =
"JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List()
}
});
});
return services;
}
internal static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyMeetings API"); });
return app;
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Validation/BusinessRuleValidationExceptionProblemDetails.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Domain;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Configuration.Validation
{
public class BusinessRuleValidationExceptionProblemDetails : ProblemDetails
{
public BusinessRuleValidationExceptionProblemDetails(BusinessRuleValidationException exception)
{
Title = "Business rule broken";
Status = StatusCodes.Status409Conflict;
Detail = exception.Message;
Type = "https://somedomain/business-rule-validation-error";
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Configuration/Validation/InvalidCommandProblemDetails.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Application;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Configuration.Validation
{
public class InvalidCommandProblemDetails : ProblemDetails
{
public InvalidCommandProblemDetails(InvalidCommandException exception)
{
Title = "Command validation error";
Status = StatusCodes.Status400BadRequest;
Type = "https://somedomain/validation-error";
Errors = exception.Errors;
}
public List Errors { get; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Administration/AdministrationAutofacModule.cs
================================================
using Autofac;
using CompanyName.MyMeetings.Modules.Administration.Application.Contracts;
using CompanyName.MyMeetings.Modules.Administration.Infrastructure;
namespace CompanyName.MyMeetings.API.Modules.Administration
{
internal class AdministrationAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType()
.As()
.InstancePerLifetimeScope();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Administration/AdministrationPermissions.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Administration
{
public class AdministrationPermissions
{
public const string AcceptMeetingGroupProposal = "AcceptMeetingGroupProposal";
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Administration/MeetingGroupProposals/MeetingGroupProposalsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Administration.Application.Contracts;
using CompanyName.MyMeetings.Modules.Administration.Application.MeetingGroupProposals.AcceptMeetingGroupProposal;
using CompanyName.MyMeetings.Modules.Administration.Application.MeetingGroupProposals.GetMeetingGroupProposal;
using CompanyName.MyMeetings.Modules.Administration.Application.MeetingGroupProposals.GetMeetingGroupProposals;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Administration.MeetingGroupProposals
{
[Route("api/administration/meetingGroupProposals")]
[ApiController]
public class MeetingGroupProposalsController : ControllerBase
{
private readonly IAdministrationModule _administrationModule;
public MeetingGroupProposalsController(IAdministrationModule administrationModule)
{
_administrationModule = administrationModule;
}
[HttpGet("")]
[HasPermission(AdministrationPermissions.AcceptMeetingGroupProposal)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetMeetingGroupProposals()
{
var meetingGroupProposals =
await _administrationModule.ExecuteQueryAsync(new GetMeetingGroupProposalsQuery());
return Ok(meetingGroupProposals);
}
[HttpPatch("{meetingGroupProposalId}/accept")]
[HasPermission(AdministrationPermissions.AcceptMeetingGroupProposal)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task AcceptMeetingGroupProposal(Guid meetingGroupProposalId)
{
await _administrationModule.ExecuteCommandAsync(
new AcceptMeetingGroupProposalCommand(meetingGroupProposalId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Countries/CountriesController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Meetings.Application.Contracts;
using CompanyName.MyMeetings.Modules.Meetings.Application.Countries;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Meetings.Countries
{
[Route("api/meetings/countries")]
[ApiController]
public class CountriesController : ControllerBase
{
private readonly IMeetingsModule _meetingsModule;
public CountriesController(IMeetingsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpGet("")]
[HasPermission(MeetingsPermissions.GetMeetingGroupProposals)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetAllCountries(int? page, int? perPage)
{
var countries = await _meetingsModule.ExecuteQueryAsync(
new GetAllCountriesQuery());
return Ok(countries);
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingCommentingConfiguration/MeetingCommentingConfigurationController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Meetings.Application.Contracts;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingCommentingConfigurations.DisableMeetingCommentingConfiguration;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingCommentingConfigurations.EnableMeetingCommentingConfiguration;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingCommentingConfiguration
{
[Route("api/meetings/meetings/{meetingId}/configuration/commenting")]
[ApiController]
public class MeetingCommentingConfigurationController : ControllerBase
{
private readonly IMeetingsModule _meetingsModule;
public MeetingCommentingConfigurationController(IMeetingsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpPatch("disable")]
[HasPermission(MeetingsPermissions.DisableMeetingCommenting)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task DisableCommenting(Guid meetingId)
{
await _meetingsModule.ExecuteCommandAsync(new DisableMeetingCommentingConfigurationCommand(meetingId));
return Ok();
}
[HttpPatch("enable")]
[HasPermission(MeetingsPermissions.EnableMeetingCommenting)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task EnableCommenting(Guid meetingId)
{
await _meetingsModule.ExecuteCommandAsync(new EnableMeetingCommentingConfigurationCommand(meetingId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingComments/AddMeetingCommentRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingComments
{
public class AddMeetingCommentRequest
{
public Guid MeetingId { get; set; }
public string Comment { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingComments/EditMeetingCommentRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingComments
{
public class EditMeetingCommentRequest
{
public string EditedComment { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingComments/MeetingCommentsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Meetings.Application.Contracts;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingComments.AddMeetingComment;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingComments.AddMeetingCommentLike;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingComments.AddMeetingCommentReply;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingComments.EditMeetingComment;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingComments.RemoveMeetingComment;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingComments.RemoveMeetingCommentLike;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingComments
{
[Route("api/meetings/[controller]")]
[ApiController]
public class MeetingCommentsController : ControllerBase
{
private readonly IMeetingsModule _meetingModule;
public MeetingCommentsController(IMeetingsModule meetingModule)
{
_meetingModule = meetingModule;
}
[HttpPost]
[HasPermission(MeetingsPermissions.AddMeetingComment)]
[ProducesResponseType(typeof(Guid), StatusCodes.Status200OK)]
public async Task AddComment([FromBody] AddMeetingCommentRequest request)
{
var commentId =
await _meetingModule.ExecuteCommandAsync(new AddMeetingCommentCommand(
request.MeetingId,
request.Comment));
return Ok(commentId);
}
[HttpPut("{meetingCommentId}")]
[HasPermission(MeetingsPermissions.EditMeetingComment)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task EditComment(
[FromRoute] Guid meetingCommentId,
[FromBody] EditMeetingCommentRequest request)
{
await _meetingModule.ExecuteCommandAsync(new EditMeetingCommentCommand(
meetingCommentId,
request.EditedComment));
return Ok();
}
[HttpDelete("{meetingCommentId}")]
[HasPermission(MeetingsPermissions.RemoveMeetingComment)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task DeleteComment([FromRoute] Guid meetingCommentId, [FromQuery] string reason)
{
await _meetingModule.ExecuteCommandAsync(
new RemoveMeetingCommentCommand(meetingCommentId, reason));
return Ok();
}
[HttpPost("{meetingCommentId}/replies")]
[HasPermission(MeetingsPermissions.AddMeetingCommentReply)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task AddReply([FromRoute] Guid meetingCommentId, [FromBody] string reply)
{
await _meetingModule.ExecuteCommandAsync(new AddReplyToMeetingCommentCommand(meetingCommentId, reply));
return Ok();
}
[HttpPost("{meetingCommentId}/likes")]
[HasPermission(MeetingsPermissions.LikeMeetingComment)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task LikeComment([FromRoute] Guid meetingCommentId)
{
await _meetingModule.ExecuteCommandAsync(
new AddMeetingCommentLikeCommand(meetingCommentId));
return Ok();
}
[HttpDelete("{meetingCommentId}/likes")]
[HasPermission(MeetingsPermissions.UnlikeMeetingComment)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task UnlikeComment([FromRoute] Guid meetingCommentId)
{
await _meetingModule.ExecuteCommandAsync(
new RemoveMeetingCommentLikeCommand(meetingCommentId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingGroupProposals/MeetingGroupProposalsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Meetings.Application.Contracts;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroupProposals.GetAllMeetingGroupProposals;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroupProposals.GetMeetingGroupProposal;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroupProposals.GetMemberMeetingGroupProposals;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroupProposals.ProposeMeetingGroup;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingGroupProposals
{
[Route("api/meetings/[controller]")]
[ApiController]
public class MeetingGroupProposalsController : ControllerBase
{
private readonly IMeetingsModule _meetingsModule;
public MeetingGroupProposalsController(IMeetingsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpGet("")]
[HasPermission(MeetingsPermissions.GetMeetingGroupProposals)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetMemberMeetingGroupProposals()
{
var meetingGroupProposals = await _meetingsModule.ExecuteQueryAsync(
new GetMemberMeetingGroupProposalsQuery());
return Ok(meetingGroupProposals);
}
[HttpGet("all")]
[HasPermission(MeetingsPermissions.GetMeetingGroupProposals)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetAllMeetingGroupProposals(int? page, int? perPage)
{
var meetingGroupProposals = await _meetingsModule.ExecuteQueryAsync(
new GetAllMeetingGroupProposalsQuery(page, perPage));
return Ok(meetingGroupProposals);
}
[HttpPost("")]
[HasPermission(MeetingsPermissions.ProposeMeetingGroup)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task ProposeMeetingGroup(ProposeMeetingGroupRequest request)
{
await _meetingsModule.ExecuteCommandAsync(
new ProposeMeetingGroupCommand(
request.Name,
request.Description,
request.LocationCity,
request.LocationCountryCode));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingGroupProposals/ProposeMeetingGroupRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingGroupProposals
{
public class ProposeMeetingGroupRequest
{
public string Name { get; set; }
public string Description { get; set; }
public string LocationCity { get; set; }
public string LocationCountryCode { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingGroups/CreateNewMeetingGroupRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingGroups
{
public class CreateNewMeetingGroupRequest
{
public string Name { get; set; }
public string Description { get; set; }
public string LocationCity { get; set; }
public string LocationCountry { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingGroups/EditMeetingGroupGeneralAttributesRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingGroups
{
public class EditMeetingGroupGeneralAttributesRequest
{
public string Name { get; set; }
public string Description { get; set; }
public string LocationCity { get; set; }
public string LocationCountry { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingGroups/MeetingGroupsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Meetings.Application.Contracts;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroups.EditMeetingGroupGeneralAttributes;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroups.GetAllMeetingGroups;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroups.GetAuthenticationMemberMeetingGroups;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroups.GetMeetingGroupDetails;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroups.JoinToGroup;
using CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroups.LeaveMeetingGroup;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Meetings.MeetingGroups
{
[Route("api/meetings/[controller]")]
[ApiController]
public class MeetingGroupsController : ControllerBase
{
private readonly IMeetingsModule _meetingsModule;
public MeetingGroupsController(IMeetingsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpGet("")]
[HasPermission(MeetingsPermissions.GetAuthenticatedMemberMeetingGroups)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetAuthenticatedMemberMeetingGroups()
{
var meetingGroups = await _meetingsModule.ExecuteQueryAsync(
new GetAuthenticationMemberMeetingGroupsQuery());
return Ok(meetingGroups);
}
[HttpGet("{meetingGroupId}")]
[HasPermission(MeetingsPermissions.GetMeetingGroupDetails)]
[ProducesResponseType(typeof(MeetingGroupDetailsDto), StatusCodes.Status200OK)]
public async Task GetMeetingGroupDetails(Guid meetingGroupId)
{
var meetingGroupDetails = await _meetingsModule.ExecuteQueryAsync(
new GetMeetingGroupDetailsQuery(meetingGroupId));
return Ok(meetingGroupDetails);
}
[HttpGet("all")]
[HasPermission(MeetingsPermissions.GetAllMeetingGroups)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetAllMeetingGroups()
{
var meetingGroups = await _meetingsModule.ExecuteQueryAsync(new GetAllMeetingGroupsQuery());
return Ok(meetingGroups);
}
[HttpPut("{meetingGroupId}")]
[HasPermission(MeetingsPermissions.EditMeetingGroupGeneralAttributes)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task EditMeetingGroupGeneralAttributes(
[FromRoute] Guid meetingGroupId,
[FromBody] EditMeetingGroupGeneralAttributesRequest request)
{
await _meetingsModule.ExecuteCommandAsync(new EditMeetingGroupGeneralAttributesCommand(
meetingGroupId,
request.Name,
request.Description,
request.LocationCity,
request.LocationCountry));
return Ok();
}
[HttpPost("{meetingGroupId}/members")]
[HasPermission(MeetingsPermissions.JoinToGroup)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task JoinToGroup(Guid meetingGroupId)
{
await _meetingsModule.ExecuteCommandAsync(new JoinToGroupCommand(meetingGroupId));
return Ok();
}
[HttpDelete("{meetingGroupId}/members")]
[HasPermission(MeetingsPermissions.LeaveMeetingGroup)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task LeaveMeetingGroup(Guid meetingGroupId)
{
await _meetingsModule.ExecuteCommandAsync(new LeaveMeetingGroupCommand(meetingGroupId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Meetings/AddMeetingAttendeeRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.Meetings
{
public class AddMeetingAttendeeRequest
{
public int GuestsNumber { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Meetings/ChangeMeetingMainAttributesRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.Meetings
{
public class ChangeMeetingMainAttributesRequest
{
public Guid MeetingId { get; set; }
public string Title { get; set; }
public DateTime TermStartDate { get; set; }
public DateTime TermEndDate { get; set; }
public string Description { get; set; }
public string MeetingLocationName { get; set; }
public string MeetingLocationAddress { get; set; }
public string MeetingLocationPostalCode { get; set; }
public string MeetingLocationCity { get; set; }
public int? AttendeesLimit { get; set; }
public int GuestsLimit { get; set; }
public DateTime? RSVPTermStartDate { get; set; }
public DateTime? RSVPTermEndDate { get; set; }
public decimal? EventFeeValue { get; set; }
public string EventFeeCurrency { get; set; }
public List HostMemberIds { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Meetings/CreateMeetingRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.Meetings
{
public class CreateMeetingRequest
{
public Guid MeetingGroupId { get; set; }
public string Title { get; set; }
public DateTime TermStartDate { get; set; }
public DateTime TermEndDate { get; set; }
public string Description { get; set; }
public string MeetingLocationName { get; set; }
public string MeetingLocationAddress { get; set; }
public string MeetingLocationPostalCode { get; set; }
public string MeetingLocationCity { get; set; }
public int? AttendeesLimit { get; set; }
public int GuestsLimit { get; set; }
public DateTime? RSVPTermStartDate { get; set; }
public DateTime? RSVPTermEndDate { get; set; }
public decimal? EventFeeValue { get; set; }
public string EventFeeCurrency { get; set; }
public List HostMemberIds { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Meetings/MeetingsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Meetings.Application.Contracts;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.AddMeetingAttendee;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.AddMeetingNotAttendee;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.CancelMeeting;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.ChangeMeetingMainAttributes;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.ChangeNotAttendeeDecision;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.CreateMeeting;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.GetAuthenticatedMemberMeetings;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.GetMeetingAttendees;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.GetMeetingDetails;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.RemoveMeetingAttendee;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.SetMeetingAttendeeRole;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.SetMeetingHostRole;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.SignOffMemberFromWaitlist;
using CompanyName.MyMeetings.Modules.Meetings.Application.Meetings.SignUpMemberToWaitlist;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Meetings.Meetings
{
[Route("api/meetings/meetings")]
[ApiController]
public class MeetingsController : ControllerBase
{
private readonly IMeetingsModule _meetingsModule;
public MeetingsController(IMeetingsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpGet("")]
[HasPermission(MeetingsPermissions.GetAuthenticatedMemberMeetings)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetAuthenticatedMemberMeetings()
{
var meetings = await _meetingsModule.ExecuteQueryAsync(new GetAuthenticatedMemberMeetingsQuery());
return Ok(meetings);
}
[HttpGet("{meetingId}")]
[HasPermission(MeetingsPermissions.GetMeetingDetails)]
[ProducesResponseType(typeof(MeetingDetailsDto), StatusCodes.Status200OK)]
public async Task GetMeetingDetails(Guid meetingId)
{
var meetingDetails = await _meetingsModule.ExecuteQueryAsync(new GetMeetingDetailsQuery(meetingId));
return Ok(meetingDetails);
}
[HttpPost("")]
[HasPermission(MeetingsPermissions.CreateNewMeeting)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task CreateNewMeeting([FromBody] CreateMeetingRequest request)
{
await _meetingsModule.ExecuteCommandAsync(new CreateMeetingCommand(
request.MeetingGroupId,
request.Title,
request.TermStartDate,
request.TermEndDate,
request.Description,
request.MeetingLocationName,
request.MeetingLocationAddress,
request.MeetingLocationPostalCode,
request.MeetingLocationCity,
request.AttendeesLimit,
request.GuestsLimit,
request.RSVPTermStartDate,
request.RSVPTermEndDate,
request.EventFeeValue,
request.EventFeeCurrency,
request.HostMemberIds));
return Ok();
}
[HttpPut("{meetingId}")]
[HasPermission(MeetingsPermissions.EditMeeting)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task EditMeeting(
[FromRoute] Guid meetingId,
[FromBody] ChangeMeetingMainAttributesRequest mainAttributesRequest)
{
await _meetingsModule.ExecuteCommandAsync(new ChangeMeetingMainAttributesCommand(
meetingId,
mainAttributesRequest.Title,
mainAttributesRequest.TermStartDate,
mainAttributesRequest.TermEndDate,
mainAttributesRequest.Description,
mainAttributesRequest.MeetingLocationName,
mainAttributesRequest.MeetingLocationAddress,
mainAttributesRequest.MeetingLocationPostalCode,
mainAttributesRequest.MeetingLocationCity,
mainAttributesRequest.AttendeesLimit,
mainAttributesRequest.GuestsLimit,
mainAttributesRequest.RSVPTermStartDate,
mainAttributesRequest.RSVPTermEndDate,
mainAttributesRequest.EventFeeValue,
mainAttributesRequest.EventFeeCurrency));
return Ok();
}
[HttpGet("{meetingId}/attendees")]
[HasPermission(MeetingsPermissions.GetMeetingAttendees)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetMeetingAttendees(Guid meetingId)
{
var meetingAttendees = await _meetingsModule.ExecuteQueryAsync(new GetMeetingAttendeesQuery(meetingId));
return Ok(meetingAttendees);
}
[HttpPost("{meetingId}/attendees")]
[HasPermission(MeetingsPermissions.AddMeetingAttendee)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task AddMeetingAttendee(
[FromRoute] Guid meetingId,
[FromBody] AddMeetingAttendeeRequest attendeeRequest)
{
await _meetingsModule.ExecuteCommandAsync(new AddMeetingAttendeeCommand(
meetingId,
attendeeRequest.GuestsNumber));
return Ok();
}
[HttpDelete("{meetingId}/attendees/{attendeeId}")]
[HasPermission(MeetingsPermissions.RemoveMeetingAttendee)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task RemoveMeetingAttendee(
Guid meetingId,
Guid attendeeId,
RemoveMeetingAttendeeRequest request)
{
await _meetingsModule.ExecuteCommandAsync(
new RemoveMeetingAttendeeCommand(meetingId, attendeeId, request.RemovingReason));
return Ok();
}
[HttpPost("{meetingId}/notAttendees")]
[HasPermission(MeetingsPermissions.AddNotAttendee)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task AddNotAttendee(Guid meetingId)
{
await _meetingsModule.ExecuteCommandAsync(new AddMeetingNotAttendeeCommand(meetingId));
return Ok();
}
[HttpDelete("{meetingId}/notAttendees")]
[HasPermission(MeetingsPermissions.ChangeNotAttendeeDecision)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task ChangeNotAttendeeDecision(Guid meetingId)
{
await _meetingsModule.ExecuteCommandAsync(new ChangeNotAttendeeDecisionCommand(meetingId));
return Ok();
}
[HttpPost("{meetingId}/waitlistMembers")]
[HasPermission(MeetingsPermissions.SignUpMemberToWaitlist)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task SignUpMemberToWaitlist(Guid meetingId)
{
await _meetingsModule.ExecuteCommandAsync(new SignUpMemberToWaitlistCommand(meetingId));
return Ok();
}
[HttpDelete("{meetingId}/waitlistMembers")]
[HasPermission(MeetingsPermissions.SignOffMemberFromWaitlist)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task SignOffMemberFromWaitlist(Guid meetingId)
{
await _meetingsModule.ExecuteCommandAsync(new SignOffMemberFromWaitlistCommand(meetingId));
return Ok();
}
[HttpPost("{meetingId}/hosts")]
[HasPermission(MeetingsPermissions.SetMeetingHostRole)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task SetMeetingHostRole(Guid meetingId, SetMeetingHostRequest request)
{
await _meetingsModule.ExecuteCommandAsync(new SetMeetingHostRoleCommand(request.AttendeeId, meetingId));
return Ok();
}
[HttpPost("{meetingId}/attendees/attendeeRole")]
[HasPermission(MeetingsPermissions.SetMeetingAttendeeRole)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task SetMeetingAttendeeRole(Guid meetingId, SetMeetingHostRequest request)
{
await _meetingsModule.ExecuteCommandAsync(new SetMeetingAttendeeRoleCommand(request.AttendeeId, meetingId));
return Ok();
}
[HttpPatch("{meetingId}/cancel")]
[HasPermission(MeetingsPermissions.CancelMeeting)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task CancelMeeting(Guid meetingId)
{
await _meetingsModule.ExecuteCommandAsync(new CancelMeetingCommand(meetingId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Meetings/RemoveMeetingAttendeeRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.Meetings
{
public class RemoveMeetingAttendeeRequest
{
public string RemovingReason { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Meetings/SetMeetingAttendeeRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.Meetings
{
public class SetMeetingAttendeeRequest
{
public Guid AttendeeId { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/Meetings/SetMeetingHostRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings.Meetings
{
public class SetMeetingHostRequest
{
public Guid AttendeeId { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingsAutofacModule.cs
================================================
using Autofac;
using CompanyName.MyMeetings.Modules.Meetings.Application.Contracts;
using CompanyName.MyMeetings.Modules.Meetings.Infrastructure;
namespace CompanyName.MyMeetings.API.Modules.Meetings
{
public class MeetingsAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType()
.As()
.InstancePerLifetimeScope();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Meetings/MeetingsPermissions.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Meetings
{
public class MeetingsPermissions
{
public const string GetMeetingGroupProposals = "GetMeetingGroupProposals";
public const string ProposeMeetingGroup = "ProposeMeetingGroup";
public const string CreateNewMeeting = "CreateNewMeeting";
public const string EditMeeting = "EditMeeting";
public const string AddMeetingAttendee = "AddMeetingAttendee";
public const string RemoveMeetingAttendee = "RemoveMeetingAttendee";
public const string AddNotAttendee = "AddNotAttendee";
public const string ChangeNotAttendeeDecision = "ChangeNotAttendeeDecision";
public const string SignUpMemberToWaitlist = "SignUpMemberToWaitlist";
public const string SignOffMemberFromWaitlist = "SignOffMemberFromWaitlist";
public const string SetMeetingHostRole = "SetMeetingHostRole";
public const string SetMeetingAttendeeRole = "SetMeetingAttendeeRole";
public const string CancelMeeting = "CancelMeeting";
public const string GetAllMeetingGroups = "GetAllMeetingGroups";
public const string EditMeetingGroupGeneralAttributes = "EditMeetingGroupGeneralAttributes";
public const string JoinToGroup = "JoinToGroup";
public const string LeaveMeetingGroup = "LeaveMeetingGroup";
public const string AddMeetingComment = "AddMeetingComment";
public const string EditMeetingComment = "EditMeetingComment";
public const string RemoveMeetingComment = "RemoveMeetingComment";
public const string AddMeetingCommentReply = "AddMeetingCommentReply";
public const string LikeMeetingComment = "LikeMeetingComment";
public const string UnlikeMeetingComment = "UnlikeMeetingComment";
public const string EnableMeetingCommenting = "EnableMeetingCommenting";
public const string DisableMeetingCommenting = "DisableMeetingCommenting";
public const string GetAuthenticatedMemberMeetingGroups = "GetAuthenticatedMemberMeetingGroups";
public const string GetMeetingGroupDetails = "GetMeetingGroupDetails";
public const string GetMeetingDetails = "GetMeetingDetails";
public const string GetAuthenticatedMemberMeetings = "GetAuthenticatedMemberMeetings";
public const string GetMeetingAttendees = "GetMeetingAttendees";
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/MeetingFees/CreateMeetingFeePaymentRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.MeetingFees
{
public class CreateMeetingFeePaymentRequest
{
public Guid MeetingFeeId { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/MeetingFees/MeetingFeePaymentsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Payments.Application.Contracts;
using CompanyName.MyMeetings.Modules.Payments.Application.MeetingFees.CreateMeetingFeePayment;
using CompanyName.MyMeetings.Modules.Payments.Application.MeetingFees.MarkMeetingFeePaymentAsPaid;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Payments.MeetingFees
{
[Route("api/payments/meetingFeePayments")]
[ApiController]
public class MeetingFeePaymentsController : ControllerBase
{
private readonly IPaymentsModule _meetingsModule;
public MeetingFeePaymentsController(IPaymentsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpPost]
[HasPermission(PaymentsPermissions.RegisterPayment)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task CreateMeetingFeePayment(CreateMeetingFeePaymentRequest request)
{
await _meetingsModule.ExecuteCommandAsync(new CreateMeetingFeePaymentCommand(request.MeetingFeeId));
return Ok();
}
[HttpPut]
[Route("{meetingFeePaymentId}/purchased")]
[HasPermission(PaymentsPermissions.RegisterPayment)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task RegisterMeetingFeePayment(
Guid meetingFeePaymentId)
{
await _meetingsModule.ExecuteCommandAsync(new MarkMeetingFeePaymentAsPaidCommand(meetingFeePaymentId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/MeetingFees/RegisterMeetingFeePaymentRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.MeetingFees
{
public class RegisterMeetingFeePaymentRequest
{
public Guid PaymentId { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/Payers/PayersController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Payments.Application.Contracts;
using CompanyName.MyMeetings.Modules.Payments.Application.Subscriptions.GetPayerSubscription;
using CompanyName.MyMeetings.Modules.Payments.Application.Subscriptions.GetSubscriptionDetails;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Payments.Payers
{
[Route("api/payments/payers")]
[ApiController]
public class PayersController : ControllerBase
{
private readonly IPaymentsModule _paymentsModule;
public PayersController(IPaymentsModule paymentsModule)
{
_paymentsModule = paymentsModule;
}
[HttpGet("authenticated/subscription")]
[HasPermission(PaymentsPermissions.GetAuthenticatedPayerSubscription)]
[ProducesResponseType(typeof(SubscriptionDetailsDto), StatusCodes.Status200OK)]
public async Task GetAuthenticatedPayerSubscription()
{
var subscription = await _paymentsModule.ExecuteQueryAsync(new GetAuthenticatedPayerSubscriptionQuery());
return Ok(subscription);
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/PaymentsAutofacModule.cs
================================================
using Autofac;
using CompanyName.MyMeetings.Modules.Payments.Application.Contracts;
using CompanyName.MyMeetings.Modules.Payments.Infrastructure;
namespace CompanyName.MyMeetings.API.Modules.Payments
{
public class PaymentsAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType()
.As()
.InstancePerLifetimeScope();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/PaymentsPermissions.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments
{
public class PaymentsPermissions
{
public const string RegisterPayment = "RegisterPayment";
public const string BuySubscription = "BuySubscription";
public const string RenewSubscription = "RenewSubscription";
public const string CreatePriceListItem = "CreatePriceListItem";
public const string ActivatePriceListItem = "ActivatePriceListItem";
public const string DeactivatePriceListItem = "DeactivatePriceListItem";
public const string ChangePriceListItemAttributes = "ChangePriceListItemAttributes";
public const string GetAuthenticatedPayerSubscription = "GetAuthenticatedPayerSubscription";
public const string GetPriceListItem = "GetPriceListItem";
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/PriceListItems/ChangePriceListItemAttributesRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.PriceListItems
{
public class ChangePriceListItemAttributesRequest
{
public Guid PriceListItemId { get; set; }
public string CountryCode { get; set; }
public string SubscriptionPeriodCode { get; set; }
public string CategoryCode { get; set; }
public decimal PriceValue { get; set; }
public string PriceCurrency { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/PriceListItems/CreatePriceListItemRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.PriceListItems
{
public class CreatePriceListItemRequest
{
public string CountryCode { get; set; }
public string SubscriptionPeriodCode { get; set; }
public string CategoryCode { get; set; }
public decimal PriceValue { get; set; }
public string PriceCurrency { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/PriceListItems/GetPriceListItemRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.PriceListItems
{
public class GetPriceListItemRequest
{
public string CountryCode { get; set; }
public string CategoryCode { get; set; }
public string PeriodTypeCode { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/PriceListItems/PriceListItemsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Payments.Application.Contracts;
using CompanyName.MyMeetings.Modules.Payments.Application.PriceListItems.ActivatePriceListItem;
using CompanyName.MyMeetings.Modules.Payments.Application.PriceListItems.ChangePriceListItemAttributes;
using CompanyName.MyMeetings.Modules.Payments.Application.PriceListItems.CreatePriceListItem;
using CompanyName.MyMeetings.Modules.Payments.Application.PriceListItems.DeactivatePriceListItem;
using CompanyName.MyMeetings.Modules.Payments.Application.PriceListItems.GetPriceListItem;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Payments.PriceListItems
{
[ApiController]
[Route("api/payments/priceListItems")]
public class PriceListItemsController : ControllerBase
{
private readonly IPaymentsModule _paymentsModule;
public PriceListItemsController(IPaymentsModule paymentsModule)
{
_paymentsModule = paymentsModule;
}
[HttpGet]
[HasPermission(PaymentsPermissions.GetPriceListItem)]
[ProducesResponseType(typeof(PriceListItemMoneyValueDto), StatusCodes.Status200OK)]
public async Task GetPriceListItem([FromQuery] GetPriceListItemRequest request)
{
var priceListItem = await _paymentsModule.ExecuteQueryAsync(new GetPriceListItemQuery(
request.CountryCode,
request.CategoryCode,
request.PeriodTypeCode));
return Ok(priceListItem);
}
[HttpPost]
[HasPermission(PaymentsPermissions.CreatePriceListItem)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task CreatePriceListItem([FromBody] CreatePriceListItemRequest request)
{
await _paymentsModule.ExecuteCommandAsync(new CreatePriceListItemCommand(
request.SubscriptionPeriodCode,
request.CategoryCode,
request.CountryCode,
request.PriceValue,
request.PriceCurrency));
return Ok();
}
[HttpPatch("{priceListItemId}/activate")]
[HasPermission(PaymentsPermissions.ActivatePriceListItem)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task ActivatePriceListItem([FromRoute] Guid priceListItemId)
{
await _paymentsModule.ExecuteCommandAsync(new ActivatePriceListItemCommand(priceListItemId));
return Ok();
}
[HttpPatch("{priceListItemId}/deactivate")]
[HasPermission(PaymentsPermissions.DeactivatePriceListItem)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task DeactivatePriceListItem([FromRoute] Guid priceListItemId)
{
await _paymentsModule.ExecuteCommandAsync(new DeactivatePriceListItemCommand(priceListItemId));
return Ok();
}
[HttpPut]
[HasPermission(PaymentsPermissions.ChangePriceListItemAttributes)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task ChangePriceListItemAttributes(
[FromBody] ChangePriceListItemAttributesRequest request)
{
await _paymentsModule.ExecuteCommandAsync(new ChangePriceListItemAttributesCommand(
request.PriceListItemId,
request.CountryCode,
request.SubscriptionPeriodCode,
request.CategoryCode,
request.PriceValue,
request.PriceCurrency));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/RegisterSubscriptionRenewalPaymentRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments
{
public class RegisterSubscriptionRenewalPaymentRequest
{
public Guid PaymentId { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/SubscriptionRenewalsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Payments.Application.Contracts;
using CompanyName.MyMeetings.Modules.Payments.Application.Subscriptions.MarkSubscriptionRenewalPaymentAsPaid;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Payments
{
[Route("api/payments/subscriptionRenewals")]
[ApiController]
public class SubscriptionRenewalsController : ControllerBase
{
private readonly IPaymentsModule _paymentsModule;
public SubscriptionRenewalsController(IPaymentsModule paymentsModule)
{
_paymentsModule = paymentsModule;
}
[HttpPost]
[HasPermission(PaymentsPermissions.RegisterPayment)]
public async Task RegisterSubscriptionPayment(RegisterSubscriptionRenewalPaymentRequest request)
{
await _paymentsModule.ExecuteCommandAsync(
new MarkSubscriptionRenewalPaymentAsPaidCommand(request.PaymentId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/Subscriptions/BuySubscriptionRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.Subscriptions
{
public class BuySubscriptionRequest
{
public string SubscriptionTypeCode { get; set; }
public string CountryCode { get; set; }
public decimal Value { get; set; }
public string Currency { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/Subscriptions/RegisterSubscriptionPaymentRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.Subscriptions
{
public class RegisterSubscriptionPaymentRequest
{
public Guid PaymentId { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/Subscriptions/RenewSubscriptionRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.Payments.Subscriptions
{
public class RenewSubscriptionRequest
{
public string SubscriptionTypeCode { get; set; }
public string CountryCode { get; set; }
public decimal Value { get; set; }
public string Currency { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/Subscriptions/SubscriptionPaymentsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Payments.Application.Contracts;
using CompanyName.MyMeetings.Modules.Payments.Application.Subscriptions.MarkSubscriptionPaymentAsPaid;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Payments.Subscriptions
{
[Route("api/payments/subscriptionPayments")]
[ApiController]
public class SubscriptionPaymentsController : ControllerBase
{
private readonly IPaymentsModule _meetingsModule;
public SubscriptionPaymentsController(IPaymentsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpPost]
[HasPermission(PaymentsPermissions.RegisterPayment)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task RegisterSubscriptionPayment(RegisterSubscriptionPaymentRequest request)
{
await _meetingsModule.ExecuteCommandAsync(new MarkSubscriptionPaymentAsPaidCommand(request.PaymentId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/Payments/Subscriptions/SubscriptionsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Payments.Application.Contracts;
using CompanyName.MyMeetings.Modules.Payments.Application.Subscriptions.BuySubscription;
using CompanyName.MyMeetings.Modules.Payments.Application.Subscriptions.BuySubscriptionRenewal;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.Payments.Subscriptions
{
[Route("api/payments/subscriptions")]
[ApiController]
public class SubscriptionsController : ControllerBase
{
private readonly IPaymentsModule _meetingsModule;
public SubscriptionsController(IPaymentsModule meetingsModule)
{
_meetingsModule = meetingsModule;
}
[HttpPost("")]
[HasPermission(PaymentsPermissions.BuySubscription)]
public async Task BuySubscription(BuySubscriptionRequest request)
{
var paymentId = await _meetingsModule.ExecuteCommandAsync(
new BuySubscriptionCommand(
request.SubscriptionTypeCode,
request.CountryCode,
request.Value,
request.Currency));
return Ok(paymentId);
}
[HttpPost("{subscriptionId}/renewals")]
[HasPermission(PaymentsPermissions.RenewSubscription)]
public async Task RenewSubscription(
Guid subscriptionId,
RenewSubscriptionRequest request)
{
await _meetingsModule.ExecuteCommandAsync(
new BuySubscriptionRenewalCommand(
subscriptionId,
request.SubscriptionTypeCode,
request.CountryCode,
request.Value,
request.Currency));
return Accepted();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/UserAccess/AuthenticatedUserController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Authorization.GetAuthenticatedUserPermissions;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Authorization.GetUserPermissions;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Contracts;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Users.GetAuthenticatedUser;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Users.GetUser;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.UserAccess
{
[Route("api/userAccess/authenticatedUser")]
[ApiController]
public class AuthenticatedUserController : ControllerBase
{
private readonly IUserAccessModule _userAccessModule;
public AuthenticatedUserController(IUserAccessModule userAccessModule)
{
_userAccessModule = userAccessModule;
}
[NoPermissionRequired]
[HttpGet("")]
[ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
public async Task GetAuthenticatedUser()
{
var user = await _userAccessModule.ExecuteQueryAsync(new GetAuthenticatedUserQuery());
return Ok(user);
}
[NoPermissionRequired]
[HttpGet("permissions")]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetAuthenticatedUserPermissions()
{
var permissions = await _userAccessModule.ExecuteQueryAsync(new GetAuthenticatedUserPermissionsQuery());
return Ok(permissions);
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/UserAccess/EmailsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Contracts;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Emails;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.UserAccess
{
[Route("api/userAccess/emails")]
[ApiController]
public class EmailsController : ControllerBase
{
private readonly IUserAccessModule _userAccessModule;
public EmailsController(IUserAccessModule userAccessModule)
{
_userAccessModule = userAccessModule;
}
[NoPermissionRequired]
[AllowAnonymous]
[HttpGet("")]
public async Task GetEmails()
{
var allEmails = await _userAccessModule.ExecuteQueryAsync(new GetAllEmailsQuery());
return Ok(allEmails);
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/UserAccess/RegisterNewUserRequest.cs
================================================
namespace CompanyName.MyMeetings.API.Modules.UserAccess
{
public class RegisterNewUserRequest
{
public string Login { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ConfirmLink { get; set; }
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/UserAccess/UserAccessAutofacModule.cs
================================================
using Autofac;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Contracts;
using CompanyName.MyMeetings.Modules.UserAccess.Infrastructure;
namespace CompanyName.MyMeetings.API.Modules.UserAccess
{
public class UserAccessAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType()
.As()
.InstancePerLifetimeScope();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Modules/UserAccess/UserRegistrationsController.cs
================================================
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.Modules.Registrations.Application.Contracts;
using CompanyName.MyMeetings.Modules.Registrations.Application.UserRegistrations.ConfirmUserRegistration;
using CompanyName.MyMeetings.Modules.Registrations.Application.UserRegistrations.RegisterNewUser;
using CompanyName.MyMeetings.Modules.UserAccess.Application.Contracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CompanyName.MyMeetings.API.Modules.UserAccess
{
[Route("userAccess/[controller]")]
[ApiController]
public class UserRegistrationsController : ControllerBase
{
private readonly IRegistrationsModule _registrationsModule;
public UserRegistrationsController(IRegistrationsModule registrationsModule)
{
_registrationsModule = registrationsModule;
}
[NoPermissionRequired]
[AllowAnonymous]
[HttpPost("")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task RegisterNewUser(RegisterNewUserRequest request)
{
await _registrationsModule.ExecuteCommandAsync(new RegisterNewUserCommand(
request.Login,
request.Password,
request.Email,
request.FirstName,
request.LastName,
request.ConfirmLink));
return Ok();
}
[NoPermissionRequired]
[AllowAnonymous]
[HttpPatch("{userRegistrationId}/confirm")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task ConfirmRegistration(Guid userRegistrationId)
{
await _registrationsModule.ExecuteCommandAsync(new ConfirmUserRegistrationCommand(userRegistrationId));
return Ok();
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Program.cs
================================================
using Autofac.Extensions.DependencyInjection;
namespace CompanyName.MyMeetings.API
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateWebHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(
webBuilder => { webBuilder.UseStartup(); });
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Properties/launchSettings.json
================================================
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57869",
"sslPort": 44368
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"DevWorkshops.Meetings.API": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5000"
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/api/values",
"publishAllPorts": true,
"useSSL": true
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/Startup.cs
================================================
using Autofac;
using Autofac.Extensions.DependencyInjection;
using CompanyName.MyMeetings.API.Configuration.Authorization;
using CompanyName.MyMeetings.API.Configuration.ExecutionContext;
using CompanyName.MyMeetings.API.Configuration.Extensions;
using CompanyName.MyMeetings.API.Configuration.Validation;
using CompanyName.MyMeetings.API.Modules.Administration;
using CompanyName.MyMeetings.API.Modules.Meetings;
using CompanyName.MyMeetings.API.Modules.Payments;
using CompanyName.MyMeetings.API.Modules.UserAccess;
using CompanyName.MyMeetings.BuildingBlocks.Application;
using CompanyName.MyMeetings.BuildingBlocks.Domain;
using CompanyName.MyMeetings.BuildingBlocks.Infrastructure.Emails;
using CompanyName.MyMeetings.Modules.Administration.Infrastructure.Configuration;
using CompanyName.MyMeetings.Modules.Meetings.Infrastructure.Configuration;
using CompanyName.MyMeetings.Modules.Payments.Infrastructure.Configuration;
using CompanyName.MyMeetings.Modules.Registrations.Infrastructure.Configuration;
using CompanyName.MyMeetings.Modules.UserAccess.Infrastructure.Configuration;
using CompanyName.MyMeetings.Modules.UserAccess.Infrastructure.Configuration.Identity;
using Hellang.Middleware.ProblemDetails;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Server.HttpSys;
using Serilog;
using Serilog.Formatting.Compact;
using ILogger = Serilog.ILogger;
namespace CompanyName.MyMeetings.API
{
public class Startup
{
private const string MeetingsConnectionString = "MeetingsConnectionString";
private static ILogger _logger;
private static ILogger _loggerForApi;
private readonly IConfiguration _configuration;
public Startup(IWebHostEnvironment env)
{
ConfigureLogger();
_configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json")
.AddUserSecrets()
.AddEnvironmentVariables("Meetings_")
.Build();
_loggerForApi.Information("Connection string:" + _configuration.GetConnectionString(MeetingsConnectionString));
AuthorizationChecker.CheckAllEndpoints();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerDocumentation();
services.ConfigureIdentityService();
services.AddSingleton();
services.AddSingleton();
services.AddProblemDetails(x =>
{
x.Map(ex => new InvalidCommandProblemDetails(ex));
x.Map(ex => new BusinessRuleValidationExceptionProblemDetails(ex));
});
services.AddAuthorization(options =>
{
options.AddPolicy(HasPermissionAttribute.HasPermissionPolicyName, policyBuilder =>
{
policyBuilder.Requirements.Add(new HasPermissionAuthorizationRequirement());
policyBuilder.AddAuthenticationSchemes("Bearer");
});
});
services.AddScoped();
}
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
containerBuilder.RegisterModule(new MeetingsAutofacModule());
containerBuilder.RegisterModule(new AdministrationAutofacModule());
containerBuilder.RegisterModule(new UserAccessAutofacModule());
containerBuilder.RegisterModule(new PaymentsAutofacModule());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
var container = app.ApplicationServices.GetAutofacRoot();
app.UseCors(builder =>
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
InitializeModules(container);
app.UseMiddleware();
app.UseSwaggerDocumentation();
app.AddIdentityService();
if (env.IsDevelopment())
{
app.UseProblemDetails();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
// app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
private static void ConfigureLogger()
{
_logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console(
outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] [{Module}] [{Context}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(new CompactJsonFormatter(), "logs/logs")
.CreateLogger();
_loggerForApi = _logger.ForContext("Module", "API");
_loggerForApi.Information("Logger configured");
}
private void InitializeModules(ILifetimeScope container)
{
var httpContextAccessor = container.Resolve();
var executionContextAccessor = new ExecutionContextAccessor(httpContextAccessor);
var emailsConfiguration = new EmailsConfiguration(_configuration["EmailsConfiguration:FromEmail"]);
MeetingsStartup.Initialize(
_configuration.GetConnectionString(MeetingsConnectionString),
executionContextAccessor,
_logger,
emailsConfiguration,
null);
AdministrationStartup.Initialize(
_configuration.GetConnectionString(MeetingsConnectionString),
executionContextAccessor,
_logger,
null);
UserAccessStartup.Initialize(
_configuration.GetConnectionString(MeetingsConnectionString),
executionContextAccessor,
_logger,
emailsConfiguration,
_configuration["Security:TextEncryptionKey"],
null,
null);
PaymentsStartup.Initialize(
_configuration.GetConnectionString(MeetingsConnectionString),
executionContextAccessor,
_logger,
emailsConfiguration,
null);
RegistrationsStartup.Initialize(
_configuration.GetConnectionString(MeetingsConnectionString),
executionContextAccessor,
_logger,
emailsConfiguration,
_configuration["Security:TextEncryptionKey"],
null,
null);
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/appsettings.Development.json
================================================
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/appsettings.Production.json
================================================
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/appsettings.json
================================================
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"System": "Information",
"Microsoft": "None"
}
},
"AllowedHosts": "*",
"EmailsConfiguration": {
"FromEmail": "no-reply@mymeetings.com"
},
"Security": {
/* NOTE! This is sensitive data and should be stored in secure way (not here). Added only for demo purpose. */
"TextEncryptionKey": "E546C8DF278CK5990069B522"
},
"ConnectionStrings": {
"MeetingsConnectionString": "YourConnectioString"
}
}
================================================
FILE: src/API/CompanyName.MyMeetings.API/entrypoint.sh
================================================
#!/bin/bash
sleep 30 ;
dotnet CompanyName.MyMeetings.API.dll
================================================
FILE: src/API/CompanyName.MyMeetings.API/tempkey.rsa
================================================
{"KeyId":"6962297f9adb377dadb20e11b9d82f6c","Parameters":{"D":"k4wzTPOMjoB3/gKcu/IGMXrLgZlmPR7NbtUb22Dkw8xhUMVGBV2fE7zEEZyR+jkvKTQbzL+vOA9pmAOxtgZk3AnB1c3ntreZjB3tjYdshglRq7I1VhVDdxJ6e8jwcXqdUhUMiXdYScdkA/jKUO9Ls1XVKA4iXl7fJ3nMhLNgsCXAzuS824XvDGEGJ6FZxjCNfGtTIgoZPFTyJvkHAqQ+Ll72BYdb0vS3gY7wNlAYScHdfBOhmeirvkN4Z9uXp1E/m+QGGlfgm7Eqdt0d4AjMQ8BeNR3wrMB4B5QN6ssP0ENVqIDSLxnq4NLL74fiqgBcFlu3nqSRcqgPB0tvMah2aQ==","DP":"fTAwFVELf2DVCALpwParCuCChyFRgBWbgHanv4oRstuHHe2hgbasAKnXF+dO00D6k3Kvh5xFKlHr+e3W4hFI7nGM47DfVOX0L+DhsC2sa4qCHpMNU0EpJdrnASpPWWfBAiQPae+VC4WbzJQy1LOoH8Juqm5FqG8evZJ7otMzB9s=","DQ":"hBz7Jz9TQoKsV//0KfXMlRFqO3v1qVe4A8b7knrTCL/0IjaD1edZvx3G6H6zkKXZkkXHVTYnJHMxIRm3Ds8C6EYwt9jfNtodQundv9w8xTKNJTemLKLtp9IuBBbL3X4dwZdriiI4woDRhe+ZD5fP25ElqbBlDC4ra1/N6KJUREU=","Exponent":"AQAB","InverseQ":"MrVycQYUEcmT6ddtkiXV4L3Qg+1iXgIbFF5OAtgXkD+lI+rclgUnFTYG3qgUhMn/ZtV/HhpW2FavUKCsmyv2Lmd1nVHe4LjgAjpKu9NlkripI/ROw8SculZEisI7P2lcAVI5kUSAQumiQg7kQcDqrTnrTI/T5m5LuygcGoYo3kA=","Modulus":"nCbBW8+F6FuisseukkmknunroSMyJ8oi/yRyqWWBiVwiWYkvT88SfASyBLciDPXtV0PXsGkmxGyD4z/cQa5O5xU/gRHS3BKvxmuBribI+6JGBF1ukXoMooGIKEunDArgKb8O1bWDX7MyxU8sxyok73qOvtIqEb+ENKd1bFnP4PH/Yi3ZgHyTGcKfdRuB80WJQf8g9p1SFecg4Hhrh+j8XGeQow46bHgoKHelGSFlC6MFt12k0HISfty1AnHxrUP1IT5YpEWIDHNiexqJgc5Q2Bw9Tworux3sR6hQUh588NWSPw/9nhWT/l6AGifp7nJqiIEtgvrhWeVtUXJgZkWgnQ==","P":"xSulQHBrGbZPrSqKiPBORAdK+ZHqg0VD6i9pCbzjDBWYGRS/ekbF/JQR81p/Wrm/K6hi1+eeDElZPK2e4WfyqQqVeDs6QQMjXjpSA/65WWdTDjNL7So2fYSUV70dwawo/EWtY1JHmBGEcKKDbeNGMwrP44iGQhE7wsGLQFB1NM8=","Q":"yr34862ggc3OsYi8JFy83fmwiurGQc25+0U1UtiT0jhadSXcg+XEHjWUKTpHVJEIF+DKV+lwXTEtF5lsa1BAl5hHDwgcY19TJkaF4QIsfNMp0/s5iWNRdRhWKoqp9QGKxTOF9jpCeJgj0MUwLcFLZQ+UvWnqLv3yjsJ+De69xtM="}}
================================================
FILE: src/API/RequestExamples/Authentication.http
================================================
### Authenticate Member
POST {{baseUrl}}/connect/token
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=testMember@mail.com&password=testMemberPass&client_id=ro.client&client_secret=secret
### Authenticate Admin
POST {{baseUrl}}/connect/token
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=testAdmin@mail.com&password=testAdminPass&client_id=ro.client&client_secret=secret
================================================
FILE: src/API/RequestExamples/Users.http
================================================
### Register a new user
POST {{baseUrl}}/userAccess/UserRegistrations
Content-Type: application/json
{
"Login": "login",
"Password": "password",
"Email": "email@mail.com",
"FirstName": "John",
"LastName": "Doe",
"ConfirmLink": "Abc"
}
### User registration confirmation
PATCH {{baseUrl}}/userAccess/UserRegistrations/e80985c5-bf97-4bb3-b178-9423d70ef87b/confirm
================================================
FILE: src/API/RequestExamples/http-client.env.json
================================================
{
"dev": {
"baseUrl": "http://localhost:5000"
}
}
================================================
FILE: src/BuildingBlocks/Application/CompanyName.MyMeetings.BuildingBlocks.Application.csproj
================================================
================================================
FILE: src/BuildingBlocks/Application/Data/ISqlConnectionFactory.cs
================================================
using System.Data;
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Data
{
public interface ISqlConnectionFactory
{
IDbConnection GetOpenConnection();
IDbConnection CreateNewConnection();
string GetConnectionString();
}
}
================================================
FILE: src/BuildingBlocks/Application/Emails/EmailMessage.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Emails
{
public struct EmailMessage
{
public string To { get; }
public string Subject { get; }
public string Content { get; }
public EmailMessage(
string to,
string subject,
string content)
{
this.To = to;
this.Subject = subject;
this.Content = content;
}
}
}
================================================
FILE: src/BuildingBlocks/Application/Emails/IEmailSender.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Emails
{
public interface IEmailSender
{
Task SendEmail(EmailMessage message);
}
}
================================================
FILE: src/BuildingBlocks/Application/Events/DomainNotificationBase.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Domain;
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Events
{
public class DomainNotificationBase : IDomainEventNotification
where T : IDomainEvent
{
public T DomainEvent { get; }
public Guid Id { get; }
public DomainNotificationBase(T domainEvent, Guid id)
{
this.Id = id;
this.DomainEvent = domainEvent;
}
}
}
================================================
FILE: src/BuildingBlocks/Application/Events/IDomainEventNotification.cs
================================================
using MediatR;
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Events
{
public interface IDomainEventNotification : IDomainEventNotification
{
TEventType DomainEvent { get; }
}
public interface IDomainEventNotification : INotification
{
Guid Id { get; }
}
}
================================================
FILE: src/BuildingBlocks/Application/IExecutionContextAccessor.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application
{
public interface IExecutionContextAccessor
{
Guid UserId { get; }
Guid CorrelationId { get; }
bool IsAvailable { get; }
}
}
================================================
FILE: src/BuildingBlocks/Application/InvalidCommandException.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application
{
public class InvalidCommandException : Exception
{
public List Errors { get; }
public InvalidCommandException(List errors)
{
this.Errors = errors;
}
}
}
================================================
FILE: src/BuildingBlocks/Application/Outbox/IOutbox.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Outbox
{
public interface IOutbox
{
void Add(OutboxMessage message);
Task Save();
}
}
================================================
FILE: src/BuildingBlocks/Application/Outbox/OutboxMessage.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Outbox
{
public class OutboxMessage
{
public Guid Id { get; set; }
public DateTime OccurredOn { get; set; }
public string Type { get; set; }
public string Data { get; set; }
public DateTime? ProcessedDate { get; set; }
public OutboxMessage(Guid id, DateTime occurredOn, string type, string data)
{
this.Id = id;
this.OccurredOn = occurredOn;
this.Type = type;
this.Data = data;
}
private OutboxMessage()
{
}
}
}
================================================
FILE: src/BuildingBlocks/Application/Queries/IPagedQuery.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Queries
{
public interface IPagedQuery
{
///
/// Page number. If null then default is 1.
///
int? Page { get; }
///
/// Records number per page (page size).
///
int? PerPage { get; }
}
}
================================================
FILE: src/BuildingBlocks/Application/Queries/PageData.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Queries
{
public struct PageData
{
public int Offset { get; }
public int Next { get; }
public PageData(int offset, int next)
{
this.Offset = offset;
this.Next = next;
}
}
}
================================================
FILE: src/BuildingBlocks/Application/Queries/PagedQueryHelper.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Application.Queries
{
public static class PagedQueryHelper
{
public const string Offset = "Offset";
public const string Next = "Next";
public static PageData GetPageData(IPagedQuery query)
{
int offset;
if (!query.Page.HasValue ||
!query.PerPage.HasValue)
{
offset = 0;
}
else
{
offset = (query.Page.Value - 1) * query.PerPage.Value;
}
int next;
if (!query.PerPage.HasValue)
{
next = int.MaxValue;
}
else
{
next = query.PerPage.Value;
}
return new PageData(offset, next);
}
public static string AppendPageStatement(string sql)
{
return $"{sql} " +
$"OFFSET @{Offset} ROWS FETCH NEXT @{Next} ROWS ONLY; ";
}
}
}
================================================
FILE: src/BuildingBlocks/Domain/BusinessRuleValidationException.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public class BusinessRuleValidationException : Exception
{
public IBusinessRule BrokenRule { get; }
public string Details { get; }
public BusinessRuleValidationException(IBusinessRule brokenRule)
: base(brokenRule.Message)
{
BrokenRule = brokenRule;
this.Details = brokenRule.Message;
}
public override string ToString()
{
return $"{BrokenRule.GetType().FullName}: {BrokenRule.Message}";
}
}
}
================================================
FILE: src/BuildingBlocks/Domain/CompanyName.MyMeetings.BuildingBlocks.Domain.csproj
================================================
================================================
FILE: src/BuildingBlocks/Domain/DomainEventBase.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public class DomainEventBase : IDomainEvent
{
public Guid Id { get; }
public DateTime OccurredOn { get; }
public DomainEventBase()
{
this.Id = Guid.NewGuid();
this.OccurredOn = DateTime.UtcNow;
}
}
}
================================================
FILE: src/BuildingBlocks/Domain/Entity.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public abstract class Entity
{
private List _domainEvents;
///
/// Domain events occurred.
///
public IReadOnlyCollection DomainEvents => _domainEvents?.AsReadOnly();
public void ClearDomainEvents()
{
_domainEvents?.Clear();
}
///
/// Add domain event.
///
/// Domain event.
protected void AddDomainEvent(IDomainEvent domainEvent)
{
_domainEvents ??= [];
this._domainEvents.Add(domainEvent);
}
protected void CheckRule(IBusinessRule rule)
{
if (rule.IsBroken())
{
throw new BusinessRuleValidationException(rule);
}
}
}
}
================================================
FILE: src/BuildingBlocks/Domain/IAggregateRoot.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public interface IAggregateRoot
{
}
}
================================================
FILE: src/BuildingBlocks/Domain/IBusinessRule.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public interface IBusinessRule
{
bool IsBroken();
string Message { get; }
}
}
================================================
FILE: src/BuildingBlocks/Domain/IDomainEvent.cs
================================================
using MediatR;
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public interface IDomainEvent : INotification
{
Guid Id { get; }
DateTime OccurredOn { get; }
}
}
================================================
FILE: src/BuildingBlocks/Domain/IgnoreMemberAttribute.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class IgnoreMemberAttribute : Attribute
{
}
}
================================================
FILE: src/BuildingBlocks/Domain/TypedIdValueBase.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public abstract class TypedIdValueBase : IEquatable
{
public Guid Value { get; }
protected TypedIdValueBase(Guid value)
{
if (value == Guid.Empty)
{
throw new InvalidOperationException("Id value cannot be empty!");
}
Value = value;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is TypedIdValueBase other && Equals(other);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public bool Equals(TypedIdValueBase other)
{
return this.Value == other?.Value;
}
public static bool operator ==(TypedIdValueBase obj1, TypedIdValueBase obj2)
{
if (object.Equals(obj1, null))
{
if (object.Equals(obj2, null))
{
return true;
}
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(TypedIdValueBase x, TypedIdValueBase y)
{
return !(x == y);
}
}
}
================================================
FILE: src/BuildingBlocks/Domain/ValueObject.cs
================================================
using System.Reflection;
namespace CompanyName.MyMeetings.BuildingBlocks.Domain
{
public abstract class ValueObject : IEquatable
{
private List _properties;
private List _fields;
public static bool operator ==(ValueObject obj1, ValueObject obj2)
{
if (object.Equals(obj1, null))
{
if (object.Equals(obj2, null))
{
return true;
}
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(ValueObject obj1, ValueObject obj2)
{
return !(obj1 == obj2);
}
public bool Equals(ValueObject obj)
{
return Equals(obj as object);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return GetProperties().All(p => PropertiesAreEqual(obj, p))
&& GetFields().All(f => FieldsAreEqual(obj, f));
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
foreach (var prop in GetProperties())
{
var value = prop.GetValue(this, null);
hash = HashValue(hash, value);
}
foreach (var field in GetFields())
{
var value = field.GetValue(this);
hash = HashValue(hash, value);
}
return hash;
}
}
protected static void CheckRule(IBusinessRule rule)
{
if (rule.IsBroken())
{
throw new BusinessRuleValidationException(rule);
}
}
private bool PropertiesAreEqual(object obj, PropertyInfo p)
{
return object.Equals(p.GetValue(this, null), p.GetValue(obj, null));
}
private bool FieldsAreEqual(object obj, FieldInfo f)
{
return object.Equals(f.GetValue(this), f.GetValue(obj));
}
private IEnumerable GetProperties()
{
if (this._properties == null)
{
this._properties = GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.GetCustomAttribute(typeof(IgnoreMemberAttribute)) == null)
.ToList();
// Not available in Core
// !Attribute.IsDefined(p, typeof(IgnoreMemberAttribute))).ToList();
}
return this._properties;
}
private IEnumerable GetFields()
{
if (this._fields == null)
{
this._fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(p => p.GetCustomAttribute(typeof(IgnoreMemberAttribute)) == null)
.ToList();
}
return this._fields;
}
private int HashValue(int seed, object value)
{
var currentHash = value?.GetHashCode() ?? 0;
return (seed * 23) + currentHash;
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/BiDictionary.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure
{
public class BiDictionary
{
private readonly IDictionary _firstToSecond = new Dictionary();
private readonly IDictionary _secondToFirst = new Dictionary();
public void Add(TFirst first, TSecond second)
{
if (_firstToSecond.ContainsKey(first) ||
_secondToFirst.ContainsKey(second))
{
throw new ArgumentException("Duplicate first or second");
}
_firstToSecond.Add(first, second);
_secondToFirst.Add(second, first);
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return _firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return _secondToFirst.TryGetValue(second, out first);
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/CompanyName.MyMeetings.BuildingBlocks.Infrastructure.csproj
================================================
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/DomainEventsAccessor.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Domain;
using Microsoft.EntityFrameworkCore;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public class DomainEventsAccessor : IDomainEventsAccessor
{
private readonly DbContext _dbContext;
public DomainEventsAccessor(DbContext dbContext)
{
_dbContext = dbContext;
}
public IReadOnlyCollection GetAllDomainEvents()
{
var domainEntities = this._dbContext.ChangeTracker
.Entries()
.Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()).ToList();
return domainEntities
.SelectMany(x => x.Entity.DomainEvents)
.ToList();
}
public void ClearAllDomainEvents()
{
var domainEntities = this._dbContext.ChangeTracker
.Entries()
.Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()).ToList();
domainEntities
.ForEach(entity => entity.Entity.ClearDomainEvents());
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/DomainEventsDispatcher.cs
================================================
using Autofac;
using Autofac.Core;
using CompanyName.MyMeetings.BuildingBlocks.Application.Events;
using CompanyName.MyMeetings.BuildingBlocks.Application.Outbox;
using CompanyName.MyMeetings.BuildingBlocks.Domain;
using CompanyName.MyMeetings.BuildingBlocks.Infrastructure.Serialization;
using MediatR;
using Newtonsoft.Json;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public class DomainEventsDispatcher : IDomainEventsDispatcher
{
private readonly IMediator _mediator;
private readonly ILifetimeScope _scope;
private readonly IOutbox _outbox;
private readonly IDomainEventsAccessor _domainEventsProvider;
private readonly IDomainNotificationsMapper _domainNotificationsMapper;
public DomainEventsDispatcher(
IMediator mediator,
ILifetimeScope scope,
IOutbox outbox,
IDomainEventsAccessor domainEventsProvider,
IDomainNotificationsMapper domainNotificationsMapper)
{
_mediator = mediator;
_scope = scope;
_outbox = outbox;
_domainEventsProvider = domainEventsProvider;
_domainNotificationsMapper = domainNotificationsMapper;
}
public async Task DispatchEventsAsync()
{
var domainEvents = _domainEventsProvider.GetAllDomainEvents();
List> domainEventNotifications = [];
foreach (var domainEvent in domainEvents)
{
Type domainEvenNotificationType = typeof(IDomainEventNotification<>);
var domainNotificationWithGenericType = domainEvenNotificationType.MakeGenericType(domainEvent.GetType());
var domainNotification = _scope.ResolveOptional(domainNotificationWithGenericType, new List
{
new NamedParameter("domainEvent", domainEvent),
new NamedParameter("id", domainEvent.Id)
});
if (domainNotification != null)
{
domainEventNotifications.Add(domainNotification as IDomainEventNotification);
}
}
_domainEventsProvider.ClearAllDomainEvents();
foreach (var domainEvent in domainEvents)
{
await _mediator.Publish(domainEvent);
}
foreach (var domainEventNotification in domainEventNotifications)
{
var type = _domainNotificationsMapper.GetName(domainEventNotification.GetType());
var data = JsonConvert.SerializeObject(domainEventNotification, new JsonSerializerSettings
{
ContractResolver = new AllPropertiesContractResolver()
});
var outboxMessage = new OutboxMessage(
domainEventNotification.Id,
domainEventNotification.DomainEvent.OccurredOn,
type,
data);
_outbox.Add(outboxMessage);
}
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/DomainEventsDispatcherNotificationHandlerDecorator.cs
================================================
using MediatR;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public class DomainEventsDispatcherNotificationHandlerDecorator : INotificationHandler
where T : INotification
{
private readonly INotificationHandler _decorated;
private readonly IDomainEventsDispatcher _domainEventsDispatcher;
public DomainEventsDispatcherNotificationHandlerDecorator(
IDomainEventsDispatcher domainEventsDispatcher,
INotificationHandler decorated)
{
_domainEventsDispatcher = domainEventsDispatcher;
_decorated = decorated;
}
public async Task Handle(T notification, CancellationToken cancellationToken)
{
await this._decorated.Handle(notification, cancellationToken);
await this._domainEventsDispatcher.DispatchEventsAsync();
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/DomainNotificationsMapper.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public class DomainNotificationsMapper : IDomainNotificationsMapper
{
private readonly BiDictionary _domainNotificationsMap;
public DomainNotificationsMapper(BiDictionary domainNotificationsMap)
{
_domainNotificationsMap = domainNotificationsMap;
}
public string GetName(Type type)
{
return _domainNotificationsMap.TryGetBySecond(type, out var name) ? name : null;
}
public Type GetType(string name)
{
return _domainNotificationsMap.TryGetByFirst(name, out var type) ? type : null;
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/IDomainEventsAccessor.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Domain;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public interface IDomainEventsAccessor
{
IReadOnlyCollection GetAllDomainEvents();
void ClearAllDomainEvents();
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/IDomainEventsDispatcher.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public interface IDomainEventsDispatcher
{
Task DispatchEventsAsync();
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/IDomainNotificationsMapper.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public interface IDomainNotificationsMapper
{
string GetName(Type type);
Type GetType(string name);
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/DomainEventsDispatching/UnitOfWorkCommandHandlerDecorator.cs
================================================
using MediatR;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching
{
public class UnitOfWorkCommandHandlerDecorator : IRequestHandler
where T : IRequest
{
private readonly IRequestHandler _decorated;
private readonly IUnitOfWork _unitOfWork;
public UnitOfWorkCommandHandlerDecorator(
IRequestHandler decorated,
IUnitOfWork unitOfWork)
{
_decorated = decorated;
_unitOfWork = unitOfWork;
}
public async Task Handle(T command, CancellationToken cancellationToken)
{
await this._decorated.Handle(command, cancellationToken);
await this._unitOfWork.CommitAsync(cancellationToken);
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/Emails/EmailSender.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Application.Data;
using CompanyName.MyMeetings.BuildingBlocks.Application.Emails;
using Dapper;
using Serilog;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.Emails
{
public class EmailSender : IEmailSender
{
private readonly ILogger _logger;
private readonly EmailsConfiguration _configuration;
private readonly ISqlConnectionFactory _sqlConnectionFactory;
public EmailSender(
ILogger logger,
EmailsConfiguration configuration,
ISqlConnectionFactory sqlConnectionFactory)
{
_logger = logger;
_configuration = configuration;
_sqlConnectionFactory = sqlConnectionFactory;
}
public async Task SendEmail(EmailMessage message)
{
var sqlConnection = _sqlConnectionFactory.GetOpenConnection();
await sqlConnection.ExecuteScalarAsync(
"INSERT INTO [app].[Emails] ([Id], [From], [To], [Subject], [Content], [Date]) " +
"VALUES (@Id, @From, @To, @Subject, @Content, @Date) ",
new
{
Id = Guid.NewGuid(),
From = _configuration.FromEmail,
message.To,
message.Subject,
message.Content,
Date = DateTime.UtcNow
});
_logger.Information(
"Email sent. From: {From}, To: {To}, Subject: {Subject}, Content: {Content}.",
_configuration.FromEmail,
message.To,
message.Subject,
message.Content);
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/Emails/EmailsConfiguration.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.Emails
{
public class EmailsConfiguration
{
public EmailsConfiguration(string fromEmail)
{
FromEmail = fromEmail;
}
public string FromEmail { get; }
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/EventBus/IEventsBus.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.EventBus
{
public interface IEventsBus : IDisposable
{
Task Publish(T @event)
where T : IntegrationEvent;
void Subscribe(IIntegrationEventHandler handler)
where T : IntegrationEvent;
void StartConsuming();
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/EventBus/IIntegrationEventHandler.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.EventBus
{
public interface IIntegrationEventHandler : IIntegrationEventHandler
where TIntegrationEvent : IntegrationEvent
{
Task Handle(TIntegrationEvent @event);
}
public interface IIntegrationEventHandler
{
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/EventBus/InMemoryEventBus.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.EventBus
{
public sealed class InMemoryEventBus
{
static InMemoryEventBus()
{
}
private InMemoryEventBus()
{
_handlersDictionary = new Dictionary>();
}
public static InMemoryEventBus Instance { get; } = new InMemoryEventBus();
private readonly IDictionary> _handlersDictionary;
public void Subscribe(IIntegrationEventHandler handler)
where T : IntegrationEvent
{
var eventType = typeof(T).FullName;
if (eventType != null)
{
if (_handlersDictionary.ContainsKey(eventType))
{
var handlers = _handlersDictionary[eventType];
handlers.Add(handler);
}
else
{
_handlersDictionary.Add(eventType, [handler]);
}
}
}
public async Task Publish(T @event)
where T : IntegrationEvent
{
var eventType = @event.GetType().FullName;
if (eventType == null)
{
return;
}
List integrationEventHandlers = _handlersDictionary[eventType];
foreach (var integrationEventHandler in integrationEventHandlers)
{
if (integrationEventHandler is IIntegrationEventHandler handler)
{
await handler.Handle(@event);
}
}
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/EventBus/InMemoryEventBusClient.cs
================================================
using Serilog;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.EventBus
{
public class InMemoryEventBusClient : IEventsBus
{
private readonly ILogger _logger;
public InMemoryEventBusClient(ILogger logger)
{
_logger = logger;
}
public void Dispose()
{
}
public async Task Publish(T @event)
where T : IntegrationEvent
{
_logger.Information("Publishing {Event}", @event.GetType().FullName);
await InMemoryEventBus.Instance.Publish(@event);
}
public void Subscribe(IIntegrationEventHandler handler)
where T : IntegrationEvent
{
InMemoryEventBus.Instance.Subscribe(handler);
}
public void StartConsuming()
{
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/EventBus/IntegrationEvent.cs
================================================
using MediatR;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.EventBus
{
public abstract class IntegrationEvent : INotification
{
public Guid Id { get; }
public DateTime OccurredOn { get; }
protected IntegrationEvent(Guid id, DateTime occurredOn)
{
this.Id = id;
this.OccurredOn = occurredOn;
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/IUnitOfWork.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure
{
public interface IUnitOfWork
{
Task CommitAsync(
CancellationToken cancellationToken = default,
Guid? internalCommandId = null);
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/Inbox/InboxMessage.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.Inbox
{
public class InboxMessage
{
public Guid Id { get; set; }
public DateTime OccurredOn { get; set; }
public string Type { get; set; }
public string Data { get; set; }
public DateTime? ProcessedDate { get; set; }
public InboxMessage(DateTime occurredOn, string type, string data)
{
this.Id = Guid.NewGuid();
this.OccurredOn = occurredOn;
this.Type = type;
this.Data = data;
}
private InboxMessage()
{
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/InternalCommands/IInternalCommandsMapper.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.InternalCommands
{
public interface IInternalCommandsMapper
{
string GetName(Type type);
Type GetType(string name);
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/InternalCommands/InternalCommand.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.InternalCommands
{
public class InternalCommand
{
public Guid Id { get; set; }
public string Type { get; set; }
public string Data { get; set; }
public DateTime? ProcessedDate { get; set; }
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/InternalCommands/InternalCommandsMapper.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.InternalCommands
{
public class InternalCommandsMapper : IInternalCommandsMapper
{
private readonly BiDictionary _internalCommandsMap;
public InternalCommandsMapper(BiDictionary internalCommandsMap)
{
_internalCommandsMap = internalCommandsMap;
}
public string GetName(Type type)
{
return _internalCommandsMap.TryGetBySecond(type, out var name) ? name : null;
}
public Type GetType(string name)
{
return _internalCommandsMap.TryGetByFirst(name, out var type) ? type : null;
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/Serialization/AllPropertiesContractResolver.cs
================================================
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure.Serialization
{
public class AllPropertiesContractResolver : DefaultContractResolver
{
protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = type.GetProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance)
.Select(p => this.CreateProperty(p, memberSerialization))
.ToList();
properties.ForEach(p =>
{
p.Writable = true;
p.Readable = true;
});
return properties;
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/ServiceProviderWrapper.cs
================================================
using Autofac;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure
{
public class ServiceProviderWrapper : IServiceProvider
{
private readonly ILifetimeScope lifeTimeScope;
public ServiceProviderWrapper(ILifetimeScope lifeTimeScope)
{
this.lifeTimeScope = lifeTimeScope;
}
#nullable enable
public object? GetService(Type serviceType) => this.lifeTimeScope.ResolveOptional(serviceType);
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/SqlConnectionFactory.cs
================================================
using System.Data;
using System.Data.SqlClient;
using CompanyName.MyMeetings.BuildingBlocks.Application.Data;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure
{
public class SqlConnectionFactory : ISqlConnectionFactory, IDisposable
{
private readonly string _connectionString;
private IDbConnection _connection;
public SqlConnectionFactory(string connectionString)
{
this._connectionString = connectionString;
}
public IDbConnection GetOpenConnection()
{
if (this._connection == null || this._connection.State != ConnectionState.Open)
{
this._connection = new SqlConnection(_connectionString);
this._connection.Open();
}
return this._connection;
}
public IDbConnection CreateNewConnection()
{
var connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
public string GetConnectionString()
{
return _connectionString;
}
public void Dispose()
{
if (this._connection != null && this._connection.State == ConnectionState.Open)
{
this._connection.Dispose();
}
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/StronglyTypedIdValueConverterSelector.cs
================================================
using System.Collections.Concurrent;
using CompanyName.MyMeetings.BuildingBlocks.Domain;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure
{
///
/// Based on https://andrewlock.net/strongly-typed-ids-in-ef-core-using-strongly-typed-entity-ids-to-avoid-primitive-obsession-part-4/.
///
public class StronglyTypedIdValueConverterSelector : ValueConverterSelector
{
private readonly ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo> _converters
= new ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo>();
public StronglyTypedIdValueConverterSelector(ValueConverterSelectorDependencies dependencies)
: base(dependencies)
{
}
public override IEnumerable Select(Type modelClrType, Type providerClrType = null)
{
var baseConverters = base.Select(modelClrType, providerClrType);
foreach (var converter in baseConverters)
{
yield return converter;
}
var underlyingModelType = UnwrapNullableType(modelClrType);
var underlyingProviderType = UnwrapNullableType(providerClrType);
if (underlyingProviderType is null || underlyingProviderType == typeof(Guid))
{
var isTypedIdValue = typeof(TypedIdValueBase).IsAssignableFrom(underlyingModelType);
if (isTypedIdValue)
{
var converterType = typeof(TypedIdValueConverter<>).MakeGenericType(underlyingModelType);
yield return _converters.GetOrAdd((underlyingModelType, typeof(Guid)), _ =>
{
return new ValueConverterInfo(
modelClrType: modelClrType,
providerClrType: typeof(Guid),
factory: valueConverterInfo => (ValueConverter)Activator.CreateInstance(converterType, valueConverterInfo.MappingHints));
});
}
}
}
private static Type UnwrapNullableType(Type type)
{
if (type is null)
{
return null;
}
return Nullable.GetUnderlyingType(type) ?? type;
}
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/TypedIdValueConverter.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Domain;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure
{
public class TypedIdValueConverter : ValueConverter
where TTypedIdValue : TypedIdValueBase
{
public TypedIdValueConverter(ConverterMappingHints mappingHints = null)
: base(id => id.Value, value => Create(value), mappingHints)
{
}
private static TTypedIdValue Create(Guid id) => Activator.CreateInstance(typeof(TTypedIdValue), id) as TTypedIdValue;
}
}
================================================
FILE: src/BuildingBlocks/Infrastructure/UnitOfWork.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Infrastructure.DomainEventsDispatching;
using Microsoft.EntityFrameworkCore;
namespace CompanyName.MyMeetings.BuildingBlocks.Infrastructure
{
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
private readonly IDomainEventsDispatcher _domainEventsDispatcher;
public UnitOfWork(
DbContext context,
IDomainEventsDispatcher domainEventsDispatcher)
{
this._context = context;
this._domainEventsDispatcher = domainEventsDispatcher;
}
public async Task CommitAsync(
CancellationToken cancellationToken = default,
Guid? internalCommandId = null)
{
await this._domainEventsDispatcher.DispatchEventsAsync();
return await _context.SaveChangesAsync(cancellationToken);
}
}
}
================================================
FILE: src/BuildingBlocks/Tests/Application.UnitTests/CompanyName.MyMeetings.BuildingBlocks.Application.UnitTests.csproj
================================================
================================================
FILE: src/BuildingBlocks/Tests/Application.UnitTests/Queries/PagedQueryHelperTests.cs
================================================
using CompanyName.MyMeetings.BuildingBlocks.Application.Queries;
using NUnit.Framework;
namespace CompanyName.MyMeetings.BuildingBlocks.Application.UnitTests.Queries
{
[TestFixture]
public class PagedQueryHelperTests
{
[TestCase(1, 5, 0, 5)]
[TestCase(3, 10, 20, 10)]
[TestCase(null, 20, 0, 20)]
[TestCase(5, null, 0, int.MaxValue)]
[TestCase(null, null, 0, int.MaxValue)]
public void PagedQueryHelper_GetPageData_Test(int? page, int? perPage, int offset, int next)
{
IPagedQuery query = new TestQuery(page, perPage);
var pageData = PagedQueryHelper.GetPageData(query);
Assert.That(pageData, Is.EqualTo(new PageData(offset, next)));
}
private class TestQuery : IPagedQuery
{
public TestQuery(int? page, int? perPage)
{
Page = page;
PerPage = perPage;
}
public int? Page { get; }
public int? PerPage { get; }
}
}
}
================================================
FILE: src/BuildingBlocks/Tests/IntegrationTests/CompanyName.MyMeetings.BuildingBlocks.IntegrationTests.csproj
================================================
================================================
FILE: src/BuildingBlocks/Tests/IntegrationTests/EnvironmentVariablesProvider.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.IntegrationTests
{
public static class EnvironmentVariablesProvider
{
public static string GetVariable(string variableName)
{
var environmentVariable = Environment.GetEnvironmentVariable(variableName);
if (!string.IsNullOrEmpty(environmentVariable))
{
return environmentVariable;
}
environmentVariable = Environment.GetEnvironmentVariable(variableName, EnvironmentVariableTarget.User);
if (!string.IsNullOrEmpty(environmentVariable))
{
return environmentVariable;
}
return Environment.GetEnvironmentVariable(variableName, EnvironmentVariableTarget.Machine);
}
}
}
================================================
FILE: src/BuildingBlocks/Tests/IntegrationTests/Probing/AssertErrorException.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.IntegrationTests.Probing
{
public class AssertErrorException : Exception
{
public AssertErrorException(string message)
: base(message)
{
}
}
}
================================================
FILE: src/BuildingBlocks/Tests/IntegrationTests/Probing/IProbe.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.IntegrationTests.Probing
{
public interface IProbe
{
bool IsSatisfied();
Task SampleAsync();
string DescribeFailureTo();
}
public interface IProbe
{
bool IsSatisfied(T sample);
Task GetSampleAsync();
string DescribeFailureTo();
}
}
================================================
FILE: src/BuildingBlocks/Tests/IntegrationTests/Probing/Poller.cs
================================================
namespace CompanyName.MyMeetings.BuildingBlocks.IntegrationTests.Probing
{
public class Poller
{
private readonly int _timeoutMillis;
private readonly int _pollDelayMillis;
public Poller(int timeoutMillis)
{
_timeoutMillis = timeoutMillis;
_pollDelayMillis = 1000;
}
public async Task CheckAsync(IProbe probe)
{
var timeout = new Timeout(_timeoutMillis);
while (!probe.IsSatisfied())
{
if (timeout.HasTimedOut())
{
throw new AssertErrorException(DescribeFailureOf(probe));
}
await Task.Delay(_pollDelayMillis);
await probe.SampleAsync();
}
}
public async Task GetAsync(IProbe