public PublishingViewModel(ISettings settings, IMessagePublisher publisher, IUserInteraction interaction) { _settings = settings; _publisher = publisher; _interaction = interaction; PublishDate = DateTime.Today; Time = DateTime.UtcNow.ToShortTimeString(); LoadStoredServers(); _publisher.Publish(new QueryPotentialTitleUiMsg(pt => Title = pt)); }
public void Start() { // MessageBroker.Default はアプリケーション全体で有効なインスタンス var messageBroker = UniRx.MessageBroker.Default; IMessagePublisher publisher = messageBroker; IMessageReceiver receiver = messageBroker; // 型を指定して購読ができる receiver.Receive <int>() .Subscribe(x => Debug.Log("int message : " + x)).AddTo(this); receiver.Receive <string>() .Subscribe(x => Debug.Log("string message : " + x)).AddTo(this); receiver.Receive <Exception>() .Subscribe(x => Debug.LogError("Exception : " + x)).AddTo(this); // 任意の型を発行できる publisher.Publish(123); publisher.Publish("Hello!"); publisher.Publish(new Exception("Exception!")); }
public MessageBroker(IMessagePublisher messagePublisher) { _messagePublisher = messagePublisher; _onRequestThreadSubject = new Subject <Message>(); _offRequestThreadSubject = new Subject <Message>(); _offRequestThreadInternalSubject = new Subject <Message>(); _publisherInternalSubject = new Subject <Message>(); // ensure off-request data is observed onto a different thread _offRequestThreadInternalSubject.Subscribe(x => Observable.Start(() => _offRequestThreadSubject.OnNext(x), TaskPoolScheduler.Default)); _publisherInternalSubject.Subscribe(x => Observable.Start(() => _messagePublisher.Publish(x), TaskPoolScheduler.Default)); }
public void Execute(IEdiMessage message) { var orderHasBeenShippedMessage = (OrderHasBeenShippedMessage)message; var ediAsnSentMessageToBeSent = new EdiAsnSentMessage() { ControlNumber = orderHasBeenShippedMessage.ControlNumber, BOL = orderHasBeenShippedMessage.BOL, LineNumbers = orderHasBeenShippedMessage.GetLineNumbers().ToList() }; _publisher.Publish(ediAsnSentMessageToBeSent); }
public async Task <IActionResult> RecheckDkim(DkimInfoRequest request) { if (!ModelState.IsValid) { return(BadRequest(new ErrorResponse(ModelState.Values))); } DkimRecordsExpired recordsExpired = new DkimRecordsExpired(request.Domain, Guid.NewGuid().ToString(), null); await _messagePublisher.Publish(recordsExpired, _config.SnsTopicArn); return(new OkObjectResult("{}")); }
public void Awake() { _messageReceiver.Receive <GamePlayMessages.DataBitCollectedEvent>() .Subscribe(x => { Debug.Log("Data bit collected!"); }) .AddTo(this); _messageReceiver.Receive <GamePlayMessages.PlayerFailureEvent>() .Subscribe(x => { BgmTapeStop().Forget(Debug.LogException); }) .AddTo(this); _messageReceiver.Receive <GamePlayMessages.ReportBitCountEvent>() .Subscribe(x => { _bitCount = x.BitCount; }) .AddTo(this); _messageReceiver.Receive <GamePlayMessages.ReportHoldingBitCountEvent>() .Subscribe(x => { Debug.Log("Report received"); if (x.BitCount != 0) { _messagePublisher.Publish(new GamePlayMessages.DirectoryReceivedEvent()); } _collectedBitCount += x.BitCount; uiController.UpdateDataBitCount(_collectedBitCount); }).AddTo(this); _messageReceiver.Receive <GamePlayMessages.RetryRequestedEvent>() .Subscribe(x => { if (_currentLevelIndex >= Scene.Levels.Length) { _currentLevelIndex = 0; } PerformSceneTransition( ChangeScene(Scene.Main, new PlaySceneData(_currentLevelIndex)) ); }).AddTo(this); }
public void Consume(PurchaseProduct message) { if (!stock.ContainsKey(message.ProductId) || stock[message.ProductId] == 0) { throw new Exception("Item not in stock"); } stock[message.ProductId] -= 1; bus.Publish(new ProductPurchased { CustomerId = message.CustomerId, ProductId = message.ProductId }); }
private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.tag.Equals("Player")) { // Player collision, this is a sign of failure. _messagePublisher.Publish(new GamePlayMessages.PlayerFailureEvent()); if (audioSource == null || clipToPlay == null) { return; } audioSource.clip = clipToPlay; audioSource.Play(); } }
public override void Process(EventContext ctx) { Task.Factory.StartNewDelayed(1500, () => _publisher.Publish(new EventOccurrence { Id = ctx.Event.Id, OrganizationId = ctx.Event.OrganizationId, ProjectId = ctx.Event.ProjectId, StackId = ctx.Event.StackId, Type = ctx.Event.Type, IsHidden = ctx.Event.IsHidden, IsFixed = ctx.Event.IsFixed, IsNotFound = ctx.Event.IsNotFound(), IsRegression = ctx.IsRegression })); }
public IEnumerable <WeatherForecast> Get() { _messagePublisher.Publish(new WeatherForecastsRequestedMessage()); var rng = new Random(); return(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray()); }
public async Task Handle(AppointmentScheduledEvent appointmentScheduledEvent, CancellationToken cancellationToken) { _logger.LogInformation("Handling appointmentScheduledEvent"); // we are translating from a domain event to an application event here var newMessage = new CreateConfirmationEmailMessage(); var appt = appointmentScheduledEvent.AppointmentScheduled; // if this is slow these can be parallelized or cached. MEASURE before optimizing. var doctor = await _doctorRepository.GetByIdAsync(appt.DoctorId); if (doctor == null) { throw new DoctorNotFoundException(appt.DoctorId); } var clientWithPatientsSpec = new ClientByIdIncludePatientsSpecification(appt.ClientId); var client = await _clientRepository.GetBySpecAsync(clientWithPatientsSpec); if (client == null) { throw new ClientNotFoundException(appt.ClientId); } var patient = client.Patients.FirstOrDefault(p => p.Id == appt.PatientId); if (patient == null) { throw new PatientNotFoundException(appt.PatientId); } var apptType = await _appointmentTypeRepository.GetByIdAsync(appt.AppointmentTypeId); if (apptType == null) { throw new AppointmentTypeNotFoundException(appt.AppointmentTypeId); } newMessage.AppointmentId = appt.Id; newMessage.AppointmentStartDateTime = appointmentScheduledEvent.AppointmentScheduled.TimeRange.Start; newMessage.ClientName = client.FullName; newMessage.ClientEmailAddress = client.EmailAddress; newMessage.DoctorName = doctor.Name; newMessage.PatientName = patient.Name; newMessage.AppointmentType = apptType.Name; _messagePublisher.Publish(newMessage); _logger.LogInformation($"Message published. {newMessage.PatientName}"); }
public Task <MessageQueueDto> Handle(SendMessageQueueCommand request, CancellationToken cancellationToken) { var envList = new List <MessageEnvelop>() { new MessageEnvelop { RoutingKey = request.RoutingKey, Content = request.Content } }; _messagePublisher.Publish(envList); return(Task.FromResult(new MessageQueueDto())); }
public CompilerService(IMessagePublisher messages) { messages.OfType <RequestMessage>() .Where(x => x.Type == "compileRequest") .Subscribe(x => { if (x?.Data?.Code == null) { throw new InvalidOperationException("Code cannot be null."); } var result = TestRunner.Run(x.Data.Code, TestFixture); messages.Publish(new ResponseMessage("compileResult", x.ConnectionId, result)); }); }
private void OnTriggerEnter2D(Collider2D other) { if (_collected) { return; } if (other.gameObject.tag.Equals("Player")) { sRenderer.color = new Color(1, 1, 1, 0); audioSource.Play(); collectParticle.Play(); _collected = true; _messagePublisher.Publish(new GamePlayMessages.DataBitCollectedEvent()); } }
public void Hande(PositionAcquired message) { sellingPoints.Clear(); moveUpPoints.Clear(); sustainUp = message.SustainUp; sustainDown = message.SustainDown; threshold = message.Threshold; isAlive = true; publisher.Publish(new ThresholdChanged(threshold)); }
public async Task SaveAsync <TKey, TAggregateRoot>(TAggregateRoot aggregateRoot, bool purge = true) where TKey : IEquatable <TKey> where TAggregateRoot : class, IAggregateRoot <TKey>, new() { await this.SaveAggregateAsync <TKey, TAggregateRoot>(aggregateRoot); foreach (var evt in aggregateRoot.UncommittedEvents) { _messagePublisher.Publish(evt); } if (purge) { ((IPurgeable)aggregateRoot).Purge(); } }
public bool Publish(object data, string routingKey, out string errorMsg) { errorMsg = ""; try { Log.Debug("准备发送数据" + data); byte[] body = _serializer.Serialize(data); return(_messagePublisher.Publish(body, routingKey, out errorMsg)); } catch (Exception expException) { errorMsg = expException.Message; Log.Error("对象发送失败", expException); return(false); } }
public async Task Execute(KinesisEvent kinesisEvent) { _logger.Information($"Processing {kinesisEvent.Records.Count} records."); var tollAmountMessages = GetRecordContents <TollAmountMessage>(kinesisEvent.Records); var customerIds = tollAmountMessages.Select(t => t.CustomerId); try { var billingAlerts = (await _billingAlertStore.Get(customerIds))?.ToList(); if (billingAlerts == null) { billingAlerts = new List <BillingAlertItem>(); } var alertsToPublish = new List <AlertMessage>(); foreach (var billingAlert in billingAlerts) { var tollAmountMessage = tollAmountMessages.FirstOrDefault(t => t.CustomerId == billingAlert.CustomerId); billingAlert.TotalBillAmount += tollAmountMessage.TollAmount; billingAlert.BillAmountLastUpdated = DateTime.UtcNow; if (ShouldAlert(billingAlert)) { alertsToPublish.Add(new AlertMessage { CustomerId = billingAlert.CustomerId, TotalBillAmount = billingAlert.TotalBillAmount, AlertAmountThreshold = billingAlert.AlertAmountThreshold, Message = DefaultAlertMessage(billingAlert) }); } } await _messagePublisher.Publish(alertsToPublish); billingAlerts.ForEach(b => { b.IsAlerted = b.IsAlerted || alertsToPublish.Any(a => a.CustomerId == b.CustomerId); }); await _billingAlertStore.Put(billingAlerts); } catch (Exception ex) { _logger.Error(ex, ex.Message); } }
public IObservable <IResponse> GetResponses(IRequest request) { request.RequestId = Guid.NewGuid().ToString(); request.RequesterId = RequesterId.Create(); return(Observable.Create <IResponse>(observer => { IDisposable disposable = _responseSource.Messages .Where(response => response.RequestId == request.RequestId && response.RequesterId == request.RequesterId) .Subscribe(observer); _requestPublisher.Publish(request); return disposable; })); }
public void PublishBulkMessages(int numberOfTasks, int precision) { for (var i = 0; i < numberOfTasks; i++) { var message = new PiCalcMessage { Id = DateTime.Now.Ticks + i, Name = $"CalcPi{i}", Precision = precision }; publisher.Publish(message); Console.WriteLine($"Published task id: {message.Id}, " + $"name: {message.Name}, " + $"precision: {message.Precision}"); } }
/// <summary> /// Create a new invitation request and publish to queue for a collection of invites! /// </summary> /// <param name="invites"></param> /// <param name="date"></param> /// <returns></returns> private async Task CreateInvitationRequestAndPublish(List <Invite> invites, DateTime date) { try { foreach (var inv in invites) { var contract = new InvitationRequest() { Id = inv.Id, Email = inv.Email, Date = date }; await _MessagePublisher.Publish <InvitationRequest>(contract); } return; } catch (System.InvalidOperationException e) { _Logger.LogError($"Exception Caught: {e.Message}"); } }
public IActionResult Get(string id) { //TODO:in the future in case of correlated action, link them by correlation header, .... //[CustomHeader(Models.Identifiers.CorrelationId, _operationalUnit.OperationId)] // message definition //(MessageHeader Header, DomainModel<PingRequest> Body, MessageFooter Footer) Task.Run(() => { new Function(_logger, DomainModels.System.Identifiers.RetryCount).Decorate(() => { return(_publisher.Publish( _localConfiguration.MiddlewareExchange, _localConfiguration.MessagePublisherRoute, ( Header: new MessageHeader { CorrelateId = _operationalUnit.InstanceId }, Body: new DomainModel <PingModel>() { Model = new PingModel() { ChassisNumber = Guid.NewGuid(), Message = "ping - pong!" } }, Footer: new MessageFooter { Sender = ControllerContext.ActionDescriptor.DisplayName, Environemnt = _operationalUnit.Environment, Assembly = _operationalUnit.Assembly, FingerPrint = ControllerContext.ActionDescriptor.Id, Route = new Dictionary <string, string> { { DomainModels.Types.Identifiers.MessagePublisherRoute, _localConfiguration.MessagePublisherRoute } }, Hint = ResponseHint.OK } ))); }); }); //throw new CustomException(code: ExceptionCodes.MessageMalformed); return(Content(id)); }
public Task Raise <TEvent>(TEvent evt) where TEvent : IEvent { if (evt == null) { throw new ArgumentNullException(nameof(evt)); } var publishableAttr = evt.GetPublishableAttributes(); var messageId = Guid.Empty.Equals(CorrelationIdAccessor.CorrelationId) ? Guid.NewGuid() : CorrelationIdAccessor.CorrelationId; var payload = _serializer.Serialize(evt); var message = new Message(messageId, publishableAttr.Label, publishableAttr.Version, evt.GetType().AssemblyQualifiedName, payload); return(_messagePublisher.Publish(publishableAttr.DestName, publishableAttr.Type, message)); }
public void ShouldPublishTeamNewsWhenReceived() { IMessagePublisher <TestMessage> publisher = A.Fake <IMessagePublisher <TestMessage> >(); IMessageSource <TestMessage> source = A.Fake <IMessageSource <TestMessage> >(); IDisposable subscription = A.Fake <IDisposable>(); IObserver <TestMessage> observer = null; TestMessage objFrom = new TestMessage(); TestMessage objTo = new TestMessage(); IMessageConverter <TestMessage, TestMessage> converter = A.Fake <IMessageConverter <TestMessage, TestMessage> >(); IMessageBridge bridge = new MessageBridge <TestMessage, TestMessage>(publisher, converter, source); A.CallTo(() => converter.Convert(objFrom)).Returns(objTo); A.CallTo(() => source.Messages.Subscribe(A <IObserver <TestMessage> > .Ignored)).Returns(subscription); A.CallTo(() => source.Messages.Subscribe(A <IObserver <TestMessage> > .Ignored)).Invokes(call => observer = call.GetArgument <IObserver <TestMessage> >(0)); bridge.Start(); observer.OnNext(objFrom); A.CallTo(() => publisher.Publish(objTo)).MustHaveHappened(Repeated.Exactly.Once); }
public async Task <ProcessResult> Process() { Stopwatch stopwatch = Stopwatch.StartNew(); List <DkimSchedulerState> entitiesToUpdate = await _dkimPeriodicSchedulerDao.GetDkimRecordsToUpdate(); _log.LogInformation($"Found {entitiesToUpdate.Count} records to update."); if (entitiesToUpdate.Any()) { entitiesToUpdate.ForEach(async _ => await _publisher.Publish(_.ToDkimPollMessage(), _config.PublisherConnectionString)); await _dkimPeriodicSchedulerDao.UpdateLastChecked(entitiesToUpdate); _log.LogInformation($"Processing {entitiesToUpdate.Count} took: {stopwatch.Elapsed}"); } stopwatch.Stop(); return(entitiesToUpdate.Any() ? ProcessResult.Continue : ProcessResult.Stop); }
public async Task ProcessMessages(int batchSize, CancellationToken cancellationToken) { var messages = await _unitOfWork.MessageRepository.FetchUnprocessed(batchSize, cancellationToken); foreach (var message in messages) { try { //Setting processed date message.SetProcessedAt(DateTime.Now); await _publisher.Publish(message, cancellationToken); _unitOfWork.MessageRepository.UpdateProcessedAt(message); await _unitOfWork.CommitAsync(); } catch (Exception ex) { _logger.LogError($"\n-------- An error has occurred while processing message {message.Id}: {ex.Message}\n"); } } }
public async Task SaveAsync <TKey, TAggregateRoot>(TAggregateRoot aggregateRoot, bool purge = true) where TKey : IEquatable <TKey> where TAggregateRoot : class, IAggregateRoot <TKey>, new() { // When doing a CQRS architecture with Event Sourcing (ES), this step should be going // to save the events occurred within the aggregate. In this example, we simply save // the entire aggregate root to avoid handling the snapshots. await this.SaveAggregateAsync <TKey, TAggregateRoot>(aggregateRoot); foreach (var evnt in aggregateRoot.UncommittedEvents) { messagePublisher.Publish(evnt); } if (purge) { ((IPurgeable)aggregateRoot).Purge(); } }
public void Start(IMessagePublisher publisher, FeederProperties props, OnFeedFinished onfinishedCallback) { _properties = props; _onFeedFinishedCallback = onfinishedCallback; //get the data try { if (!string.IsNullOrEmpty(props.InstrumentCode)) { if (!_properties.StartDate.HasValue || !_properties.EndDate.HasValue) { throw new Exception("No Start date and/or end date defined"); } //get the market data var instrumentMktData = _dataManager.GetMarketTickData(props.StartDate.Value, props.EndDate.Value, props.InstrumentCode); foreach (var tickData in instrumentMktData) { var bytes = _binarySerializer.Serialize(tickData); //Thread.Sleep(1); publisher.Publish(bytes); } //invoke data publish finished _onFeedFinishedCallback.Invoke(); } else { throw new Exception("No instrument is defined."); } } catch (Exception exception) { throw; } }
public override async Task <ActionResult <UpdateClientResponse> > HandleAsync(UpdateClientRequest request, CancellationToken cancellationToken) { var response = new UpdateClientResponse(request.CorrelationId); var toUpdate = _mapper.Map <Client>(request); await _repository.UpdateAsync(toUpdate); var dto = _mapper.Map <ClientDto>(toUpdate); response.Client = dto; // Note: These messages could be triggered from the Repository or DbContext events // In the DbContext you could look for entities marked with an interface saying they needed // to be synchronized via cross-domain events and publish the appropriate message. var appEvent = new NamedEntityUpdatedEvent(_mapper.Map <NamedEntity>(toUpdate), "Client-Updated"); _messagePublisher.Publish(appEvent); return(Ok(response)); }
private void Spawn() { // 敵をスポーンする var enemies = _spawners.Select(spawner => spawner.Spawn() as EnemyCore).ToList(); // 敵が全滅したらイベントを発行 enemies.Select(enemy => enemy.IsDead) .Merge() .Where(_ => enemies.All(enemy => enemy.IsDead.Value)) .Subscribe(_ => { Debug.Log($"[{Owner.Room.ToString()}] Enemies has been slain."); _onRoomCapturedAsync.OnNext(Unit.Default); _onRoomCapturedAsync.OnCompleted(); _messagePublisher.Publish(new RoomSignal.RoomCleared()); }); Debug.Log($"[{Owner.Room.ToString()}] Enemies was spawned."); }
public override async Task <ActionResult <CreateDoctorResponse> > HandleAsync(CreateDoctorRequest request, CancellationToken cancellationToken) { var response = new CreateDoctorResponse(request.CorrelationId()); var toAdd = _mapper.Map <Doctor>(request); toAdd = await _repository.AddAsync(toAdd); var dto = _mapper.Map <DoctorDto>(toAdd); response.Doctor = dto; // Note: These messages could be triggered from the Repository or DbContext events // In the DbContext you could look for entities marked with an interface saying they needed // to be synchronized via cross-domain events and publish the appropriate message. var appEvent = new EntityCreatedEvent(_mapper.Map <NamedEntity>(toAdd)); _messagePublisher.Publish(appEvent); return(Ok(response)); }
public MessageBroker(IMessagePublisher messagePublisher) { _messagePublisher = messagePublisher; _onRequestThreadSubject = new Subject<Message>(); _offRequestThreadSubject = new Subject<Message>(); _offRequestThreadInternalSubject = new Subject<Message>(); _publisherInternalSubject = new Subject<Message>(); // ensure off-request data is observed onto a different thread _offRequestThreadInternalSubject.Subscribe(x => Observable.Start(() => _offRequestThreadSubject.OnNext(x), TaskPoolScheduler.Default)); _publisherInternalSubject.Subscribe(x => Observable.Start(() => _messagePublisher.Publish(x), TaskPoolScheduler.Default)); }