Ejemplo n.º 1
0
        async Task <Guid?> IEmployeeServiceAdmin.CreateAsync(Common.Models.Employee.Employee employee)
        {
            Guard.ArgumentIsNotNull(employee, nameof(employee));

            EmployeeValidator.Validate(employee);
            await ValdiateIfUserWithSameCompanyEmailExists(employee);

            employee.EmployeeId = Guid.NewGuid();
            EmployeeDto dto = _mapper.Map <Common.Models.Employee.Employee, EmployeeDto>(employee);

            Guid?employeeId = await _employeeRepositoryAdmin.CreateAsync(dto);

            if (employeeId == null)
            {
                return(null);
            }

            await _eventPublisher.PublishAsync <IEmployeeCreatedEvent>(new EmployeeCreatedEvent
            {
                EmployeeId = employee.EmployeeId,
                FullName   = employee.FullName,
                JobTitle   = employee.JobTitle,
                Technology = employee.Technology,
                StartDate  = employee.StartDate
            });

            return(employeeId);
        }
        public void OnDelete(DeleteEvent @event)
        {
            var eventType     = typeof(EntityDeletingEvent <>).MakeGenericType(@event.Entity.GetType());
            var deletingEvent = (IAsyncEvent)Activator.CreateInstance(eventType, @event.Entity, @event.Session);

            _eventPublisher.PublishAsync(deletingEvent).GetAwaiter().GetResult();
        }
Ejemplo n.º 3
0
        private async void OnTimerTick(object sender, EventArgs e)
        {
            if (!_isSendingDataEnabled)
            {
                return;
            }


            var resultTemp = await _eventPublisher.PublishAsync(
                ConnectionString,
                new SensorData
            {
                DeviceName = DeviceName,
                ReadTime   = DateTime.Now,
                SensorType = "Temp",
                Value      = Temperature
            });

            LastTempSendStatus = resultTemp.IsSuccess ? "Success" : "Error: " + resultTemp.Error;

            var resultHum = await _eventPublisher.PublishAsync(
                ConnectionString,
                new SensorData
            {
                DeviceName = DeviceName,
                ReadTime   = DateTime.Now,
                SensorType = "Hum",
                Value      = Humidity
            });

            LastHumSendStatus = resultHum.IsSuccess ? "Success" : "Error: " + resultHum.Error;

            LastSendTime = DateTime.Now;
        }
