Exemple #1
0
 private void OnMemoryCacheEntryRemoved(object sender, CacheEntryRemovedEventArgs e)
 {
     if (e.Reason >= CacheEntryRemovedReason.Expired)
     {
         Expired?.Invoke(sender, e);
     }
 }
        public void AsWarning()
        {
            var lots = new List <Lot>();

            var lot1 = new LotBuilder()
                       .Expired()
                       .AvailableOnStock()
                       .Build();

            var lot2 = new LotBuilder()
                       .NotExpired()
                       .AvailableOnStock()
                       .Build();

            lots.Add(lot1);
            lots.Add(lot2);

            string expectedWarningMessage = new Expired().GetErrorMessageWhenExpectingFalse(lot2);

            var result = Specification
                         .Create <Lot>(lots)
                         .ThatAreNot <Expired>().AsWarning()
                         .AndAre <AvailableOnStock>()
                         .GetResults();

            Assert.True(result.AreAllCandidatesValid);
            Assert.Equal(0, result.TotalOfErrors);
            Assert.Equal(1, result.TotalOfWarnings);
            Assert.False(result.HasError <Expired>());
            Assert.True(result.HasWarning <Expired>());
            Assert.True(result.HasWarning <Expired>(lot1));
            Assert.Equal(expectedWarningMessage, result.WarningMessages);
        }
Exemple #3
0
        public ExpiringCache(TimeSpan activeMonitoringInterval)
        {
            cache = new Hash <TKey, TValue>();
            expirationPolicies = new Hash <TKey, ExpirationPolicy <TValue> >();
            var newTimer = new Timer(activeMonitoringInterval.TotalMilliseconds);

            newTimer.Elapsed += (sender, e) =>
            {
                lock (locker)
                {
                    var expiredKeys = cache
                                      .Where(i => expirationPolicies.FlatMap(i.Key, v => v.ItemEvictable(i.Value), false))
                                      .Select(i => i.Key)
                                      .ToArray();
                    foreach (var key in expiredKeys)
                    {
                        var args = new ExpirationArgs <TKey, TValue>(key, cache[key]);
                        Expired?.Invoke(this, args);
                        if (!args.CancelEviction)
                        {
                            cache.Remove(key);
                            expirationPolicies.Remove(key);
                        }
                    }
                }
            };

            anyTimer  = newTimer.Some();
            locker    = new object();
            NewPolicy = () => new NonExpiration <TValue>();
        }
Exemple #4
0
 private void ExpireNow()
 {
     _timerEvent.Stop();
     if (_secondsToExpire > 0)
     {
         Expired?.Invoke(Key, Item);
     }
 }
Exemple #5
0
 public virtual void RunWhile(DoAndNoReturn @do, Condition condition, Expired expired)
 {
     while(condition())
     {
         @do();
         if (TimeUp) expired();
     }
 }
Exemple #6
0
 private void OnTick()
 {
     while (true)
     {
         Thread.Sleep(this.Interval);
         Expired?.Invoke(DateTime.Now);
     }
 }
        public void UpdateBanExpiration(int banID, Expired expired)
        {
            var query      = "UPDATE AccountBan SET Expired=@Value WHERE BannedId=@BannedId";
            var sqlCommand = factory.GetCommand(sqlConnection);

            sqlCommand.SetCommand(query);
            sqlCommand.AddParameter("@Value", (byte)expired);
            sqlCommand.AddParameter("@BannedId", banID);
            sqlCommand.Execute();
        }
 private void TimerExpired(object state)
 {
     lock (_lock)
     {
         if (_enabled)
         {
             Expired?.Invoke(this, EventArgs.Empty);
         }
     }
 }
