static void Main() { // Create an event to signal the timeout count threshold in the // timer callback. AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(10); // Create an inferred delegate that invokes methods for the timer. TimerCallback tcb = statusChecker.CheckStatus; // Create a timer that signals the delegate to invoke // CheckStatus after one second, and every 1/4 second // thereafter. Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff")); Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250); // When autoEvent signals, change the period to every // 1/2 second. autoEvent.WaitOne(5000, false); stateTimer.Change(0, 500); Console.WriteLine("\nChanging period.\n"); // When autoEvent signals the second time, dispose of // the timer. autoEvent.WaitOne(5000, false); stateTimer.Dispose(); Console.WriteLine("\nDestroying timer."); }
protected virtual async Task <SoapGetProductsResponse> GetProductsAsync(string productType, bool productTypeShouldBeExcluded, string productIdLike, DateTime?updatedFrom) { try { var filters = new filters { filter = new associativeEntity[0], complex_filter = new complexFilter[0] }; if (productType != null) { AddFilter(filters, productType, "type", productTypeShouldBeExcluded ? "neq" : "eq"); } if (updatedFrom.HasValue) { AddFilter(filters, updatedFrom.Value.ToSoapParameterString(), "updated_at", "from"); } if (!string.IsNullOrWhiteSpace(productIdLike)) { AddFilter(filters, productIdLike, "product_id", "like"); } var store = string.IsNullOrWhiteSpace(this.Store) ? null : this.Store; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new catalogProductListResponse(); var privateClient = this._clientFactory.GetClient(); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshClient(privateClient); var sessionId = await this.GetSessionId().ConfigureAwait(false); using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) res = await privateClient.catalogProductListAsync(sessionId.SessionId, filters, store).ConfigureAwait(false); }).ConfigureAwait(false); return(new SoapGetProductsResponse(res)); } catch (Exception exc) { throw new MagentoSoapException(string.Format("An error occured during GetProductsAsync()"), exc); } }
public virtual async Task <ProductAttributeMediaListResponse> GetProductAttributeMediaListAsync(GetProductAttributeMediaListRequest getProductAttributeMediaListRequest, bool throwException = true) { Func <bool, Task <catalogProductAttributeMediaListResponse> > call = async(keepAlive) => { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var privateClient = this._clientFactory.GetClient(keepAlive); var res = new catalogProductAttributeMediaListResponse(); var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshClient(privateClient, keepAlive); var sessionId = await this.GetSessionId().ConfigureAwait(false); using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) res = await privateClient.catalogProductAttributeMediaListAsync(sessionId.SessionId, getProductAttributeMediaListRequest.ProductId, "0", "1").ConfigureAwait(false); return(res); }; try { var keepAlive = false; var res = new catalogProductAttributeMediaListResponse(); await ActionPolicies.GetAsync.Do(async() => { try { res = await call(keepAlive).ConfigureAwait(false); return; } catch (CommunicationException) { keepAlive = !keepAlive; } res = await call(keepAlive).ConfigureAwait(false); }).ConfigureAwait(false); return(new ProductAttributeMediaListResponse(res, getProductAttributeMediaListRequest.ProductId, getProductAttributeMediaListRequest.Sku)); } catch (Exception exc) { throw new MagentoSoapException(string.Format("An error occured during GetProductAttributeMediaListAsync({0})", getProductAttributeMediaListRequest), exc); } }
public virtual async Task< GetOrdersResponse > GetOrdersAsync( DateTime modifiedFrom, DateTime modifiedTo, Mark mark = null ) { try { filters filters; if( string.IsNullOrWhiteSpace( this.Store ) ) filters = new filters { complex_filter = new complexFilter[ 2 ] }; else { filters = new filters { complex_filter = new complexFilter[ 3 ] }; filters.complex_filter[ 2 ] = new complexFilter { key = "store_id", value = new associativeEntity { key = "in", value = this.Store } }; } filters.complex_filter[ 1 ] = new complexFilter { key = "updated_at", value = new associativeEntity { key = "from", value = modifiedFrom.ToSoapParameterString() } }; filters.complex_filter[ 0 ] = new complexFilter { key = "updated_at", value = new associativeEntity { key = "to", value = modifiedTo.ToSoapParameterString() } }; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new salesOrderListResponse(); var privateClient = this._clientFactory.GetClient(); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshClient( privateClient ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) res = await privateClient.salesOrderListAsync( sessionId.SessionId, filters ).ConfigureAwait( false ); } ).ConfigureAwait( false ); //crutch for magento 1.7 res.result = res.result.Where( x => Extensions.ToDateTimeOrDefault( x.updated_at ) >= modifiedFrom && Extensions.ToDateTimeOrDefault( x.updated_at ) <= modifiedTo ).ToArray(); return new GetOrdersResponse( res ); } catch( Exception exc ) { throw new MagentoSoapException( $"An error occured during GetOrdersAsync(modifiedFrom:{modifiedFrom},modifiedTo{modifiedTo})", exc ); } }
public virtual async Task <OrderInfoResponse> GetOrderAsync(string incrementId) { try { //var frameworkSearchFilterGroups = new List< FrameworkSearchFilterGroup > //{ // new FrameworkSearchFilterGroup() { filters = new[] { new FrameworkFilter() { field = "increment_id", conditionType = "eq", value = incrementId } } }, //}; //if( string.IsNullOrWhiteSpace( this.Store ) ) // frameworkSearchFilterGroups.Add( new FrameworkSearchFilterGroup() { filters = new[] { new FrameworkFilter() { field = "store_Id", conditionType = "eq", value = this.Store } } } ); var filters = new SalesOrderRepositoryV1GetRequest { id = int.Parse(incrementId) }; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new salesOrderRepositoryV1GetResponse1(); var privateClient = this.CreateMagentoSalesOrderRepositoryServiceClient(this.BaseMagentoUrl); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; if (privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening) { privateClient = this.CreateMagentoSalesOrderRepositoryServiceClient(this.BaseMagentoUrl); } using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) res = await privateClient.salesOrderRepositoryV1GetAsync(filters).ConfigureAwait(false); }).ConfigureAwait(false); return(new OrderInfoResponse(res)); } catch (Exception exc) { throw new MagentoSoapException(string.Format("An error occured during GetOrderAsync(incrementId:{0})", incrementId), exc); } }
public virtual async Task <OrderInfoResponse> GetOrderAsync(string incrementId, Mark mark = null) { try { var filters = new SalesOrderRepositoryV1GetRequest { id = int.Parse(incrementId) }; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new salesOrderRepositoryV1GetResponse1(); var privateClient = this._clientFactory.CreateMagentoSalesOrderRepositoryServiceClient(); await ActionPolicies.GetWithMarkAsync(mark).Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshMagentoSalesOrderRepositoryServiceClient(privateClient); using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) try { res = await privateClient.salesOrderRepositoryV1GetAsync(filters).ConfigureAwait(false); } catch (Exception ex) { if (ex.Message.ToLower() == "requested entity doesn't exist") { res = null; return; } throw; } }).ConfigureAwait(false); return(res == null ? null : new OrderInfoResponse(res)); } catch (Exception exc) { throw new MagentoSoapException($"An error occured during GetOrderAsync(incrementId:{incrementId}) ", exc, mark); } }
public static byte[] GetRawImage(Tensor imageTensorF, float scale = 1.0f, int channels = 3, Status status = null) { using (StatusChecker checker = new StatusChecker(status)) { var graph = new Graph(); Operation input = graph.Placeholder(imageTensorF.Type); Tensor scaleTensor = new Tensor(scale); Operation scaleOp = graph.Const(scaleTensor, scaleTensor.Type, opName: "scale"); Operation scaled = graph.Mul(input, scaleOp); Operation byteCaster = graph.Cast(scaled, DstT: DataType.Uint8); //cast to byte //Operation scaled = graph. Session session = new Session(graph); Tensor[] imageResults = session.Run(new Output[] { input }, new Tensor[] { imageTensorF }, new Output[] { byteCaster }); byte[] raw = imageResults[0].Flat <byte>(); if (channels == 3) { return(raw); } else if (channels == 4) { int pixelCount = raw.Length / 3; byte[] colors = new byte[pixelCount * 4]; for (int i = 0; i < pixelCount; i++) { colors[i * 4] = raw[i * 3]; colors[i * 4 + 1] = raw[i * 3 + 1]; colors[i * 4 + 2] = raw[i * 3 + 2]; colors[i * 4 + 3] = (byte)255; } return(colors); } else { throw new Exception(String.Format("Channel count of {0} is not supported", channels)); } } }
public virtual async Task <CatalogProductAttributeInfoResponse> GetManufacturersInfoAsync(string attribute) { try { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new catalogProductAttributeInfoResponse(); var privateClient = this._clientFactory.GetClient(); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshClient(privateClient); var sessionId = await this.GetSessionId().ConfigureAwait(false); try // this try catch block is crunch for 1.7 { using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) { res = await privateClient.catalogProductAttributeInfoAsync(sessionId.SessionId, attribute).ConfigureAwait(false); } } catch (Exception exc) { if (exc.Message.ToLower().Contains("Procedure 'catalogProductAttributeInfoRequestParam' not present".ToLower()) && this.StoreVersion.StartsWith("1.7")) { res = null; } else { throw; } } }).ConfigureAwait(false); return(new CatalogProductAttributeInfoResponse(res)); } catch (Exception exc) { throw new MagentoSoapException(string.Format("An error occured during GetManufacturerAsync()"), exc); } }
public virtual async Task <InventoryStockItemListResponse> GetStockItemsAsync(List <string> skusOrIds) { try { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var privateClient = this.CreateMagentoCatalogInventoryStockServiceClient(this.BaseMagentoUrl); var responses = await skusOrIds.ProcessInBatchAsync(10, async x => { var res = new catalogInventoryStockRegistryV1GetStockItemBySkuResponse1(); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; if (privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening) { privateClient = this.CreateMagentoCatalogInventoryStockServiceClient(this.BaseMagentoUrl); } using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) { var catalogInventoryStockRegistryV1GetStockItemBySkuRequest = new CatalogInventoryStockRegistryV1GetStockItemBySkuRequest() { productSku = x }; res = await privateClient.catalogInventoryStockRegistryV1GetStockItemBySkuAsync(catalogInventoryStockRegistryV1GetStockItemBySkuRequest).ConfigureAwait(false); } }).ConfigureAwait(false); return(Tuple.Create(x, res.catalogInventoryStockRegistryV1GetStockItemBySkuResponse.result)); }).ConfigureAwait(false); return(new InventoryStockItemListResponse(responses)); } catch (Exception exc) { var productsBriefInfo = string.Join("|", skusOrIds); throw new MagentoSoapException(string.Format("An error occured during GetStockItemsAsync({0})", productsBriefInfo), exc); } }
public virtual async Task< GetOrdersResponse > GetOrdersAsync( IEnumerable< string > ordersIds ) { var ordersIdsAgregated = string.Empty; try { ordersIdsAgregated = string.Join( ",", ordersIds ); filters filters; if( string.IsNullOrWhiteSpace( this.Store ) ) filters = new filters { complex_filter = new complexFilter[ 1 ] }; else { filters = new filters { complex_filter = new complexFilter[ 2 ] }; filters.complex_filter[ 1 ] = new complexFilter { key = "store_id", value = new associativeEntity { key = "in", value = this.Store } }; } filters.complex_filter[ 0 ] = new complexFilter { key = "increment_id", value = new associativeEntity { key = "in", value = ordersIdsAgregated } }; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new salesOrderListResponse(); var privateClient = this._clientFactory.GetClient(); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshClient( privateClient ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) res = await privateClient.salesOrderListAsync( sessionId.SessionId, filters ).ConfigureAwait( false ); } ).ConfigureAwait( false ); return new GetOrdersResponse( res ); } catch( Exception exc ) { throw new MagentoSoapException( $"An error occured during GetOrdersAsync({ordersIdsAgregated})", exc ); } }
public Sarmiento() { InitializeComponent(); DataContext = ViewModel; Loaded += Page_Loaded; Unloaded += (sender, args) => { DataService.CancelRequest(); _dataRealTimeService.CancelRequest(); }; StatusChecker.Check("Trenes.Sarmiento"); ViewModel.Ramales.Clear(); DataService.EndRequest = EndRequest; DataService.StartRequest = StartRequest; }
public void CheckStatus_HasNan_CreatesSingleAlert() { // Arrange var s = new FileStream(fileWithBadNAN, FileMode.Open); string contents = convertStreamToString(s); var e = new TOA5Extractor( "CookEastEcTower_Flux_Raw_2017_11_03_1300_badNAN.dat", contents, -8); var a = new MockTweeter(); StatusChecker sut = new StatusChecker(e, a); // Act var alerts = sut.CheckStatus(); // Assert Assert.Single(alerts); }
public virtual async Task <ProductAttributeMediaListResponse> GetProductAttributeMediaListAsync(GetProductAttributeMediaListRequest getProductAttributeMediaListRequest, bool throwException = true) { try { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var privateClient = this.CreateMagentocatalogProductAttributeMediaGalleryRepositoryServiceClient(this.BaseMagentoUrl); var res = new catalogProductAttributeMediaGalleryManagementV1GetListResponse1(); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; if (privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening) { privateClient = this.CreateMagentocatalogProductAttributeMediaGalleryRepositoryServiceClient(this.BaseMagentoUrl); } var catalogProductAttributeMediaGalleryManagementV1GetListRequest = new CatalogProductAttributeMediaGalleryManagementV1GetListRequest() { sku = getProductAttributeMediaListRequest.Sku }; using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) res = await privateClient.catalogProductAttributeMediaGalleryManagementV1GetListAsync(catalogProductAttributeMediaGalleryManagementV1GetListRequest).ConfigureAwait(false); }).ConfigureAwait(false); return(new ProductAttributeMediaListResponse(res, getProductAttributeMediaListRequest.ProductId, getProductAttributeMediaListRequest.Sku)); } catch (Exception exc) { if (throwException) { throw new MagentoSoapException(string.Format("An error occured during GetProductAttributeMediaListAsync({0})", getProductAttributeMediaListRequest), exc); } else { return(new ProductAttributeMediaListResponse(exc)); } } }
public virtual async Task <CatalogProductInfoResponse> GetProductInfoAsync(CatalogProductInfoRequest catalogProductInfoRequest, bool throwException = true) { try { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new catalogProductRepositoryV1GetResponse1(); var privateClient = this._clientFactory.CreateMagentoCatalogProductRepositoryServiceClient(); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshMagentoCatalogProductRepositoryServiceClient(privateClient); // we don't need them, since Magento 2.0 returns all attributes //var attributes = new catalogProductRequestAttributes { additional_attributes = custAttributes ?? new string[ 0 ] }; using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) { var catalogProductRepositoryV1GetRequest = new CatalogProductRepositoryV1GetRequest() { sku = catalogProductInfoRequest.Sku }; res = await privateClient.catalogProductRepositoryV1GetAsync(catalogProductRepositoryV1GetRequest).ConfigureAwait(false); } }).ConfigureAwait(false); return(new CatalogProductInfoResponse(res)); } catch (Exception exc) { if (throwException) { throw new MagentoSoapException($"An error occured during GetProductInfoAsync({catalogProductInfoRequest.ToJson()})", exc); } else { return(new CatalogProductInfoResponse(exc)); } } }
public void CheckStatus_HasNanAtOkLocations_NoAlert() { // Arrange var s = new FileStream(fileWithNANOkLocations, FileMode.Open); string contents = convertStreamToString(s); var e = new TOA5Extractor( "CookEastEcTower_Flux_Raw_2017_11_03_1300_okNAN.dat", contents, -8); var a = new MockTweeter(); StatusChecker sut = new StatusChecker(e, a); // Act var alerts = sut.CheckStatus(); // Assert Assert.Empty(alerts); }
static void Main(string[] args) { System.Console.WriteLine("---------------------------------------------------------------------------"); System.Console.WriteLine("---------------------- BEGIN SYNCHRONIZE APPLICATION ----------------------"); System.Console.WriteLine("---------------------------------------------------------------------------"); System.Console.WriteLine("\n\n"); StatusChecker statusChecker = new StatusChecker(); AutoResetEvent autoEvent = new AutoResetEvent(true); // Create an inferred delegate that invokes methods for the timer. TimerCallback tcb = statusChecker.CheckStatus; System.Threading.Timer stateTimer = new System.Threading.Timer(tcb, autoEvent, 1000, 0); autoEvent.WaitOne((int)(5 * 60000), true); stateTimer.Change(0, (int)(5 * 60000)); // (X) * 1 Minute System.Console.ReadKey(); }
public async Task <Response> Authorize() { var code = Request.Query["code"].ToString(); var state = Request.Query["state"].ToString(); var expectedState = Session[SessionKeys.CSRF] as string; if (state != expectedState) { throw new InvalidOperationException("SECURITY FAIL!"); } Session[SessionKeys.CSRF] = null; var token = await StatusChecker.OAuthAccessToken(code); Session[SessionKeys.OAuthToken] = token.AccessToken; return(Context.GetRedirect(Linker.BuildRelativeUri(Context, "AboutPage").ToString())); }
public void ShouldHandle_Exceptions() { // Arrange var fakeAPI = new FakeDiskAPI_ThrowsExceptions(); var directoryMock = new Mock <IDirectoryWrapper>(); directoryMock.Setup(dir => dir.Exists(It.IsAny <string>())).Returns(true); var checker = new StatusChecker(fakeAPI, directoryMock.Object); var opt = new StatusOptions(@"c:\temp", 50, 20); // Act var logs = checker.GetStatus(opt); // Assert Assert.AreEqual(1, logs.Count); var log = logs.First(); Assert.AreEqual($"ERROR - Something went wrong!", log.Message); Assert.AreEqual(MessageType.Critical, log.MessageType); }
public void ShouldReturn_ProperStatus(double warning, double critical, string message, MessageType messageType) { // Arrange var fakeAPI = new FakeDiskAPI(); var directoryMock = new Mock <IDirectoryWrapper>(); directoryMock.Setup(dir => dir.Exists(It.IsAny <string>())).Returns(true); var checker = new StatusChecker(fakeAPI, directoryMock.Object); var opt = new StatusOptions(@"c:\temp", warning, critical); // Act var logs = checker.GetStatus(opt); // Assert Assert.AreEqual(1, logs.Count); var log = logs.First(); Assert.AreEqual(message, log.Message); Assert.AreEqual(messageType, log.MessageType); }
public void ShouldHandle_InvalidPath() { // Arrange var fakeAPI = new FakeDiskAPI(); var directoryMock = new Mock <IDirectoryWrapper>(); directoryMock.Setup(dir => dir.Exists(It.IsAny <string>())).Returns(false); var checker = new StatusChecker(fakeAPI, directoryMock.Object); var opt = new StatusOptions(@"c:\temp", 50, 20); // Act var logs = checker.GetStatus(opt); // Assert Assert.AreEqual(1, logs.Count); var log = logs.First(); Assert.AreEqual($@"ERROR - Verify that you have the correct path: c:\temp", log.Message); Assert.AreEqual(MessageType.Critical, log.MessageType); }
public virtual async Task <SoapGetProductsResponse> GetProductsAsync() { try { var filters = new filters { filter = new associativeEntity[0] }; var store = string.IsNullOrWhiteSpace(this.Store) ? null : this.Store; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new catalogProductListResponse(); var privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; if (privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening) { privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl); } var sessionId = await this.GetSessionId().ConfigureAwait(false); using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) res = await privateClient.catalogProductListAsync(sessionId.SessionId, filters, store).ConfigureAwait(false); }).ConfigureAwait(false); return(new SoapGetProductsResponse(res)); } catch (Exception exc) { throw new MagentoSoapException(string.Format("An error occured during GetProductsAsync()"), exc); } }
public void Timer_Negative_Duetime_Test7() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes duetime to -2 (negative two) sec /// 5. Verifies ArgumentOutOfRangeException exception is thrown /// </summary> /// OutputHelper.WriteLine("Tests the Timer Change method for ArgumentOutOfRangeException"); AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); OutputHelper.WriteLine("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); OutputHelper.WriteLine("Creating timer: " + DateTime.UtcNow.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; OutputHelper.WriteLine("Waiting and verifying"); autoEvent.WaitOne(5000, false); statusChecker.m_result = false; OutputHelper.WriteLine("Changing period -ve"); OutputHelper.WriteLine("duetime is negative and is not equal to Infinite(or -1) should throw an exception"); Assert.Throws(typeof(ArgumentOutOfRangeException), () => { stateTimer.Change(-2, 500); OutputHelper.WriteLine("Waiting and verifying"); autoEvent.WaitOne(7500, false); }); OutputHelper.WriteLine("Destroying timer."); stateTimer.Dispose(); }
public Puntos() { InitializeComponent(); TxtVersion.Text = "Versión " + App.Configuration.Version; MobFoxAdControl.PublisherID = App.Configuration.MobFoxID; MobFoxAdControl.TestMode = App.Configuration.MobFoxInTestMode; RegionList.ItemsSource = App.Configuration.GetRegions().Select(x => x.Value); RegionList.SelectedIndex = App.Configuration.SelectedRegion.HasValue ? App.Configuration.SelectedRegion.Value : 0; MarketList.ItemsSource = App.Configuration.GetMarketsByRegions(RegionList.SelectedIndex).Select(x => x.Value); MarketList.SelectedIndex = App.Configuration.SelectedMarket.HasValue ? App.Configuration.SelectedMarket.Value : 0; if (!App.Configuration.SelectedMarket.HasValue || !App.Configuration.SelectedRegion.HasValue) { SetApplicationBarEnabled(false); OptionSelectionPanel.Visibility = Visibility.Visible; } else { if (!App.Configuration.IsRated && App.Configuration.OpenCount > 2) { if (MessageBox.Show("Queres calificar la aplicación?", "Ayudanos a mejorar", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { App.Configuration.IsRated = true; Config.Set(App.Configuration); ShowReviewTask(); } } } StatusChecker.Check("Home"); DataContext = ViewModel; Loaded += Page_Loaded; }
private void Rotation() { while (Main.isLaunched) { try { if (StatusChecker.BasicConditions() && !ObjectManager.Me.HaveBuff("Drink") && !ObjectManager.Me.HaveBuff("Food")) { ApplyEnchantWeapon(); _totemManager.CheckForTotemicCall(); } if (StatusChecker.OutOfCombat(RotationRole)) { specialization.BuffRotation(); } if (StatusChecker.InPull()) { specialization.Pull(); } if (StatusChecker.InCombat()) { specialization.CombatRotation(); } if (AIOParty.GroupAndRaid.Any(p => p.InCombatFlagOnly && p.GetDistance < 50)) { specialization.HealerCombat(); } } catch (Exception arg) { Logging.WriteError("ERROR: " + arg, true); } Thread.Sleep(ToolBox.GetLatency() + settings.ThreadSleepCycle); } Logger.Log("Stopped."); }
public void CheckStatus_HasBadValueAtSecondRowAndNAN_CreatesExpectedAlertString() { // Arrange var s = new FileStream(fileWithBadDataAtSecondRowAndNAN, FileMode.Open); string contents = convertStreamToString(s); var e = new TOA5Extractor( "CookEastEcTower_Flux_Raw_2017_11_03_1300_2linesBadCO2BadNAN.dat", contents, -8); var a = new MockTweeter(); StatusChecker sut = new StatusChecker(e, a); string expected = "[E] CookEastEcTower_Flux_Raw_2017_11_03_1300_2linesBadCO2BadNAN.dat: Null values > 3.\r\n[W] CookEastEcTower_Flux_Raw_2017_11_03_1300_2linesBadCO2BadNAN.dat: CO2_sig_strgth_Min < 0.8 (0.7)."; // Act var alerts = sut.CheckStatus(); // Assert Assert.Equal(2, alerts.Count); Assert.Equal( expected, string.Join("\r\n", alerts)); }
static void Main() { AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(); // Create the delegate that invokes methods for the timer. TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); // タイマー起動 Console.WriteLine("{0} タイマーを起動します.\n", DateTime.Now.ToString("h:mm:ss.fff")); Timer stateTimer = //最後の2つの値→初動実行までの時間,実行間隔(ミリ秒)b new Timer(timerDelegate, autoEvent, 0, 5000); // タイマーの待機時間は-1にすると無制限になる(有限にしたい場合はミリ秒で記述) autoEvent.WaitOne(60000, false); //タイマーの開放 stateTimer.Dispose(); }
private void Rotation() { while (Main.isLaunched) { try { if (StatusChecker.OutOfCombat(RotationRole)) { specialization.BuffRotation(); } if (StatusChecker.InPull()) { specialization.Pull(); } if (StatusChecker.InCombat()) { specialization.CombatRotation(); } if (StatusChecker.InCombatNoTarget()) { specialization.CombatNoTarget(); } if (AIOParty.GroupAndRaid.Any(p => p.InCombatFlagOnly)) { specialization.HealerCombat(); } } catch (Exception arg) { Logging.WriteError("ERROR: " + arg, true); } Thread.Sleep(ToolBox.GetLatency() + settings.ThreadSleepCycle); } Logger.Log("Stopped."); }
private async Task <salesOrderRepositoryV1GetListResponse1> GetOrdersPageByFilter(SalesOrderRepositoryV1GetListRequest filters, Mark mark) { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new salesOrderRepositoryV1GetListResponse1(); var privateClient = this._clientFactory.CreateMagentoSalesOrderRepositoryServiceClient(); await ActionPolicies.GetWithMarkAsync(mark).Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshMagentoSalesOrderRepositoryServiceClient(privateClient); using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) res = await privateClient.salesOrderRepositoryV1GetListAsync(filters).ConfigureAwait(false); }).ConfigureAwait(false); return(res); }
public MFTestResults Timer_Dispose_Test5() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Immediately Disposes the timer /// 4. Verifies that the Timer is disposed /// </summary> /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); statusChecker.c_flag = true; Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); Log.Comment("Immediately Destroying timer"); stateTimer.Dispose(); Log.Comment("Waiting and verifying for Timer disposed"); autoEvent.WaitOne(5000, false); if (statusChecker.counter != 0) { Log.Comment("Failure : expected timer destroyed immediately hence callback method" + " never invoked but is invoked '" + statusChecker.counter + "' times"); testResult = MFTestResults.Fail; } return(testResult); }
private void Rotation() { while (Main.isLaunched) { try { if (StatusChecker.BasicConditions() && _polymorphedEnemy != null && !ObjectManager.Me.InCombatFlagOnly) { _polymorphedEnemy = null; } if (StatusChecker.OutOfCombat(RotationRole)) { specialization.BuffRotation(); } if (StatusChecker.InPull()) { specialization.Pull(); } if (StatusChecker.InCombat() && !cast.IsBackingUp && !_isPolymorphing && (!ObjectManager.Target.HaveBuff("Polymorph") || ObjectManager.GetNumberAttackPlayer() < 1)) { specialization.CombatRotation(); } } catch (Exception arg) { Logging.WriteError("ERROR: " + arg, true); } Thread.Sleep(ToolBox.GetLatency() + settings.ThreadSleepCycle); } Logger.Log("Stopped."); }
private async Task <Negotiator> Status() { var settings = await SystemSettings.GetSettingsAsync(); var checker = new StatusChecker(SystemSettings); var status = await Cache.GetOrSetAsync(CacheKeys.LastestProductVersion, async() => await checker.GetStatus(), 30); var md = new Markdown(new MarkdownOptions { AutoNewLines = true, AutoHyperlink = true }); status.ReleaseNotes = md.Transform(status.ReleaseNotes); settings.Status = status; settings.BranchDropdown = new List <BranchDropdown> { new BranchDropdown { Name = EnumHelper <Branches> .GetBranchValue <BranchAttribute>(Branches.Stable).DisplayName, Value = Branches.Stable, Selected = settings.Branch == Branches.Stable }, new BranchDropdown { Name = EnumHelper <Branches> .GetBranchValue <BranchAttribute>(Branches.EarlyAccessPreview).DisplayName, Value = Branches.EarlyAccessPreview, Selected = settings.Branch == Branches.EarlyAccessPreview }, new BranchDropdown { Name = EnumHelper <Branches> .GetBranchValue <BranchAttribute>(Branches.Dev).DisplayName, Value = Branches.Dev, Selected = settings.Branch == Branches.Dev }, }; return(View["Status", settings]); }
public virtual async Task <GetMagentoInfoResponse> GetMagentoInfoAsync(bool suppressException) { try { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new magentoInfoResponse(); var privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl); await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; if (privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening) { privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl); } var sessionId = await this.GetSessionId().ConfigureAwait(false); using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) res = await privateClient.magentoInfoAsync(sessionId.SessionId).ConfigureAwait(false); }).ConfigureAwait(false); return(new GetMagentoInfoResponse(res)); } catch (Exception exc) { if (suppressException) { return(null); } throw new MagentoSoapException(string.Format("An error occured during GetMagentoInfoAsync()"), exc); } }
public MFTestResults Timer_TimerCallback_ZeroTest2() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Change duetime to zero sec /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback restarted immediately /// </summary> /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.z_flag = true; Log.Comment("Changing duetime to zero and Verifying the timer started Immediately."); DateTime t1 = DateTime.Now; stateTimer.Change(0, 500); Thread.Sleep(1); TimeSpan time = DateTime.Now - statusChecker.t2; Log.Comment("callback method called within " + time.ToString()); if (time.CompareTo(new TimeSpan(0, 0, 0, 0, 100)) > 0) { Log.Comment("The timer didn't start immediately, started after '" + time.ToString() + "'"); testResult = MFTestResults.Fail; } Log.Comment("Waiting and verifying"); autoEvent.WaitOne(7500, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } return testResult; }
private async void OnButton4_Click(object sender, RoutedEventArgs e) { MakeBtnRed(sender); var checker = new StatusChecker(); checker.StatusUpdated = false; //await checker.UpdateStatus().ConfigureAwait(false); // this one does not hang and sees the right value //Task www = checker.UpdateStatus(); // this one hangs forever Task.Run(delegate { return checker.UpdateStatus(); }); // this one hangs forever while (!checker.StatusUpdated || _isGetOut) ; MakeBtnGreen(sender); }
public MFTestResults Timer_Disable_Periodic_Signaling_Test3() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes period to zero (0) /// 5. Verifies periodic signaling is disabled /// 6. Changes period to Infinite /// 7. Verifies periodic signaling is disabled /// 8. Changes period to quarter sec /// 9. Disposes the timer after it signals /// 10. Verifies that the TimerCallback has been called /// </summary> /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.c_flag = true; Log.Comment("Changing period to zero (0) "); stateTimer.Change(0, 0); Log.Comment("Waiting and verifying the callback method is invoked once"); autoEvent.WaitOne(5000, false); if (statusChecker.counter != 1) { Log.Comment("Failure : expected callback '1' times but got '" + statusChecker.counter + "'"); testResult = MFTestResults.Fail; } Log.Comment("Reseting counter to zero"); statusChecker.counter = 0; Log.Comment("Changing period to Timeout.Infinite"); stateTimer.Change(0, Timeout.Infinite); Log.Comment("Waiting and verifying the callback method is invoked once"); autoEvent.WaitOne(5000, false); if (statusChecker.counter != 1) { Log.Comment("Failure : expected callback '1' times but got '" + statusChecker.counter + "'"); testResult = MFTestResults.Fail; } Log.Comment("Changing period to quarter sec "); stateTimer.Change(0, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } return testResult; }
public MFTestResults Timer_Dispose_Test5() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Immediately Disposes the timer /// 4. Verifies that the Timer is disposed /// </summary> /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); statusChecker.c_flag = true; Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); Log.Comment("Immediately Destroying timer"); stateTimer.Dispose(); Log.Comment("Waiting and verifying for Timer disposed"); autoEvent.WaitOne(5000, false); if (statusChecker.counter != 0) { Log.Comment("Failure : expected timer destroyed immediately hence callback method" + " never invoked but is invoked '" + statusChecker.counter + "' times"); testResult = MFTestResults.Fail; } return testResult; }
public MFTestResults Timer_TimerCallback_Duetime_Infinite_Test4() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it after infinite time /// 3. Verifies the callback method is never invoked /// </summary> /// Log.Comment("Tests the TimerCallback is never invoked if it's duetime is infinite "); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); statusChecker.c_flag = true; Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, Timeout.Infinite, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); if (statusChecker.counter != 0) { Log.Comment("Failure : expected callback method never invoked" + " but is invoked '" + statusChecker.counter + "' times"); testResult = MFTestResults.Fail; } return testResult; }
public MFTestResults Timer_Negative_Duetime_Test7() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes duetime to -2 (negative two) sec /// 5. Verifies ArgumentOutOfRangeException exception is thrown /// </summary> /// Log.Comment("Tests the Timer Change method for ArgumentOutOfRangeException"); MFTestResults testResult = MFTestResults.Fail; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); statusChecker.m_result = false; Log.Comment("Changing period -ve"); try { Log.Comment("duetime is negative and is not equal to Infinite(or -1) should throw an exception"); stateTimer.Change(-2, 500); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(7500, false); } catch (ArgumentOutOfRangeException e) { Log.Comment("Correctly threw exception on negative duetime name " + e.ToString()); testResult = MFTestResults.Pass; } finally { Log.Comment("Destroying timer."); stateTimer.Dispose(); } return testResult; }
public MFTestResults Timer_TimerCallback_Null_Test8() { /// <summary> /// 1. Creates a Timer with callback parameter null /// 2. Verifies ArgumentNullException exception is thrown /// </summary> /// Log.Comment("Tests the Timer for ArgumentNullException"); MFTestResults testResult = MFTestResults.Fail; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating timer: " + DateTime.Now.ToString()); try { Log.Comment("Passing callback parameter to a timer should throw exception"); Timer stateTimer = new Timer(null, autoEvent, 1000, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(7500, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); } catch (Exception e) { Log.Comment("Correctly threw exception on null callback parameter name " + e.ToString()); testResult = MFTestResults.Pass; } return testResult; }
public MFTestResults Timer_MaxInt_DueTime_Test9() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes duetime to MaxInt (in this case MaxInt assumed to be 4 sec) /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback starts after 4 sec /// </summary> /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.z_flag = true; Log.Comment("Changing duetime to 4 sec (Assumed MaxInt)"); DateTime t1 = DateTime.Now; stateTimer.Change(4000, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(8000, false); TimeSpan duration = statusChecker.t2 - t1; Log.Comment("Verifying callback method 1st invoked after 4000msec."); if (duration.CompareTo(new TimeSpan(4000)) <= 0) { Log.Comment("Failure : expected 1st callback happens more than" + " '4000msec.' but happened after '" + duration.ToString() + "'"); testResult = MFTestResults.Fail; } if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } Log.Comment("Destroying timer."); stateTimer.Dispose(); return testResult; }
public MFTestResults Timer_TimerCallback_Test1() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Change period to half sec /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback has been called /// </summary> /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; Log.Comment("Changing period to 500msec"); stateTimer.Change(0, 500); Log.Comment("Waiting for 7500msec and verifying"); autoEvent.WaitOne(7500, false); stateTimer.Dispose(); Log.Comment("Destroying timer."); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } return testResult; }
public MFTestResults Timer_MaxInt_Period_Test10() { /// <summary> /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes period to MaxInt (in this case MaxInt assumed to be 4 sec) /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback starts every 4 sec /// </summary> /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.m_flag = true; Log.Comment("Changing period to 4 sec (Assumed MaxInt)"); stateTimer.Change(0, 4000); Log.Comment("Waiting and verifying callback method is invoked every 4 sec"); autoEvent.WaitOne(60000, false); if (!statusChecker.m_result) { Log.Comment("Failure : after 60sec. expected callback invoked '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying time interval b/n callback invoke is atleast 4sec."); TimeSpan duration = statusChecker.t2 - statusChecker.t1; if(duration.CompareTo(new TimeSpan(4000)) < 0) { Log.Comment("Failure : expected interval b/n callbacks at least '4sec' but got '"+duration.Seconds.ToString()+"sec'"); testResult = MFTestResults.Fail; } Log.Comment("Destroying timer."); stateTimer.Dispose(); return testResult; }