Ejemplo n.º 4
0
        public async Task SendAsync <TCommand>(TCommand command, bool publishEvents = true) where TCommand : ICommand
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var commandHandler = _resolver.Resolve <ICommandHandlerAsync <TCommand> >();

            if (commandHandler == null)
            {
                throw new Exception($"No handler found for command '{command.GetType().FullName}'");
            }

            var events = await commandHandler.HandleAsync(command);

            if (!publishEvents)
            {
                return;
            }

            foreach (var @event in events)
            {
                var concreteEvent = EventFactory.CreateConcreteEvent(@event);
                await _eventPublisher.PublishAsync(concreteEvent);
            }
        }
        public async Task ReplayAllEvents(CancellationToken cancellationToken)
        {
            var command = new CommandDefinition(string.Format(GETALL_SELECT_SQL, eventStoreTable), cancellationToken: cancellationToken);

            using (var connection = await _GetConnection(cancellationToken))
            {
                var eventsQuery = await connection.QueryAsync <DocumentData>(command);

                // create a function to deserialize event data
                Func <string, string, IEvent> func = (eventType, data) =>
                {
                    var output = DeserializeData <IEvent>(data, Type.GetType(eventType));
                    return(output);
                };

                // deserialize the events from our documents
                var events = from e in eventsQuery
                             select func(e.EventType, e.EventData);

                foreach (var @event in events)
                {
                    await publisher.PublishAsync(@event, cancellationToken);
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> UpdateHearingDetails(Guid hearingId, [FromBody] UpdateHearingRequest request)
        {
            if (hearingId == Guid.Empty)
            {
                ModelState.AddModelError(nameof(hearingId), $"Please provide a valid {nameof(hearingId)}");
                return(BadRequest(ModelState));
            }

            var result = new UpdateHearingRequestValidation().Validate(request);

            if (!result.IsValid)
            {
                ModelState.AddFluentValidationErrors(result.Errors);
                return(BadRequest(ModelState));
            }

            var getHearingByIdQuery = new GetHearingByIdQuery(hearingId);
            var videoHearing        = await _queryHandler.Handle <GetHearingByIdQuery, VideoHearing>(getHearingByIdQuery);

            if (videoHearing == null)
            {
                return(NotFound());
            }

            var venue = await GetVenue(request.HearingVenueName);

            if (venue == null)
            {
                ModelState.AddModelError(nameof(request.HearingVenueName), "Hearing venue does not exist");
                return(BadRequest(ModelState));
            }

            var cases = MapCase(request.Cases);

            // use existing video hearing values here when request properties are null
            request.AudioRecordingRequired ??= videoHearing.AudioRecordingRequired;
            request.QuestionnaireNotRequired ??= videoHearing.QuestionnaireNotRequired;
            request.HearingRoomName ??= videoHearing.HearingRoomName;
            request.OtherInformation ??= videoHearing.OtherInformation;

            var command = new UpdateHearingCommand(hearingId, request.ScheduledDateTime,
                                                   request.ScheduledDuration, venue, request.HearingRoomName, request.OtherInformation,
                                                   request.UpdatedBy, cases, request.QuestionnaireNotRequired.Value, request.AudioRecordingRequired.Value);

            await _commandHandler.Handle(command);

            var hearingMapper  = new HearingToDetailsResponseMapper();
            var updatedHearing = await _queryHandler.Handle <GetHearingByIdQuery, VideoHearing>(getHearingByIdQuery);

            var response = hearingMapper.MapHearingToDetailedResponse(updatedHearing);

            if (videoHearing.Status == BookingStatus.Created)
            {
                // publish this event when Hearing is set for ready for video
                await _eventPublisher.PublishAsync(new HearingDetailsUpdatedIntegrationEvent(updatedHearing));
            }

            return(Ok(response));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="taxCategoryId">Tax category identifier</param>
        /// <param name="customer">Customer</param>
        /// <param name="price">Price (taxable value)</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the calculated tax rate. A value indicating whether a request is taxable
        /// </returns>
        protected virtual async Task <(decimal taxRate, bool isTaxable)> GetTaxRateAsync(Product product, int taxCategoryId,
                                                                                         Customer customer, decimal price)
        {
            var taxRate = decimal.Zero;

            //active tax provider
            var store = await _storeContext.GetCurrentStoreAsync();

            var activeTaxProvider = await _taxPluginManager.LoadPrimaryPluginAsync(customer, store.Id);

            if (activeTaxProvider == null)
            {
                return(taxRate, true);
            }

            //tax request
            var taxRateRequest = await PrepareTaxRateRequestAsync(product, taxCategoryId, customer, price);

            var isTaxable = !await IsTaxExemptAsync(product, taxRateRequest.Customer);

            //tax exempt

            //make EU VAT exempt validation (the European Union Value Added Tax)
            if (isTaxable &&
                _taxSettings.EuVatEnabled &&
                await IsVatExemptAsync(taxRateRequest.Address, taxRateRequest.Customer))
            {
                //VAT is not chargeable
                isTaxable = false;
            }

            //get tax rate
            var taxRateResult = await activeTaxProvider.GetTaxRateAsync(taxRateRequest);

            //tax rate is calculated, now consumers can adjust it
            await _eventPublisher.PublishAsync(new TaxRateCalculatedEvent(taxRateResult));

            if (taxRateResult.Success)
            {
                //ensure that tax is equal or greater than zero
                if (taxRateResult.TaxRate < decimal.Zero)
                {
                    taxRateResult.TaxRate = decimal.Zero;
                }

                taxRate = taxRateResult.TaxRate;
            }
            else if (_taxSettings.LogErrors)
            {
                foreach (var error in taxRateResult.Errors)
                {
                    await _logger.ErrorAsync($"{activeTaxProvider.PluginDescriptor.FriendlyName} - {error}", null, customer);
                }
            }

            return(taxRate, isTaxable);
        }
Ejemplo n.º 8
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // Wait for bus to be ready
            await Task.Delay(TimeSpan.FromSeconds(8), stoppingToken);

            // Generate random vehicle Ids
            var rnd      = new Random(DateTimeOffset.UtcNow.Millisecond);
            var vehicles = Enumerable.Range(0, 5).Select(_ => GenerateRandomString(rnd)).ToList();

            // Find the number of possible combinations
            var kinds        = Enum.GetValues <DoorKind>().ToList();
            var states       = Enum.GetValues <DoorState>().ToList();
            var combinations = vehicles.Count * kinds.Count * states.Count;

            // Select a portion of the combinations
            var times = rnd.Next(1, combinations);

            logger.LogInformation("Selected {Times} of {Combinations} combinations.", times, combinations);

            var delay = TimeSpan.FromSeconds(15);

            for (var i = 0; i < times; i++)
            {
                // Select vehicle, door kind and door state randonly
                var vehicle = vehicles[rnd.Next(0, combinations) * 1 % vehicles.Count];
                var kind    = kinds[rnd.Next(0, combinations) * i % kinds.Count];
                var state   = states[rnd.Next(0, combinations) * i % states.Count];

                // Publish event depending on the door state
                if (state == DoorState.Closed)
                {
                    var evt = new DoorClosed
                    {
                        VehicleId = vehicle,
                        Closed    = DateTimeOffset.UtcNow,
                        Kind      = kind,
                    };

                    await publisher.PublishAsync(evt, cancellationToken : stoppingToken);
                }
                else
                {
                    var evt = new DoorOpened
                    {
                        VehicleId = vehicle,
                        Opened    = DateTimeOffset.UtcNow,
                        Kind      = kind,
                    };

                    await publisher.PublishAsync(evt, cancellationToken : stoppingToken);
                }

                await Task.Delay(delay, stoppingToken);
            }

            logger.LogInformation("Finished producing dummy data!");
        }
Ejemplo n.º 9
0
        public void Should_publish_message_to_queue_when_HearingCancelledIntegrationEvent_is_raised()
        {
            var hearingCancelledEvent = new HearingCancelledIntegrationEvent(Guid.NewGuid());

            _eventPublisher.PublishAsync(hearingCancelledEvent);

            _serviceBusQueueClient.Count.Should().Be(1);
            var @event = _serviceBusQueueClient.ReadMessageFromQueue();

            @event.IntegrationEvent.Should().BeOfType <HearingCancelledIntegrationEvent>();
        }
Ejemplo n.º 10
0
        public MaakOefeningAanCommand HandleMaakKlantAanCommand(MaakOefeningAanCommand command)
        {
            _oefeningRepository.Add(command.Oefening);

            _eventPublisher.PublishAsync(new OefeningAangemaaktEvent
            {
                Oefening = command.Oefening
            });

            return(command);
        }
        public async Task Run()
        {
            await _publisher.PublishAsync(
                new IntegrationEventA
                { Content = "A->" + DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture) });

            await _publisher.PublishAsync(
                new IntegrationEventB
                { Content = "B->" + DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture) });

            await _dbContext.SaveChangesAsync();
        }
Ejemplo n.º 12
0
        protected virtual async Task TriggerEventWithEntity(IEventPublisher eventPublisher, Type genericEventType, object entity, bool triggerInCurrentUnitOfWork)
        {
            var entityType = ProxyHelper.UnProxy(entity).GetType();
            var eventType  = genericEventType.MakeGenericType(entityType);

            if (triggerInCurrentUnitOfWork || UnitOfWorkManager.Current == null)
            {
                await eventPublisher.PublishAsync(eventType, Activator.CreateInstance(eventType, entity));

                return;
            }

            UnitOfWorkManager.Current.OnCompleted(() => eventPublisher.PublishAsync(eventType, Activator.CreateInstance(eventType, entity)));
        }
Ejemplo n.º 13
0
        public async Task InitializeAsync(HttpContext httpContext)
        {
            var scheduler = httpContext.RequestServices.GetService <ITaskScheduler>();
            var taskStore = httpContext.RequestServices.GetService <ITaskStore>();

            if (scheduler == null || taskStore == null)
            {
                // No scheduler or store registered. Get out!
                Logger.Warn("Task scheduler has not been registered.");
                return;
            }

            var tasks = await taskStore.GetAllTasksAsync(true);

            await taskStore.CalculateFutureSchedulesAsync(tasks, true /* isAppStart */);

            scheduler.Activate(
                _appConfig.TaskSchedulerBaseUrl,
                _appConfig.TaskSchedulerPollInterval,
                httpContext);

            Logger.Info("Initialized TaskScheduler with base url '{0}'".FormatInvariant(scheduler.BaseUrl));

            await _eventPublisher.PublishAsync(new TaskSchedulerInitializedEvent { Tasks = tasks });
        }
Ejemplo n.º 14
0
        public async Task <ActionResult> CreateOrderJson(VirtoCommerceDomainPaymentModelBankCardInfo bankCardInfo)
        {
            EnsureThatCartExist();

            //Need lock to prevent concurrent access to same cart
            using (var lockObject = await AsyncLock.GetLockByKey(GetAsyncLockCartKey(WorkContext.CurrentCart.Id)).LockAsync())
            {
                var order = await _orderApi.OrderModuleCreateOrderFromCartAsync(_cartBuilder.Cart.Id);

                //Raise domain event
                await _orderPlacedEventPublisher.PublishAsync(new OrderPlacedEvent(order.ToWebModel(base.WorkContext.AllCurrencies, base.WorkContext.CurrentLanguage), _cartBuilder.Cart));

                await _cartBuilder.RemoveCartAsync();

                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    var contact = await _customerApi.CustomerModuleGetContactByIdAsync(WorkContext.CurrentCustomer.Id);

                    var orderAddresses = GetOrderAddresses(order);
                    foreach (var orderAddress in orderAddresses)
                    {
                        contact.Addresses.Add(orderAddress.ToCustomerModel());
                    }

                    await _customerApi.CustomerModuleUpdateContactAsync(contact);
                }

                var processingResult = await GetOrderProcessingResultAsync(order, bankCardInfo);

                return(Json(new { order = order, orderProcessingResult = processingResult }, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 15
0
        protected override async void OnClosed(EventArgs e)
        {
            _viewModel.Dispose();
            await _eventPublisher.PublishAsync(new ChangeViewEnabledEvent(_invoker, true));

            base.OnClosed(e);
        }
Ejemplo n.º 16
0
        public async Task SaveAsync <T>(T aggregate, int?expectedVersion = null) where T : AggregateRoot
        {
            if (expectedVersion != null && _eventStore.Get(aggregate.Id, expectedVersion.Value).Any())
            {
                throw new ConcurrencyException(aggregate.Id);
            }
            var i = 0;

            foreach (var @event in aggregate.GetUncommittedChanges())
            {
                if (@event.Id == Guid.Empty)
                {
                    @event.Id = aggregate.Id;
                }
                if (@event.Id == Guid.Empty)
                {
                    throw new AggregateOrEventMissingIdException(aggregate.GetType(), @event.GetType());
                }
                i++;
                @event.Version   = aggregate.Version + i;
                @event.TimeStamp = DateTimeOffset.UtcNow;
                // Note: Events should be saved and handled in sequence
                await _eventStore.SaveAsync(@event);

                await _publisher.PublishAsync(@event);
            }
            aggregate.MarkChangesAsCommitted();
        }