Exemple #9
0
        /// <summary>
        /// Atualiza o vencimento do banimento.
        /// </summary>
        /// <param name="banID"></param>
        /// <param name="expired"></param>
        private void UpdateBanExpiration(long banId, Expired expired)
        {
            var query      = "UPDATE AccountBan SET Expired=@Value WHERE BanId=@BanId";
            var sqlCommand = factory.GetCommand(sqlConnection);

            sqlCommand.SetCommand(query);
            sqlCommand.AddParameter("@Value", (byte)expired);
            sqlCommand.AddParameter("@BanId", banId);
            sqlCommand.ExecuteNonQuery();
        }
Exemple #10
0
 public TimedEvent(Aircraft aircraft)
 {
     Aircraft        = aircraft;
     TimeStamp       = aircraft.TimeStamp;
     Timer           = new System.Timers.Timer();
     Timer.Elapsed  += (sender, args) => { Expired?.Invoke(this, System.EventArgs.Empty); };
     Timer.Interval  = 5000;  // 5 second intervals
     Timer.AutoReset = false; // Repeatable timer
     Timer.Enabled   = true;
 }
Exemple #11
0
        public DbEvents(RealmManager manager)
        {
            var db = manager.Database;

            // setup event for expiring keys
            db.Sub.Subscribe($"__keyevent@{db.DatabaseIndex}__:expired", (s, buff) =>
            {
                Expired?.Invoke(this, new DbEventArgs(Encoding.UTF8.GetString(buff)));
            });
        }
Exemple #12
0
 /// <summary>
 /// Perform certain task till specified condition is matched
 /// </summary>
 /// <param name="do">Delegate executed repeatedly at recheck interval of Clock. The return value is used as argument for "matched" delegate.</param>
 /// <param name="matched">The return value of the "do" delegate passed as argument to this delegate. Return value of true would cause the
 /// Clock to stop.</param>
 /// <param name="expired">In case of a no match this delegate is called</param>
 /// <returns></returns>
 public virtual object Perform(Do @do, Matched matched, Expired expired)
 {
     while (true)
     {
         object o = @do();
         if (matched(o)) return o;
         if (TimeUp) return expired();
         Thread.Sleep(recheckAfterInMilliSeconds);
     }
 }
Exemple #13
0
        /// <summary>
        /// Remove item from cache by key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="raiseEvents">Indicates whether events should be raised.</param>
        /// <param name="action">The action that need to be executed in synchronization with the item cache removal.</param>
        /// <returns>The value indicating whether the item was removed.</returns>
        private bool RemoveItem(TKey key, bool raiseEvents, Action action = null)
        {
            // Try to get item, if there is no item by that key then return true to indicate that item was removed.
            var item = default(CacheStorageValueInfo <TValue>);

            if (!_dictionary.TryGetValue(key, out item))
            {
                return(true);
            }

            action?.Invoke();

            var cancel           = false;
            var expirationPolicy = item.ExpirationPolicy;

            if (raiseEvents)
            {
                var expiringEventArgs = new ExpiringEventArgs <TKey, TValue>(key, item.Value, expirationPolicy);
                Expiring.SafeInvoke(this, expiringEventArgs);

                cancel           = expiringEventArgs.Cancel;
                expirationPolicy = expiringEventArgs.ExpirationPolicy;
            }

            if (cancel)
            {
                if (expirationPolicy == null && _defaultExpirationPolicyInitCode != null)
                {
                    expirationPolicy = _defaultExpirationPolicyInitCode.Invoke();
                }

                _dictionary[key] = new CacheStorageValueInfo <TValue>(item.Value, expirationPolicy);

                return(false);
            }

            _dictionary.Remove(key);

            bool dispose = _disposeValuesOnRemoval;

            if (raiseEvents)
            {
                var expiredEventArgs = new ExpiredEventArgs <TKey, TValue>(key, item.Value, dispose);
                Expired.SafeInvoke(this, expiredEventArgs);

                dispose = expiredEventArgs.Dispose;
            }

            if (dispose)
            {
                item.DisposeValue();
            }

            return(true);
        }
