public virtual void Run() { StartGame(); RenderGame(); long time = _stopwatch.ElapsedMilliseconds; for (;;) { SystemEvents.CheckEvents(); if (_updateRate == 0) { continue; } UpdateGame(); RenderGame(); if (_updateRate == 0 || _updateRate >= 60) { continue; } long period = 1000 / _updateRate; while (_stopwatch.ElapsedMilliseconds - time < period) { SystemEvents.CheckEvents(); } time += period; } }
private void UIUpdateTimer_Tick(object sender, EventArgs e) { SystemEvents.OnUpdateTimerTick(); StripStatus_Clock.Text = DateTime.Now.ToString("HH:mm:ss"); }
/// <exception cref="InvalidOperationException"> /// Attempt to associate non-null <paramref name="tuple"/> with <paramref name="key"/> of unknown type. /// </exception> internal EntityState UpdateStateInCache(Key key, Tuple tuple, bool isStale) { var result = EntityStateCache[key, true]; if (result == null) { if (!key.HasExactType && tuple != null) { throw Exceptions.InternalError( Strings.ExCannotAssociateNonEmptyEntityStateWithKeyOfUnknownType, OrmLog.Instance); } result = AddEntityStateToCache(key, tuple, isStale); SystemEvents.NotifyEntityMaterialized(result); Events.NotifyEntityMaterialized(result); } else { if (!result.Key.HasExactType && key.HasExactType) { EntityStateCache.RemoveKey(result.Key); result = AddEntityStateToCache(key, tuple, result.IsStale); } result.Update(tuple); result.IsStale = isStale; if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXUpdatingCacheY, this, result); } } return(result); }
[InlineData(30000)] // 30s public void TimerElapsedIsRoughlyEquivalentToInterval(int interval) { const double permittedProportionUnder = -0.1; const double permittedProportionOver = 0.5; var elapsed = new AutoResetEvent(false); IntPtr timer = IntPtr.Zero; var stopwatch = new Stopwatch(); TimerElapsedEventHandler handler = (sender, args) => { if (args?.TimerId == timer) { stopwatch.Stop(); elapsed.Set(); } }; SystemEvents.TimerElapsed += handler; try { timer = SystemEvents.CreateTimer(interval); stopwatch.Start(); Assert.True(elapsed.WaitOne(interval * SystemEventsTest.ExpectedEventMultiplier)); var proportionDifference = (double)(stopwatch.ElapsedMilliseconds - interval) / interval; Assert.True(permittedProportionUnder < proportionDifference && proportionDifference < permittedProportionOver, $"Timer should fire less than {permittedProportionUnder * 100.0}% before and less than {permittedProportionOver * 100.0}% after expected interval {interval}, actual: {stopwatch.ElapsedMilliseconds}, difference: {proportionDifference * 100.0}%"); } finally { SystemEvents.TimerElapsed -= handler; SystemEvents.KillTimer(timer); } }
public void TestEventsAreSentCorrectly() { var ex = new Exception("Hello"); string msg1 = "Event1"; string msg2 = "Event2"; SystemEvents.DispatchDiagnosicEvent(msg1, LogLevel.Error); SystemEvents.DispatchDiagnosicEvent(msg2, LogLevel.Fatal, ex); var events = _genertorUnderTest.GetEvents().Cast <Diagnostic>().ToList(); Assert.AreEqual(2, events.Count()); var pid = Process.GetCurrentProcess().Id; var tid = Thread.CurrentThread.ManagedThreadId; var actualEvent = events.ElementAt(0); Assert.AreEqual(pid, actualEvent.Payload.First().ProcessId); Assert.AreEqual(tid, actualEvent.Payload.First().ThreadId); Assert.AreEqual(msg1, actualEvent.Payload.First().Message); Assert.AreEqual(LogLevel.Error.ToString(), actualEvent.Payload.First().Severity); Assert.AreEqual(ThreadContext.Get().ExecutionId, actualEvent.Payload.First().CorrelationId); actualEvent = events.ElementAt(1); Assert.AreEqual(pid, actualEvent.Payload.First().ProcessId); Assert.AreEqual(tid, actualEvent.Payload.First().ThreadId); Assert.AreEqual(ex.FormatExceptionMessage(msg2), actualEvent.Payload.First().Message); Assert.AreEqual(LogLevel.Fatal.ToString(), actualEvent.Payload.First().Severity); Assert.AreEqual(ThreadContext.Get().ExecutionId, actualEvent.Payload.First().CorrelationId); }
public void On(SystemEvents @event, Action callback) { switch (@event) { case SystemEvents.connect: OnConnect = callback; break; case SystemEvents.connectTimeOut: OnConnectTimeOut = callback; break; case SystemEvents.reconnectAttempt: OnReconnectAttempt = callback; break; case SystemEvents.reconnectFailed: OnReconnectFailed = callback; break; case SystemEvents.disconnect: OnDisconnect = callback; break; default: Debug.LogErrorFormat("{0} event can not be handled by Action callback (Try the other On() methods)", @event.ToString()); break; } }
internal void CommitTransaction(Transaction transaction) { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXCommittingTransaction, this); } SystemEvents.NotifyTransactionPrecommitting(transaction); Events.NotifyTransactionPrecommitting(transaction); Persist(PersistReason.Commit); ValidationContext.Validate(ValidationReason.Commit); SystemEvents.NotifyTransactionCommitting(transaction); Events.NotifyTransactionCommitting(transaction); Handler.CompletingTransaction(transaction); if (transaction.IsNested) { Handler.ReleaseSavepoint(transaction); } else { Handler.CommitTransaction(transaction); } }
internal void RollbackTransaction(Transaction transaction) { try { OrmLog.Debug(Strings.LogSessionXRollingBackTransaction, this); SystemEvents.NotifyTransactionRollbacking(transaction); Events.NotifyTransactionRollbacking(transaction); } finally { try { Handler.CompletingTransaction(transaction); } finally { try { if (Configuration.Supports(SessionOptions.SuppressRollbackExceptions)) { RollbackWithSuppression(transaction); } else { Rollback(transaction); } } finally { if (!persistingIsFailed || !Configuration.Supports(SessionOptions.NonTransactionalReads)) { CancelEntitySetsChanges(); ClearChangeRegistry(); NonPairedReferencesRegistry.Clear(); EntitySetChangeRegistry.Clear(); } persistingIsFailed = false; } } } }
public bool IsEnable(object Sender, object Element) { DateTime startDate = User.GetLocalDate(DateTime.UtcNow).Date.AddDays(-6); DateTime endDate = DateTime.Today.AddDays(1); return(SystemEvents.CheckSystemEvents(startDate, endDate)); }
internal void CompleteTransaction(Transaction transaction) { userDefinedQueryTasks.Clear(); pinner.ClearRoots(); ValidationContext.Reset(); Transaction = transaction.Outer; switch (transaction.State) { case TransactionState.Committed: if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXCommittedTransaction, this); } SystemEvents.NotifyTransactionCommitted(transaction); Events.NotifyTransactionCommitted(transaction); break; case TransactionState.RolledBack: if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXRolledBackTransaction, this); } SystemEvents.NotifyTransactionRollbacked(transaction); Events.NotifyTransactionRollbacked(transaction); break; default: throw new ArgumentOutOfRangeException("transaction.State"); } }
public static void Main(string[] args) { Initialize(); stopWatch.Start(); while (loop) { //Thread.Sleep(10); SystemEvents.CheckEvents(); Update(); Render(); #region "Calculation for frame rate" mFrame++; mT = stopWatch.ElapsedMilliseconds; if (mT - mT0 >= 1000) { float seconds = (mT - mT0) / 1000; mFps = mFrame / seconds; mT0 = mT; mFrame = 0; } #endregion } term(); }
private void btnSave_ServerClick(object sender, EventArgs e) { int ObjectTypeId = int.Parse(pc["GlobalSubscription_ObjectType"]); // —формируем массив выбранных элементов, представив их в виде строки EventTypeId_ObjectRoleId ArrayList selectedValues = new ArrayList(); foreach (DataGridItem item in grdMain.Items) { string sEventTypeId = item.Cells[0].Text; for (int i = 2; i < item.Cells.Count; i++) { TableCell cell = item.Cells[i]; foreach (Control ctrl in cell.Controls) { CheckBox chk = ctrl as CheckBox; if (chk != null && chk.Checked) { selectedValues.Add(String.Format("{0}_{1}", sEventTypeId, chk.ID.Substring(5))); } } } } SystemEvents.AddGlobalSubscriptions(ObjectTypeId, selectedValues); }
private TransactionScope OpenTransactionScope(Transaction transaction) { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXOpeningTransaction, this); } SystemEvents.NotifyTransactionOpening(transaction); Events.NotifyTransactionOpening(transaction); Transaction = transaction; transaction.Begin(); IDisposable logIndentScope = null; if (IsDebugEventLoggingEnabled) { logIndentScope = OrmLog.DebugRegion(Strings.LogSessionXTransaction, this); } SystemEvents.NotifyTransactionOpened(transaction); Events.NotifyTransactionOpened(transaction); return(new TransactionScope(transaction, logIndentScope)); }
private void FormMain_FormClosing(object sender, FormClosingEventArgs e) { if (Utility.Configuration.Config.Life.ConfirmOnClosing) { if (MessageBox.Show(SoftwareInformation.SoftwareNameJapanese + " を終了しますか?", "確認", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No) { e.Cancel = true; return; } } Utility.Logger.Add(2, SoftwareInformation.SoftwareNameJapanese + " を終了しています…"); UIUpdateTimer.Stop(); fBrowser.CloseBrowser(); if (!Directory.Exists("Settings")) { Directory.CreateDirectory("Settings"); } SystemEvents.OnSystemShuttingDown(); SaveLayout(Configuration.Config.Life.LayoutFilePath); }
public void InvokeOnEventsThreadRunsAsynchronously() { var invoked = new AutoResetEvent(false); SystemEvents.InvokeOnEventsThread(new Action(() => invoked.Set())); Assert.True(invoked.WaitOne(PostMessageWait)); }
private async ValueTask <TransactionScope> OpenTransactionScope( Transaction transaction, bool isAsync, CancellationToken token = default) { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXOpeningTransaction, this); } SystemEvents.NotifyTransactionOpening(transaction); Events.NotifyTransactionOpening(transaction); Transaction = transaction; if (isAsync) { await transaction.BeginAsync(token).ConfigureAwait(false); } else { transaction.Begin(); } IDisposable logIndentScope = null; if (IsDebugEventLoggingEnabled) { logIndentScope = OrmLog.DebugRegion(Strings.LogSessionXTransaction, this); } SystemEvents.NotifyTransactionOpened(transaction); Events.NotifyTransactionOpened(transaction); return(new TransactionScope(transaction, logIndentScope)); }
public void InvokeOnEventsThreadRunsOnSameThreadAsOtherEvents() { int expectedThreadId = -1, actualThreadId = -1; var invoked = new AutoResetEvent(false); EventHandler handler = (sender, args) => { expectedThreadId = Environment.CurrentManagedThreadId; }; try { // force a TimeChanged event to get the event thread ID SystemEvents.TimeChanged += handler; SendMessage(User32.WM_REFLECT + User32.WM_TIMECHANGE, IntPtr.Zero, IntPtr.Zero); Assert.NotEqual(-1, expectedThreadId); SystemEvents.InvokeOnEventsThread(new Action(() => { actualThreadId = Environment.CurrentManagedThreadId; invoked.Set(); })); Assert.True(invoked.WaitOne(PostMessageWait)); Assert.Equal(expectedThreadId, actualThreadId); } finally { SystemEvents.TimeChanged -= handler; invoked.Dispose(); } }
// IDisposable implementation /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (isDisposed) { return; } try { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXDisposing, this); } SystemEvents.NotifyDisposing(); Events.NotifyDisposing(); Services.DisposeSafely(); Handler.DisposeSafely(); CommandProcessorContextProvider.DisposeSafely(); Domain.ReleaseSingleConnection(); disposableSet.DisposeSafely(); disposableSet = null; EntityChangeRegistry.Clear(); EntitySetChangeRegistry.Clear(); EntityStateCache.Clear(); ReferenceFieldsChangesRegistry.Clear(); NonPairedReferencesRegistry.Clear(); } finally { isDisposed = true; } }
private void grdMain_UpdateCommand(object source, DataGridCommandEventArgs e) { int EventTypeId = int.Parse(e.CommandArgument.ToString()); ArrayList selectedValues = new ArrayList(); for (int i = 2; i < e.Item.Cells.Count; i++) { TableCell cell = e.Item.Cells[i]; foreach (Control ctrl in cell.Controls) { CheckBox chk = ctrl as CheckBox; if (chk != null && chk.Checked) { selectedValues.Add(int.Parse(chk.ID.Substring(5))); } } } SystemEvents.AddPersonalSubscription(EventTypeId, selectedValues); grdMain.EditItemIndex = -1; BindData(); }
public void TestQueueSizeDoesNotPassLimit() { var internalQueueSize = (uint)(AgentConfiguration.RemoteConfiguration.MaxLocalCacheSize * 0.2); string msg1 = "Event1"; SystemEvents.DispatchDiagnosicEvent(msg1, LogLevel.Error); var events = _genertorUnderTest.GetEvents().Cast <Diagnostic>(); var eventSize = events.First().EstimatedSize; uint totalSize = 0; while (totalSize < 6 * internalQueueSize) { SystemEvents.DispatchDiagnosicEvent(msg1, LogLevel.Error); totalSize += eventSize; } events = _genertorUnderTest.GetEvents().Cast <Diagnostic>(); uint actualSize = 0; foreach (var ev in events) { actualSize += ev.EstimatedSize; } Assert.IsTrue(actualSize <= internalQueueSize); }
public void StartListener() { var createDeviceNotifierDelegate = new CreateDeviceNotifierDelegate(CreateDeviceNotifier); SystemEvents.InvokeOnEventsThread(createDeviceNotifierDelegate); _thread = new Thread(ListeningThread); _thread.Start(); }
public HandlingEventServiceImpl(HandlingEventRepository handlingEventRepository, SystemEvents systemEvents, HandlingEventFactory handlingEventFactory) { this.handlingEventRepository = handlingEventRepository; this.systemEvents = systemEvents; this.handlingEventFactory = handlingEventFactory; }
public CargoUpdater(SystemEvents systemEvents, CargoRepository cargoRepository, HandlingEventRepository handlingEventRepository) { this.systemEvents = systemEvents; this.cargoRepository = cargoRepository; this.handlingEventRepository = handlingEventRepository; }
internal static extern IntPtr SetWinEventHook( SystemEvents eventMin, SystemEvents eventMax, IntPtr hmodWinEventProc, SystemEventHandler lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
/// <summary> /// Register events /// </summary> public static void RegisterEvents() { SqlQuery.OnQueryExecuted += EventHandlers.OnQueryExecutedHandler; //register events on global storage SystemEvents.Common.RegisterEventGroup(nameof(SqlQuery), SystemEvents.GetEvents(typeof(SqlQuery))); SystemEvents.Common.RegisterEventGroup(nameof(Entities), SystemEvents.GetEvents(typeof(Entities))); }
public void ConcurrentTimers() { const int NumConcurrentTimers = 10; var timersSignalled = new Dictionary <IntPtr, bool>(); int numSignaled = 0; var elapsed = new AutoResetEvent(false); TimerElapsedEventHandler handler = (sender, args) => { bool signaled = false; lock (timersSignalled) { if (timersSignalled.TryGetValue(args.TimerId, out signaled) && !signaled) { timersSignalled[args.TimerId] = true; if (Interlocked.Increment(ref numSignaled) == NumConcurrentTimers) { elapsed.Set(); } } } }; SystemEvents.TimerElapsed += handler; try { if (PlatformDetection.IsFullFramework) { // desktop has a bug where it will allow EnsureSystemEvents to proceed without actually creating the HWND SystemEventsTest.WaitForSystemEventsWindow(); } for (int i = 0; i < NumConcurrentTimers; i++) { lock (timersSignalled) { timersSignalled[SystemEvents.CreateTimer(TimerInterval)] = false; } } Assert.True(elapsed.WaitOne(TimerInterval * SystemEventsTest.ExpectedEventMultiplier)); lock (timersSignalled) { foreach (var timer in timersSignalled.Keys.ToArray()) { Assert.True(timersSignalled[timer]); SystemEvents.KillTimer(timer); } } } finally { SystemEvents.TimerElapsed -= handler; elapsed.Dispose(); } }
private static void ObjectModified(object sender, BusinessObjectEventArgs e) { MetaClass metaClass = e.Object.GetMetaType(); if (ListManager.MetaClassIsList(metaClass)) { SystemEvents.AddSystemEvents(SystemEventTypes.List_Updated_Data, ListManager.GetListIdByClassName(metaClass.Name)); } }
static extern IntPtr SetWinEventHook( SystemEvents eventMin , SystemEvents eventMax , IntPtr hmodWinEventProc , WinEventDelegate lpfnWinEventProc , uint idProcess , uint idThread , uint dwFlags );
/// <summary> /// Register app events /// </summary> public static void RegisterEvents() { Authorization.OnUserLogIn += delegate { }; Authorization.OnUserLogout += delegate { }; Users.OnUserCreated += delegate { }; //register events on global storage SystemEvents.Common.RegisterEventGroup(nameof(Authorization), SystemEvents.GetEvents(typeof(Authorization))); SystemEvents.Common.RegisterEventGroup(nameof(Users), SystemEvents.GetEvents(typeof(Users))); }
public void StopRecording() { EIT?.CompleteAdding(); ECG?.CompleteAdding(); SystemEvents?.StopRecording(); RPosition?.StopRecording(); Tags?.StopRecording(); RecordingInProgress = false; }
public void setUp() { systemEvents = MockRepository.GenerateMock<SystemEvents>(); cargoRepository = new CargoRepositoryInMem(); handlingEventRepository = new HandlingEventRepositoryInMem(); locationRepository = new LocationRepositoryInMem(); voyageRepository = new VoyageRepositoryInMem(); trackingIdFactory = new TrackingIdFactoryInMem(); handlingEventFactory = new HandlingEventFactory(cargoRepository, voyageRepository, locationRepository); cargoUpdater = new CargoUpdater(systemEvents, cargoRepository, handlingEventRepository); }
protected void setUp() { cargoRepository = MockRepository.GenerateMock<CargoRepository>(); voyageRepository = MockRepository.GenerateMock<VoyageRepository>(); handlingEventRepository = MockRepository.GenerateMock<HandlingEventRepository>(); locationRepository = MockRepository.GenerateMock<LocationRepository>(); systemEvents = MockRepository.GenerateMock<SystemEvents>(); HandlingEventFactory handlingEventFactory = new HandlingEventFactory(cargoRepository, voyageRepository, locationRepository); service = new HandlingEventServiceImpl(handlingEventRepository, systemEvents, handlingEventFactory); }
public void Init() { systemUnits = new SystemEvents(); AddActionClassesToList(systemUnits); }