public async Task executed_job_should_be_stored() { var storage = Substitute.For<IFileStorage>(); var container = Substitute.For<IContainer>(); var appEvent = new ApplicationEvent(); var sut = new ContainerEventBus(storage, container); await sut.PublishAsync(appEvent); storage.Received().PushAsync(appEvent); }
/// <summary> /// Initializes a new instance of the <see cref="EventHandlerFailedEventArgs"/> class. /// </summary> /// <param name="applicationEvent">The application event that one or more subscribers failed to process.</param> /// <param name="failures">One instance per handler.</param> /// <param name="handlerCount">Total amount of subscribers (and not just the amount of failed handlers).</param> /// <exception cref="System.ArgumentNullException"> /// applicationEvent /// or /// failures /// </exception> /// <exception cref="System.ArgumentOutOfRangeException">handlerCount;Suspicions handler count</exception> public EventHandlerFailedEventArgs(ApplicationEvent applicationEvent, IReadOnlyList<HandlerFailure> failures, int handlerCount) { if (applicationEvent == null) throw new ArgumentNullException("applicationEvent"); if (failures == null) throw new ArgumentNullException("failures"); if (handlerCount < 0 || handlerCount > 1000) throw new ArgumentOutOfRangeException("handlerCount", handlerCount, "Suspicions handler count"); ApplicationEvent = applicationEvent; Failures = failures; HandlerCount = handlerCount; }
public void Init(ApplicationDesc desc) { // set icon if (!string.IsNullOrEmpty(desc.Win32_IconFileName)) { using (var s = this.GetType().Assembly.GetManifestResourceStream(desc.Win32_IconFileName)) { if (s == null) Debug.ThrowError("WinFormApplication", "Cannot find icon file.\nYou must use this nameing convention: {MyAppNam}.IconFileName.png"); Bitmap bmp = new Bitmap(s); this.Icon = Icon.FromHandle(bmp.GetHicon()); } } theEvent = new ApplicationEvent(); base.Name = desc.Name; base.Text = desc.Name; var frame = desc.FrameSize; if (frame.Width == 0 || frame.Height == 0) frame = (IPlatform.Singleton.ScreenSize.ToVector2() / 1.5f).ToSize2(); base.ClientSize = new System.Drawing.Size(frame.Width, frame.Height); switch (desc.StartPosition) { case ApplicationStartPositions.Default: StartPosition = FormStartPosition.WindowsDefaultLocation; break; case ApplicationStartPositions.CenterCurrentScreen: StartPosition = FormStartPosition.CenterScreen; break; } switch (desc.Type) { case ApplicationTypes.Box: FormBorderStyle = FormBorderStyle.None; break; case ApplicationTypes.Frame: FormBorderStyle = FormBorderStyle.FixedDialog; MaximizeBox = false; break; case ApplicationTypes.FrameSizable: FormBorderStyle = FormBorderStyle.Sizable; break; } base.FormClosing += winFormClosing; base.Shown += winFormShown; MouseMove += mouseMoveEvent; MouseDown += mouseDownEvent; MouseUp += mouseUpEvent; KeyDown += keyDownEvent; KeyUp += keyUpEvent; MouseWheel += scrollEvent; }
public static ApplicationEvent InsertApplicationEvent( this IDbConnection connection, IDbTransaction transaction, Guid applicationId, ApplicationEventType eventType, string message) { if (transaction == null) { throw new ArgumentNullException(nameof(transaction)); } var applicationEvent = new ApplicationEvent { ApplicationId = applicationId, EventType = eventType, Message = message }.SetNew(); connection.Insert(applicationEvent, transaction); return(applicationEvent); }
public int GetRecordCount(string signalId, DateTime startTime, DateTime endTime) { try { return(_db.Controller_Event_Log.Count(r => r.SignalID == signalId && r.Timestamp >= startTime && r.Timestamp < endTime)); } catch (Exception ex) { var logRepository = ApplicationEventRepositoryFactory.Create(); var e = new ApplicationEvent(); e.ApplicationName = "MOE.Common"; e.Class = GetType().ToString(); e.Function = "GetRecordCount"; e.SeverityLevel = ApplicationEvent.SeverityLevels.High; e.Timestamp = DateTime.Now; e.Description = signalId + " - " + ex.Message; logRepository.Add(e); throw ex; } }
public async Task RaiseAndListenToEvents_ApplicationBus_ValidCase() { var bus = new Tavisca.Common.Plugins.Configuration.ApplicationEventBus(); var mockEventObserver = new MOQObserver(); var applicationEvent = new ApplicationEvent() { Context = "Hi", Name = "Invalidate-Cache", Id = Guid.NewGuid().ToString(), Publisher = "Tushar", TimeStamp = DateTime.UtcNow }; bus.Register("Invalidate-Cache", mockEventObserver); Thread.Sleep(2000); bus.Notify(applicationEvent); Thread.Sleep(5000); Assert.AreEqual(MOQObserver.EventId, applicationEvent.Id); }
private void MainForm_ApplicationEvent(ApplicationEvent Event) { if (Event.EventType == ApplicationEvent.Type.ELEMENT_CREATED) { if (Event.Doc.Type == ProjectElement.ElementType.CHARACTER_SET) { foreach (ComboItem item in comboCharsetFiles.Items) { if ((DocumentInfo)item.Tag == Event.Doc) { return; } } string nameToUse = Event.Doc.DocumentFilename ?? "New File"; comboCharsetFiles.Items.Add(new Types.ComboItem(nameToUse, Event.Doc)); } } if (Event.EventType == ApplicationEvent.Type.ELEMENT_REMOVED) { if (Event.Doc.Type == ProjectElement.ElementType.CHARACTER_SET) { foreach (Types.ComboItem comboItem in comboCharsetFiles.Items) { if ((DocumentInfo)comboItem.Tag == Event.Doc) { comboCharsetFiles.Items.Remove(comboItem); if (comboCharsetFiles.SelectedIndex == -1) { comboCharsetFiles.SelectedIndex = 0; } break; } } } } }
public List <Controller_Event_Log> GetEventsByEventCodesParamDateTimeRange(string signalId, DateTime startTime, DateTime endTime, int startHour, int startMinute, int endHour, int endMinute, List <int> eventCodes, int param) { try { var events = (from s in _db.Controller_Event_Log where s.SignalID == signalId && s.Timestamp >= startTime && s.Timestamp <= endTime && ((s.Timestamp.Hour > startHour && s.Timestamp.Hour < endHour) || (s.Timestamp.Hour == startHour && s.Timestamp.Hour == endHour && s.Timestamp.Minute >= startMinute && s.Timestamp.Minute <= endMinute) || (s.Timestamp.Hour == startHour && s.Timestamp.Hour < endHour && s.Timestamp.Minute >= startMinute) || (s.Timestamp.Hour < startHour && s.Timestamp.Hour == endHour && s.Timestamp.Minute <= endMinute)) && s.EventParam == param && eventCodes.Contains(s.EventCode) select s).ToList(); events.Sort((x, y) => DateTime.Compare(x.Timestamp, y.Timestamp)); return(events); } catch (Exception ex) { IApplicationEventRepository logRepository = ApplicationEventRepositoryFactory.Create(); ApplicationEvent e = new ApplicationEvent(); e.ApplicationName = "MOE.Common"; e.Class = GetType().ToString(); e.Function = "GetSignalEventsByEventCodesParamDateTimeRange"; e.SeverityLevel = ApplicationEvent.SeverityLevels.High; e.Timestamp = DateTime.Now; e.Description = ex.Message; logRepository.Add(e); throw; } }
public void Update(Detector detector) { var g = (from r in _db.Detectors where r.ID == detector.ID select r).FirstOrDefault(); if (g != null) { foreach (var i in detector.DetectionTypeIDs) { var t = (from r in _db.DetectionTypes where r.DetectionTypeID == i select r).FirstOrDefault(); detector.DetectionTypes.Add(t); } try { _db.Entry(g).CurrentValues.SetValues(detector); _db.SaveChanges(); } catch (Exception ex) { var repository = ApplicationEventRepositoryFactory.Create(); var error = new ApplicationEvent(); error.ApplicationName = "MOE.Common"; error.Class = "Models.Repository.DetectorRepository"; error.Function = "Update"; error.Description = ex.Message; error.SeverityLevel = ApplicationEvent.SeverityLevels.High; error.Timestamp = DateTime.Now; repository.Add(error); throw; } } }
public List <RouteSignal> GetByRouteID(int routeID) { var routes = (from r in db.RouteSignals where r.RouteId == routeID select r).ToList(); if (routes.Count > 0) { return(routes); } { var repository = ApplicationEventRepositoryFactory.Create(); var error = new ApplicationEvent(); error.ApplicationName = "MOE.Common"; error.Class = "Models.Repository.ApproachRouteDetailsRepository"; error.Function = "GetByRouteID"; error.Description = "No Route for ID. Attempted ID# = " + routeID; error.SeverityLevel = ApplicationEvent.SeverityLevels.High; error.Timestamp = DateTime.Now; repository.Add(error); throw new Exception("There is no ApproachRouteDetail for this ID"); } }
public void EventExecutionVerification_OnSuccessfulCompletionOfCahceRefresh() { var localBus = new InstanceEventBus(); localBus.Register("in-memory-consul-cache-refresh", new MockCacheRefreshObserver()); var eventData = new ApplicationEvent { Id = Guid.NewGuid().ToString(), Name = "test event", TimeStamp = DateTime.Now }; var configStoreMock = new Mock <IConfigurationStore>(); var sensitiveDataProviderMock = new Mock <ISensitiveDataProvider>(); var dataSet = new Dictionary <string, string>(); dataSet.Add("key", "value"); configStoreMock.Setup(cs => cs.GetAllAsync()).ReturnsAsync(dataSet); var eventHandler = new ConfigurationUpdateEventHandler(configStoreMock.Object, localBus, sensitiveDataProviderMock.Object); var configUpdateObserver = new ConfigurationObserver(eventHandler); configUpdateObserver.Process(eventData); Thread.Sleep(5000); Assert.Equal(1, MockCacheRefreshObserver.Count); configUpdateObserver.Process(eventData); Thread.Sleep(5000); Assert.Equal(2, MockCacheRefreshObserver.Count); }
public List <Controller_Event_Log> GetEventsByEventCodesParamWithOffsetAndLatencyCorrection(string signalId, DateTime startTime, DateTime endTime, List <int> eventCodes, int param, double offset, double latencyCorrection) { try { var events = (from s in _db.Controller_Event_Log where s.SignalID == signalId && s.Timestamp >= startTime && s.Timestamp <= endTime && s.EventParam == param && eventCodes.Contains(s.EventCode) select s).ToList(); events.Sort((x, y) => DateTime.Compare(x.Timestamp, y.Timestamp)); foreach (var cel in events) { cel.Timestamp = cel.Timestamp.AddMilliseconds(offset); cel.Timestamp = cel.Timestamp.AddSeconds(0 - latencyCorrection); } return(events); } catch (Exception ex) { var logRepository = ApplicationEventRepositoryFactory.Create(); var e = new ApplicationEvent(); e.ApplicationName = "MOE.Common"; e.Class = GetType().ToString(); e.Function = "GetEventsByEventCodesParamWithOffsetAndLatencyCorrection"; e.SeverityLevel = ApplicationEvent.SeverityLevels.High; e.Timestamp = DateTime.Now; e.Description = ex.Message; logRepository.Add(e); throw; } }
private void LogRequest(ApplicationEvent eventModel) { _logger.LogInformation("******* Request Received ****"); _logger.LogInformation(JsonConvert.SerializeObject(eventModel)); _logger.LogInformation("***** End of Request ******"); }
private void handleEvent(ApplicationEvent applicationEvent) { if (HandleEvent != null) HandleEvent(applicationEvent); }
public bool Accept(ApplicationEvent applicationEvent) { return(applicationEvent is T); }
public Task SendAsync(ApplicationEvent applicationEvent) { SentEvents.Add(applicationEvent); return(Task.CompletedTask); }
private void Handle(ApplicationEvent @event) { AngularModules.Add(@event.GetValue("ModuleName")); }
public void Notify(ApplicationEvent eventData) { _eventBus.Notify(eventData); }
public async Task make_sure_that_the_Second_handler_is_invoked_if_the_first_fails() { var storage = Substitute.For<IFileStorage>(); var container = Substitute.For<IContainer>(); var scope = Substitute.For<IContainerScope>(); var handler1 = Substitute.For<IApplicationEventSubscriber<ApplicationEvent>>(); var handler2 = Substitute.For<IApplicationEventSubscriber<ApplicationEvent>>(); var ApplicationEvent = new ApplicationEvent(); handler1 .When(x => x.HandleAsync(ApplicationEvent)) .Do(x => { throw new InvalidCastException(); }); storage.PopEventAsync().Returns(Task.FromResult(ApplicationEvent)); container.CreateScope().Returns(scope); scope.ResolveAll(typeof(IApplicationEventSubscriber<ApplicationEvent>)) .Returns(new object[] { handler1, handler2 }); EventHandlerFailedEventArgs actual = null; var sut = new ContainerEventBus(storage, container); sut.HandlerFailed += (sender, args) => actual = args; await sut.PublishAsync(Substitute.For<ApplicationEvent>()); await sut.ExecuteJobAsync(); handler2.ReceivedWithAnyArgs().HandleAsync(null); }
public void AddOrUpdate(Approach approach) { var g = (from r in _db.Approaches where r.ApproachID == approach.ApproachID select r).FirstOrDefault(); if (approach.Detectors != null) { foreach (var det in approach.Detectors) { AddDetectiontypestoDetector(det); } } if (g != null) { try { _db.Entry(g).CurrentValues.SetValues(approach); _db.SaveChanges(); } catch (Exception ex) { var repository = ApplicationEventRepositoryFactory.Create(); var error = new ApplicationEvent { ApplicationName = "MOE.Common", Class = "Models.Repository.ApproachRepository", Function = "Update", Description = ex.Message, SeverityLevel = ApplicationEvent.SeverityLevels.High, Timestamp = DateTime.Now }; repository.Add(error); throw; } } else { try { foreach (var d in approach.Detectors) { if (d.DetectionTypes == null && d.DetectionTypeIDs != null) { d.DetectionTypes = _db.DetectionTypes .Where(dt => d.DetectionTypeIDs.Contains(dt.DetectionTypeID)).ToList(); } } _db.Approaches.Add(approach); _db.SaveChanges(); } catch (Exception ex) { var repository = ApplicationEventRepositoryFactory.Create(); var error = new ApplicationEvent { ApplicationName = "MOE.Common", Class = "Models.Repository.ApproachRepository", Function = "Add", Description = ex.Message, SeverityLevel = ApplicationEvent.SeverityLevels.High, Timestamp = DateTime.Now }; repository.Add(error); throw; } } }
private void Handle(ApplicationEvent @event) { DevDependencies.Add(@event.GetValue("name"), @event.GetValue("version")); }
private void Handle(ApplicationEvent @event) { _eventedJsFiles.Add(@event.GetValue("Src")); }
public override bool Execute(ApplicationEvent Event) { Parent.GetModel().GetCurrentPlayer().ReplaceTile(Event as ReplaceTileEvent); return true; }
public override void InvokeMonitor(MonitorId target, ApplicationEvent e) { m_networkProvider2.RemoteMonitor(target, e); }
public override void SendEvent(MachineId target, ApplicationEvent e) { m_networkProvider2.RemoteSend(target, e); }
/// <summary> /// Initializes a new instance of the <see cref="ApplicationEventMessage" /> class. /// </summary> /// <param name="applicationEvent"> /// The application event. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="applicationEvent" /> is <see langword="null" />. /// </exception> public ApplicationEventMessage(ApplicationEvent applicationEvent) : this(applicationEvent, Guid.NewGuid()) { return; }
public async Task trigger_failed_event_When_handler_throws_an_Exception() { var storage = Substitute.For<IFileStorage>(); var container = Substitute.For<IContainer>(); var scope = Substitute.For<IContainerScope>(); var handler1 = Substitute.For<IApplicationEventSubscriber<ApplicationEvent>>(); var ApplicationEvent = new ApplicationEvent(); handler1 .When(x => x.HandleAsync(ApplicationEvent)) .Do(x => { throw new InvalidCastException(); }); storage.PopEventAsync().Returns(Task.FromResult(ApplicationEvent)); container.CreateScope().Returns(scope); scope.ResolveAll(typeof(IApplicationEventSubscriber<ApplicationEvent>)) .Returns(new object[] { handler1 }); EventHandlerFailedEventArgs actual = null; var sut = new ContainerEventBus(storage, container); sut.HandlerFailed += (sender, args) => actual = args; await sut.PublishAsync(Substitute.For<ApplicationEvent>()); await sut.ExecuteJobAsync(); actual.Should().NotBeNull(); actual.ApplicationEvent.Should().BeSameAs(ApplicationEvent); actual.HandlerCount.Should().Be(1); actual.Failures[0].Handler.Should().Be(handler1); actual.Failures[0].Exception.Should().BeOfType<InvalidCastException>(); }
public EventLoggedEventArgs(ApplicationEvent applicationEvent) { this.ApplicationEvent = applicationEvent ?? throw new ArgumentNullException(nameof(applicationEvent)); }
public override bool Execute(ApplicationEvent Event) { if(!Parent.GetModel().GetCurrentPlayer().MakeMove(Event as PutWordEvent)) { Parent.UpdateView(); return false; } return true; }
public async Task <IList <ApplicationEvent> > GetApplicationEventsAsync(string applicationName, Duration duration, IList <Type> types, CancellationToken token) { await this.InitIfRequiredAsync(token).ConfigureAwait(false); var filter = FilterFactory.CreateApplicationFilter(this.traceStoreReader, types, applicationName); var allApplicationEvents = (await this.traceStoreReader.ReadTraceRecordsAsync(duration, filter, token).ConfigureAwait(false)).Select(oneRecord => ApplicationEventAdapter.Convert(oneRecord)).ToList(); if (this.traceStoreReader.IsPropertyLevelFilteringSupported() || string.IsNullOrWhiteSpace(applicationName)) { return(allApplicationEvents); } // Today, local reader doesn't support filtering, so we filter on the model event. return(allApplicationEvents.Where(oneEvent => oneEvent.ApplicationId.Equals(ApplicationEvent.TransformAppName(applicationName), StringComparison.InvariantCultureIgnoreCase)).ToList()); }
/// <summary> /// Waits for incoming notifications. /// </summary> /// <returns>Returns ApplicationEvent with current information about install/update process. /// Sets .error = true on failure. /// </returns> public ApplicationEvent WaitForEvent() { if (instance == null) Initialize(); ApplicationEvent evt = new ApplicationEvent(); UInt32 data = instance.WaitForEvents(_context, 0xFFFFFFFF); if (data >= (uint)EventReceiveError.Error_First) { evt.error = true; return evt; } UInt32 state = 0, progress = 0, error = 0; ApplicationApi.instance.DecodeState(data, out state, out progress, out error); //uint st = state; evt.state = (InstallationState)state;//Enum.ToObject(typeof(ApplicationApi.ApplicationContext.InstallationState), state); if (progress > 100) progress = 0; evt.progress = progress; evt.error = (error > 0) ? true : false; return evt; }
public override bool Execute(ApplicationEvent Event) { Parent.GetModel().GetCurrentPlayer().Pass(); return true; }
public override void Process(ApplicationEvent msg) { base.Process(msg); _eventHandler.HandleEvent(); }
protected virtual void Publish(ApplicationEvent appEvent) { _bus.Publish(appEvent); }
public void Handle(ApplicationEvent applicationEvent) { Handle((T)applicationEvent); }
public abstract bool Execute(ApplicationEvent Event);
/// <summary> /// Initializes a new instance of the <see cref="ApplicationEventMessage" /> class. /// </summary> /// <param name="applicationEvent"> /// The application event. /// </param> /// <param name="correlationIdentifier"> /// A unique identifier that is assigned to related messages. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="applicationEvent" /> is <see langword="null" />. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="correlationIdentifier" /> is equal to <see cref="Guid.Empty" />. /// </exception> public ApplicationEventMessage(ApplicationEvent applicationEvent, Guid correlationIdentifier) : this(applicationEvent, correlationIdentifier, Guid.NewGuid()) { return; }
/// <summary> /// Initializes a new instance of the <see cref="ApplicationEventMessage" /> class. /// </summary> /// <param name="applicationEvent"> /// The application event. /// </param> /// <param name="correlationIdentifier"> /// A unique identifier that is assigned to related messages. /// </param> /// <param name="identifier"> /// A unique identifier for the message. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="applicationEvent" /> is <see langword="null" />. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="correlationIdentifier" /> is equal to <see cref="Guid.Empty" /> -or- <paramref name="identifier" /> is /// equal to <see cref="Guid.Empty" />. /// </exception> public ApplicationEventMessage(ApplicationEvent applicationEvent, Guid correlationIdentifier, Guid identifier) : base(correlationIdentifier, identifier) { ApplicationEvent = applicationEvent.RejectIf().IsNull(nameof(applicationEvent)); }
public void Notify(ApplicationEvent eventData) { _distributionChannel.Notify(eventData); }
public IActionResult Publish(ApplicationEvent eventModel) { LogHeaders(); LogRequest(eventModel); return(Ok("Received Event")); }
private void Handle(ApplicationEvent @event) { _seedDataRequiredEvents.Add(@event.AdditionalInfo[EntityFrameworkEvents.SeedDataRequiredEventKey]); }
public override bool Execute(ApplicationEvent Event) { NewGameEvent NewGameEvent = Event as NewGameEvent; if(NewGameEvent == null) { return false; } Parent.GetModel().ResetGame(); List<Player> Players = new List<Player>(); List<Tuple<bool, bool>> PlayerInfoList = new List<Tuple<bool, bool>>(); foreach(PlayerIdEnum PlayerId in Enum.GetValues(typeof(PlayerIdEnum))) { PlayerInfoList.Add(NewGameEvent.GetPlayerInfo(PlayerId)); } foreach(Tuple<bool, bool> PlayerInfo in PlayerInfoList) { bool ShouldAddPlayer = PlayerInfo.Item1; bool isComputer = PlayerInfo.Item2; int PlayerIndex = 1; if(ShouldAddPlayer) { if(isComputer) { Parent.GetModel().AddPlayer(new AIPlayer(Parent.GetModel())); } else { Parent.GetModel().AddPlayer(new HumanPlayer("Player" + PlayerIndex++, Parent.GetModel())); } } } Parent.UpdateView(); return true; }