Exemple #14
0
        private void OnExpired()
        {
            if (_expired)
            {
                return;
            }

            _expired = true;

            Expired?.Invoke(this);
        }
        public void Start()
        {
            Task.Delay(Duration, _tokenSource.Token).ContinueWith(t =>
            {
                if (t.IsCanceled)
                {
                    return;
                }

                Expired?.Invoke(this);
            });
        }
Exemple #16
0
        private void OnDistributedCacheEntryExpired(object sender, CacheEntryExpiredEventArgs e)
        {
            if (e.Key.HasValue())
            {
                // When a cache entry expires in a distributed store,
                // remove the key from all memory stores.
                _stores.OfType <IMemoryCacheStore>().Each(x => x.Remove(e.Key));

                // Raise expired event
                Expired?.Invoke(sender, e);
            }
        }
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Elapsed == Limit)
            {
                Expired?.Invoke(this);
                if (Timer != null)
                {
                    Timer.Stop();
                    Timer.Dispose();
                    Timer = null;
                }
                return;
            }

            Elapsed++;
        }
Exemple #18
0
        private void CacheValidationCallback(object state)
        {
            _rwLock.EnterWriteLock();
            try {
                while (_queue.TryDequeue(out var keys))
                {
                    foreach (var key in keys)
                    {
                        if (!_contents.TryGetValue(key, out var content))
                        {
                            continue;
                        }

                        if (content.Validate())
                        {
                            var expiresAt = content.ExpiresAt;
                            if (expiresAt != DateTime.MaxValue)
                            {
                                _queue.Enqueue(content.ExpiresAt, key);
                            }

                            continue;
                        }

                        if (Expired != null)
                        {
                            var args = new ExpiredEventArgs <TKey, TValue>(content);
                            Expired.Invoke(this, args);
                            if (args.CancelEviction)
                            {
                                content.Refresh();
                                continue;
                            }
                        }
                        _contents.Remove(key);
                    }
                }
            }
            finally {
                _rwLock.ExitWriteLock();
            }

            if (_queue.TryPeekNextEntryAt(out var nextAt))
            {
                SetTimer(DateTime.MaxValue, nextAt);
            }
        }
        private void Run()
        {
            while (true)
            {
                Thread.Sleep(this.Interval);

                /* alte schreibweise
                 * if (Expired != null)
                 *   Expired(DateTime.Now);
                 */

                // neue schreibweise, Methode nach ? wird nur aufgerufen
                // falls Expired nicht null
                // 3.
                Expired?.Invoke(DateTime.Now);
            }
        }
Exemple #20
0
        public void ErrorMessageExpectingFalse()
        {
            var lot = new LotBuilder()
                      .Expired()
                      .Build();

            var result = Specification
                         .Create(lot)
                         .IsNot <Expired>()
                         .GetResult();

            string expectedMessage = new Expired().GetErrorMessageWhenExpectingFalse(lot);

            Assert.False(result.IsValid);
            Assert.Equal(expectedMessage, result.ErrorMessage);
            Assert.Equal(1, result.TotalOfErrors);
            Assert.True(result.HasError <Expired>());
        }
Exemple #21
0
        private void OnRedisKeyEvent(string channel, string message)
        {
            // INFO: "message" is the cache key

            var key = RedisUtility.GetEventFromChannel(channel);

            switch (key)
            {
            //case "expire":
            case "expired":
            case "evicted":
                Expired?.Invoke(this, new CacheEntryExpiredEventArgs {
                    Key = NormalizeKey(message)
                });
                RemoveDependingEntries(new string[] { message });
                //Debug.WriteLine("Expiration occurred for {0}".FormatInvariant(message));
                break;
            }
        }
        private void Tick()
        {
            DateTime now = DateTime.Now;

            TimeSpan elapsed   = now - startTime;
            TimeSpan remaining = endTime - now;

            //base.Text = String.Format("{0}: {1:hh\\:mm\\:ss}", Label, remaining);
            base.Text  = String.Format("{0}: {1:00}:{2:00}:{3:00}", Label, remaining.Hours, remaining.Minutes, remaining.Seconds);
            this.Value = Math.Min((int)elapsed.TotalSeconds, this.Maximum);

            tooltip.SetToolTip(this, String.Format("Expiring {0:T}", endTime));

            if (now >= endTime)
            {
                tooltip.SetToolTip(this, String.Format("Expired {0:T}", endTime));
                SystemSounds.Beep.Play();
                StartFlash();
                Expired.Invoke(this, new EventArgs());
            }
        }
Exemple #23
0
        public void AsWarning()
        {
            var lot = new LotBuilder()
                      .Expired()
                      .AvailableOnStock()
                      .Build();

            string expectedWarningMessage = new Expired().GetErrorMessageWhenExpectingFalse(lot);

            var result = Specification
                         .Create(lot)
                         .IsNot <Expired>().AsWarning()
                         .AndIs <AvailableOnStock>()
                         .GetResult();

            Assert.True(result.IsValid);
            Assert.Equal(0, result.TotalOfErrors);
            Assert.Equal(1, result.TotalOfWarnings);
            Assert.False(result.HasError <Expired>());
            Assert.True(result.HasWarning <Expired>());
            Assert.Equal(expectedWarningMessage, result.WarningMessage);
        }
Exemple #24
0
 public List <Expired> List()
 {
     try
     {
         List <Expired> MiLista = new List <Expired>();
         var            lista   = db.reserva.Join(db.detalle_reserva, r => r.res_id, dr => dr.fk_id_reserva, (r, dr) => new { r, dr }).OrderByDescending(x => x.r.fecha_salida).ToList();
         foreach (var item in lista)
         {
             Expired objE = new Expired();
             objE.res_id        = item.r.res_id;
             objE.fecha_ingreso = item.r.fecha_ingreso;
             objE.fecha_salida  = item.r.fecha_salida;
             objE.dni_clientes  = item.r.dni_clientes;
             objE.fk_num_habi   = item.dr.fk_num_habi;
             MiLista.Add(objE);
         }
         return(MiLista);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemple #25
0
        public Dictionary <string, string> GetByName()
        {
            var result = new Dictionary <string, string>
            {
                { "Id", Id },
                { "UserId", UserId.ToString() },
                { "UserName", UserName },
                { "Name", Name },
                { "Phone", Phone },
                { "Email", Email },
                { "Expired", Expired.ToString() },
                { "ActiveBranchId", ActiveBranchId.ToString() },
                { "ParentBranchId", ParentBranchId.ToString() },
                { "ActiveRoleName", ActiveRoleName },
                { "RoleNames", RoleNames },
                { "ActiveRoleId", ActiveRoleId.ToString() },
                { "RoleIds", RoleIds },
                { "PermittedBranchs", PermittedBranchs },
                { "UniqueName", UniqueName },
                { "BranchId", BranchId.ToString() },
            };

            return(result);
        }
Exemple #26
0
 private void Expire()
 {
     timer.Enabled = false;
     Expired?.Invoke(this, System.EventArgs.Empty);
 }
 public static bool IsExpired(Service service)
 {
     return(Expired.FirstOrDefault(s => s == service) != null);
 }
Exemple #28
0
 private void FireExpiredEvent(object sender, ElapsedEventArgs e)
 {
     Stop();
     Expired?.Invoke(this, e);
 }
 public void Expire()
 {
     Expired?.Invoke(this, System.EventArgs.Empty);
 }
 protected virtual void OnDisable()
 {
     Expired?.Invoke(this);
 }
Exemple #31
0
 public void EntryExpired(EntryEvent <TKey, TValue> entryEvent)
 {
     Expired?.Invoke(entryEvent);
 }
 public void OnExpire()
 {
     Expired?.Invoke(this, this);
 }