private SavedGameMetadataUpdate(Builder builder) {
     mDescriptionUpdated = builder.mDescriptionUpdated;
     mNewDescription = builder.mNewDescription;
     mCoverImageUpdated = builder.mCoverImageUpdated;
     mNewPngCoverImage = builder.mNewPngCoverImage;
     mNewPlayedTime = builder.mNewPlayedTime;
 }
        public RedisServerEvents(IRedisPubSubServer redisPubSub)
        {
            this.RedisPubSub = redisPubSub;
            this.clientsManager = redisPubSub.ClientsManager;
            redisPubSub.OnInit = OnInit;
            redisPubSub.OnError = ex => Log.Error("Exception in RedisServerEvents: " + ex.Message, ex);
            redisPubSub.OnMessage = HandleMessage;

            WaitBeforeNextRestart = TimeSpan.FromMilliseconds(2000);

            local = new MemoryServerEvents
            {
                NotifyJoin = HandleOnJoin,
                NotifyLeave = HandleOnLeave,
                NotifyHeartbeat = HandleOnHeartbeat,
                Serialize = HandleSerialize,
            };

            var appHost = HostContext.AppHost;
            var feature = appHost != null ? appHost.GetPlugin<ServerEventsFeature>() : null;
            if (feature != null)
            {
                Timeout = feature.IdleTimeout;
                HouseKeepingInterval = feature.HouseKeepingInterval;
                OnSubscribe = feature.OnSubscribe;
                OnUnsubscribe = feature.OnUnsubscribe;
                NotifyChannelOfSubscriptions = feature.NotifyChannelOfSubscriptions;
            }
        }
        private RetryConditionHeaderValue(RetryConditionHeaderValue source)
        {
            Contract.Requires(source != null);

            _delta = source._delta;
            _date = source._date;
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            // Backward compatibility with definitions of events that have MyObjectBuilder_GlobalEventDefinition as the TypeId 
            if (builder.Id.TypeId == typeof(MyObjectBuilder_GlobalEventDefinition))
            {
                builder.Id = new VRage.ObjectBuilders.SerializableDefinitionId(typeof(MyObjectBuilder_GlobalEventBase), builder.Id.SubtypeName);
            }

            base.Init(builder);

            var eventBuilder = builder as MyObjectBuilder_GlobalEventDefinition;

            // This ensures that either both min and max activation time are specified or neither of them is
            if (eventBuilder.MinActivationTimeMs.HasValue && !eventBuilder.MaxActivationTimeMs.HasValue)
            {
                eventBuilder.MaxActivationTimeMs = eventBuilder.MinActivationTimeMs;
            }
            if (eventBuilder.MaxActivationTimeMs.HasValue && !eventBuilder.MinActivationTimeMs.HasValue)
            {
                eventBuilder.MinActivationTimeMs = eventBuilder.MaxActivationTimeMs;
            }

            Debug.Assert(eventBuilder.FirstActivationTimeMs.HasValue || eventBuilder.MinActivationTimeMs.HasValue, "Global event definition has to have either the FirstActivationTime or [Min/Max]ActivationTime specified");

            if (eventBuilder.MinActivationTimeMs.HasValue)
                MinActivationTime = TimeSpan.FromTicks(eventBuilder.MinActivationTimeMs.Value * TimeSpan.TicksPerMillisecond);
            if (eventBuilder.MaxActivationTimeMs.HasValue)
                MaxActivationTime = TimeSpan.FromTicks(eventBuilder.MaxActivationTimeMs.Value * TimeSpan.TicksPerMillisecond);
            if (eventBuilder.FirstActivationTimeMs.HasValue)
                FirstActivationTime = TimeSpan.FromTicks(eventBuilder.FirstActivationTimeMs.Value * TimeSpan.TicksPerMillisecond);
        }
Example #5
0
 private VideoFile(SerializationInfo info, DeserializeInfo di)
     : this(di.Server, di.Info, di.Type)
 {
     actors = info.GetValue("a", typeof(string[])) as string[];
       description = info.GetString("de");
       director = info.GetString("di");
       genre = info.GetString("g");
       title = info.GetString("t");
       try {
     width = info.GetInt32("w");
     height = info.GetInt32("h");
       }
       catch (Exception) {
       }
       var ts = info.GetInt64("du");
       if (ts > 0) {
     duration = new TimeSpan(ts);
       }
       try {
     bookmark = info.GetInt64("b");
       }
       catch (Exception) {
     bookmark = 0;
       }
       try {
     subTitle = info.GetValue("st", typeof(Subtitle)) as Subtitle;
       }
       catch (Exception) {
     subTitle = null;
       }
       initialized = true;
 }
		public RedisLock(
			ICollection<ConnectionMultiplexer> redisCaches,
			string resource,
			TimeSpan expiryTime,
			TimeSpan? waitTime = null,
			TimeSpan? retryTime = null,
			Func<string, string> redisKeyFormatter = null,
			IRedLockLogger logger = null)
		{
			this.redisCaches = redisCaches;
			var formatter = redisKeyFormatter ?? DefaultRedisKeyFormatter;
			this.logger = logger ?? new NullLogger();

			quorum = redisCaches.Count() / 2 + 1;
			quorumRetryCount = 3;
			quorumRetryDelayMs = 400;
			clockDriftFactor = 0.01;
			redisKey = formatter(resource);

			Resource = resource;
			LockId = Guid.NewGuid().ToString();
			this.expiryTime = expiryTime;
			this.waitTime = waitTime;
			this.retryTime = retryTime;

			Start();
		}
Example #7
0
        /// <summary>
        /// Initializes the NMEA Geographic position, Latitude and Longitude and parses an NMEA sentence
        /// </summary>
        /// <param name="NMEAsentence"></param>
        public GPGLL(string NMEAsentence)
        {
            try
            {
                //Split into an array of strings.
                string[] split = NMEAsentence.Split(new Char[] { ',' });

                try
                {
                    _position = new Coordinate(GPSHandler.GPSToDecimalDegrees(split[3], split[4]),
                                                GPSHandler.GPSToDecimalDegrees(split[1], split[2]));
                }
                catch { _position = null; }

                try
                {
                    _timeOfSolution = new TimeSpan(int.Parse(split[5].Substring(0, 2)),
                                                    int.Parse(split[5].Substring(2, 2)),
                                                    int.Parse(split[5].Substring(4)));
                }
                catch
                {
                    _timeOfSolution = null; // TimeSpan.Zero;
                }
                _dataValid = (split[6] == "A");
            }
            catch { }
        }
        public QueueStats(string name,
                          string groupName,
                          int length,
                          int avgItemsPerSecond,
                          double avgProcessingTime,
                          double idleTimePercent,
                          TimeSpan? currentItemProcessingTime,
                          TimeSpan? currentIdleTime,
                          long totalItemsProcessed, 
                          long lengthCurrentTryPeak, 
                          long lengthLifetimePeak,
                          Type lastProcessedMessageType,
                          Type inProgressMessageType)
        {
            Name = name;
            GroupName = groupName;
            Length = length;
            AvgItemsPerSecond = avgItemsPerSecond;
            AvgProcessingTime = avgProcessingTime;
            IdleTimePercent = idleTimePercent;
            CurrentItemProcessingTime = currentItemProcessingTime;
            CurrentIdleTime = currentIdleTime;
            TotalItemsProcessed = totalItemsProcessed;
            LengthCurrentTryPeak = lengthCurrentTryPeak;

            LengthLifetimePeak = lengthLifetimePeak;
            LengthLifetimePeakFriendly = lengthLifetimePeak.ToFriendlyNumberString();

            LastProcessedMessageType = lastProcessedMessageType;
            InProgressMessageType = inProgressMessageType;
        }
        public InMemoryCache(string region, TimeSpan? timeToLive, TimeSpan? timeToIdle)
        {
            if (string.IsNullOrEmpty(region))
            {
                throw new ArgumentNullException(nameof(region));
            }

            if (timeToLive.HasValue && timeToLive.Value.TotalMilliseconds <= 0)
            {
                throw new ArgumentException("TTL duration must be greater than zero.", nameof(timeToLive));
            }

            if (timeToIdle.HasValue && timeToIdle.Value.TotalMilliseconds <= 0)
            {
                throw new ArgumentException("TTI duration must be greater than zero.", nameof(timeToIdle));
            }

            this.cacheManager = new InMemoryCacheManager();
            this.region = region;
            this.timeToLive = timeToLive;
            this.timeToIdle = timeToIdle;

            this.accessCount = 0;
            this.hitCount = 0;
            this.missCount = 0;
        }
Example #10
0
 public TimeTracker()
 {
     _timeline = new ParallelTimeline(null, Duration.Forever);
     _timeClock = _timeline.CreateClock();
     _timeClock.Controller.Begin();
     _lastTime = TimeSpan.FromSeconds(0);
 } 
Example #11
0
        /// <summary>
        /// Generates stats based on the difference of the order executions from the reference price and time
        /// </summary>
        /// <param name="benchmarkPrice"></param>
        /// <param name="referenceTime">Null to use QDMS-provided time, the reference time otherwise.</param>
        public void GenerateExecutionStats(ExecutionBenchmark benchmarkPrice, TimeSpan? referenceTime)
        {
            if(Orders == null || Orders.Count == 0)
            {
                throw new Exception("No orders selected.");
            }

            _referenceTime = referenceTime;
            Stats = new List<ExecutionStats>();

            if (referenceTime == null && benchmarkPrice != ExecutionBenchmark.Reference)
            {
                _instrumentSessions = GetSessionTimes(Orders.Select(x => x.Instrument).Distinct());
            }

            //if it's at the open we have to grab external data
            if(benchmarkPrice == ExecutionBenchmark.Open)
            {
                //make sure we're connected to external data source
                if(_datasourcer.ExternalDataSource == null || !_datasourcer.ExternalDataSource.Connected)
                {
                    throw new Exception("Must be connected to external data source.");
                }

                //grab the data
                RequestRequiredData();
            }

            //generate the stats
            Benchmark(Orders, benchmarkPrice);
        }
        public override void ValidateArguments()
        {
            base.ValidateArguments();

            NumberOfEntries = NumberOfEntries ?? 10;
            PollingPeriod = PollingPeriod ?? TimeSpan.FromSeconds(5);
        }
Example #13
0
        internal StatusUpdate(string name)
        {
            jobName = name;

            estimatedTime = null;
            hasError = false;
            isComplete = false;
            wasAborted = false;
            error = null;
            log = null;
            audioPosition = null;
            cliplength = null;
            audioFileSize = null;
            nbFramesDone = null;
            nbFramesTotal = null;
            projectedFileSize = null;
            timeElapsed = TimeSpan.Zero;
            processingspeed = null;
            filesize = null;

            for (int i = 0; i < UpdatesPerEstimate; ++i)
            {
                previousUpdates[i] = TimeSpan.Zero;
                previousUpdatesProgress[i] = 0M;
            }
        }
Example #14
0
 public RedisEntityTagStore(ConnectionMultiplexer connection, 
     int databaseId = 0,
     TimeSpan? expiry = null)
 {
     _expiry = expiry;
     Init(connection, databaseId);
 }
Example #15
0
		internal void AttemptSucceeded(PingReply result)
		{
			Succeeded++;
			LastSucceededTime = DateTime.Now;
			LastRoundTripTime = result.RoundTripTime;
			LastSucceeded = true;
		}
Example #16
0
 internal override void ProcessXmlCore (XmlReader reader)
 {
     switch (reader.Name) {
     case "duration":
         duration = TimeSpan.FromMilliseconds (reader.ReadElementContentAsDouble ());
         break;
     case "release-list":
         if (reader.ReadToDescendant ("release")) {
             List<Release> releases = new List<Release> ();
             do releases.Add (new Release (reader.ReadSubtree ()));
             while (reader.ReadToNextSibling ("release"));
             this.releases = releases.AsReadOnly ();
         }
         break;
     case "puid-list":
         if (reader.ReadToDescendant ("puid")) {
             List<string> puids = new List<string> ();
             do puids.Add (reader["id"]);
             while (reader.ReadToNextSibling ("puid"));
             this.puids = puids.AsReadOnly ();
         }
         break;
     default:
         base.ProcessXmlCore (reader);
         break;
     }
 }
Example #17
0
 public RedisEntityTagStore(string connectionString, 
     int databaseId = 0,
     TimeSpan? expiry = null)
 {
     _expiry = expiry;
     Init(ConnectionMultiplexer.Connect(connectionString), databaseId);
 }
Example #18
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string url;
            if (NavigationContext.QueryString.TryGetValue("url", out url))
            {
                mediaPlayer.Source = new Uri(url);
            }
            else
            {
                var filename = NavigationContext.QueryString["filename"];
                stateFile = DownloadInfo.GetStateFile(filename);
                mediaPlayer.SetSource(IsolatedStorage.OpenFileToRead(filename));
            }

            // only restore position for downloaded videos
            if (stateFile != null)
            {
                if (!position.HasValue && IsolatedStorage.FileExists(stateFile))
                {
                    position = TimeSpan.FromTicks(long.Parse(IsolatedStorage.ReadAllText(stateFile), CultureInfo.InvariantCulture));
                }
                if (position.HasValue)
                {
                    mediaPlayer.RestoreMediaState(new MediaState
                    {
                        IsPlaying = true,
                        IsStarted = true,
                        Position = position.Value,
                    });
                }
            }
        }
 public ProtoCommandLineTask(string command, bool raw = false, TimeSpan? timeout = null, bool errorOnTimeout = false)
 {
     _command = ReplaceTokens(command);
     _raw = raw;
     _timeout = timeout;
     _errorOnTimeout = errorOnTimeout;
 }
 static TradingConsoleServer()
 {
     try
     {
         string connectionString = SettingManager.Default.ConnectionString;
         using (var connection = new SqlConnection(connectionString))
         {
             SqlCommand sqlCommand = connection.CreateCommand();
             sqlCommand.CommandType = CommandType.Text;
             sqlCommand.CommandText = "SELECT [AllowInstantPayment], [MaxPriceDelayForSpotOrder] FROM [SystemParameter]";
             connection.Open();
             SqlDataReader reader = sqlCommand.ExecuteReader();
             reader.Read();
             AllowInstantPayment = (bool)reader["AllowInstantPayment"];
             object value = reader["MaxPriceDelayForSpotOrder"];
             if (value == DBNull.Value)
             {
                 MaxPriceDelayForSpotOrder = null;
             }
             else
             {
                 MaxPriceDelayForSpotOrder = TimeSpan.FromSeconds((int)value);
             }
             reader.Close();
         }
     }
     catch (Exception exception)
     {
         AllowInstantPayment = false;
         _Logger.Error(exception);
     }
 }
Example #21
0
 public DOTimeInOut(long ID, long nvID, DateTime NgayLamViec, TimeSpan? GioBatDau, TimeSpan? GioKetThuc, TimeSpan? ThoiGianLamViec,
     string IsChamCong, string NghiBuoiSang, string NghiBuoiChieu,string NghiPhepNam,string NghiKhongLuong, string NoiDung,
     long NGUOI_GHI_NHAN, DateTime? TG_GHI_NHAN, int Loai,string DUYET,long NGUOI_DUYET,DateTime NGAY_DUYET,
     string IP_ADDRESS,int LoaiDiTreVeSom,string ThoiGianSang,string ThoiGianChieu,string LoaiXacNhan,string TaiDonVi,string CongViec,string LyDo)
 {
     this._ID = ID;
     this.NVID = nvID;
     this.NgayLamViec = NgayLamViec;
     this.GioBatDau = GioBatDau;
     this.GioKetThuc = GioKetThuc;
     this.ThoiGianLamViec = ThoiGianLamViec;
     this.IsChamCong = IsChamCong;
     this._NghiBuoiSang = NghiBuoiSang;
     this._NghiBuoiChieu = NghiBuoiChieu;
     this._NghiPhepNam = NghiPhepNam;
     this._NghiKhongLuong = NghiKhongLuong;
     this._NoiDung = NoiDung;
     this._NGUOI_GHI_NHAN = NGUOI_GHI_NHAN;
     this._THOI_GIAN_GHI_NHAN = TG_GHI_NHAN;
     this._Loai = Loai;
     this._DUYET = DUYET;
     this._NGUOI_DUYET = NGUOI_DUYET;
     this._NGAY_DUYET = NGAY_DUYET;
     this._IP_ADDRESS = IP_ADDRESS;
     this._LoaiDiTreVeSom = LoaiDiTreVeSom;
     this._ThoiGianSang = ThoiGianSang;
     this._ThoiGianChieu = ThoiGianChieu;
     this._LoaiXacNhan = LoaiXacNhan;
     this._TaiDonVi = TaiDonVi;
     this._CongViec = CongViec;
     this._LyDo = LyDo;
 }
        public InvocationThrottle(TimeSpan min, TimeSpan max)
        {
            this.TimeSpanMin = min;
            this.TimeSpanMax = max;

            InitializeTimer();
        }
Example #23
0
 public void Update( GameTime time )
 {
     if( spawntime == null )
         spawntime = time.TotalGameTime;
     if( spawntime + new TimeSpan( 0, 0, 5 ) < time.TotalGameTime )
         Done = true;
 }
 public TimeSpan GetDelta()
 {
     var elapsed = this.Elapsed;
     var delta = elapsed - _lastSplit.GetValueOrDefault();
     _lastSplit = elapsed;
     return delta;
 }
        public bool IntervalElapsed(TimeSpan totalTime)
        {
            if (totalTime < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("totalTime");
            }

            if (!_started)
            {
                return false;
            }
            if (_totalTime == null)
            {
                _totalTime = totalTime;
                return true;
            }

            TimeSpan interval = !_initialUpdateProcessed ? _initialInterval : _repeatingInterval;
            bool intervalElapsed = totalTime - _totalTime >= interval;

            if (intervalElapsed)
            {
                _initialUpdateProcessed = true;
                _totalTime = totalTime;
                return true;
            }

            return false;
        }
 protected override Exception ProcessSqlResult(SqlDataReader reader)
 {
     Exception nextResultSet = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);
     if (nextResultSet == null)
     {
         bool flag = !reader.IsDBNull(1);
         TimeSpan? taskIntervalOverride = null;
         bool flag2 = false;
         if (flag)
         {
             DateTime dateTime = reader.GetDateTime(1);
             DateTime time2 = reader.GetDateTime(2);
             if (dateTime <= time2)
             {
                 flag2 = true;
             }
             else
             {
                 taskIntervalOverride = new TimeSpan?(dateTime.Subtract(time2));
             }
         }
         if (flag2)
         {
             base.Store.UpdateEventStatus(true, InstancePersistenceEvent<HasRunnableWorkflowEvent>.Value);
             return nextResultSet;
         }
         base.Store.UpdateEventStatus(false, InstancePersistenceEvent<HasRunnableWorkflowEvent>.Value);
         base.StoreLock.InstanceDetectionTask.ResetTimer(false, taskIntervalOverride);
     }
     return nextResultSet;
 }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var eventBuilder = builder as MyObjectBuilder_GlobalEventDefinition;

            // This ensures that either both min and max activation time are specified or neither of them is
            if (eventBuilder.MinActivationTimeMs.HasValue && !eventBuilder.MaxActivationTimeMs.HasValue)
            {
                eventBuilder.MaxActivationTimeMs = eventBuilder.MinActivationTimeMs;
            }
            if (eventBuilder.MaxActivationTimeMs.HasValue && !eventBuilder.MinActivationTimeMs.HasValue)
            {
                eventBuilder.MinActivationTimeMs = eventBuilder.MaxActivationTimeMs;
            }

            Debug.Assert(FirstActivationTime.HasValue || eventBuilder.MinActivationTimeMs.HasValue, "Global event definition has to have either the FirstActivationTime or [Min/Max]ActivationTime specified");

            if (eventBuilder.MinActivationTimeMs.HasValue)
                MinActivationTime = TimeSpan.FromTicks(eventBuilder.MinActivationTimeMs.Value * TimeSpan.TicksPerMillisecond);
            if (eventBuilder.MaxActivationTimeMs.HasValue)
                MaxActivationTime = TimeSpan.FromTicks(eventBuilder.MaxActivationTimeMs.Value * TimeSpan.TicksPerMillisecond);
            if (eventBuilder.FirstActivationTimeMs.HasValue)
                FirstActivationTime = TimeSpan.FromTicks(eventBuilder.FirstActivationTimeMs.Value * TimeSpan.TicksPerMillisecond);
        }
Example #28
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_timeout"></param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public WebClientEx(TimeSpan _timeout)
        {
            if (_timeout != WebClientExtensionMethods._infiniteTimeout && _timeout <= TimeSpan.Zero)
                throw new ArgumentOutOfRangeException("_timeout", _timeout, "The specified timeout must be greater than zero or infinite.");

            Timeout = _timeout;
        }
Example #29
0
 public LogRecord(String message, RecordClass recordClass, TimeSpan? runningTime, DateTime timeStamp)
 {
     this.message = message;
       this.recordClass = recordClass;
       this.runningTime = runningTime;
       this.timeStamp = timeStamp;
 }
Example #30
0
 protected override void activateAbility()
 {
     duration = new TimeSpan(0, 0, durationInSeconds);
         timeSinceUsed = TimeSpan.Zero;
         hawk.Shown = true;
         hawk.body.ApplyForce(new Vector2(50,0));
 }
 public bool KeyExpire(RedisKey key, TimeSpan?expiry, CommandFlags flags = CommandFlags.None)
 {
     return(Inner.KeyExpire(ToInner(key), expiry, flags));
 }
Example #32
0
        public static async Task CopyToAsync(this Stream source, Stream destination,
                                             Action <Stream, Stream, Exception> completed, Action <uint> progress,
                                             uint bufferSize, uint?maximumDownloadSize, TimeSpan?timeout)
        {
            byte[] buffer = new byte[bufferSize];

            Action <Exception> done = exception =>
            {
                if (completed != null)
                {
                    completed(source, destination, exception);
                }
            };

            int maxDownloadSize = maximumDownloadSize.HasValue
                ? (int)maximumDownloadSize.Value
                : int.MaxValue;
            int bytesDownloaded = 0;

            try
            {
repeat:
                int bytesRead = await source.ReadAsync(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min()).WithTimeout(timeout);

                int bytesToWrite = new[] { maxDownloadSize - bytesDownloaded, buffer.Length, bytesRead }.Min();
                destination.Write(buffer, 0, bytesToWrite);
                bytesDownloaded += bytesToWrite;
                if (!progress.IsNull() && bytesToWrite > 0)
                {
                    progress((uint)bytesDownloaded);
                }

                if (bytesToWrite == bytesRead && bytesToWrite > 0)
                {
                    goto repeat;
                }
                else
                {
                    done(null);
                }
            }
            catch (Exception e)
            {
                done(e);
            }
            IAsyncResult asyncResult            = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null);
            Action <IAsyncResult, bool> endRead = null;

            endRead = (innerAsyncResult, innerIsTimedOut) =>
            {
                try
                {
                    int bytesRead = source.EndRead(innerAsyncResult);
                    if (innerIsTimedOut)
                    {
                        done(new TimeoutException());
                    }

                    int bytesToWrite = new[] { maxDownloadSize - bytesDownloaded, buffer.Length, bytesRead }.Min();
                    destination.Write(buffer, 0, bytesToWrite);
                    bytesDownloaded += bytesToWrite;

                    if (!progress.IsNull() && bytesToWrite > 0)
                    {
                        progress((uint)bytesDownloaded);
                    }

                    if (bytesToWrite == bytesRead && bytesToWrite > 0)
                    {
                        asyncResult = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null);
                        // ReSharper disable PossibleNullReferenceException
                        // ReSharper disable AccessToModifiedClosure
                        asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout);
                        // ReSharper restore AccessToModifiedClosure
                        // ReSharper restore PossibleNullReferenceException
                    }
                    else
                    {
                        done(null);
                    }
                }
                catch (Exception exc)
                {
                    done(exc);
                }
            };

            asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout);
        }
Example #33
0
        public Object <T> Get(TimeSpan?timeout = null)
        {
            var obj = getFree(true);

            if (obj == null)
            {
                var queueItem = new GetSyncQueueInfo();

                _getSyncQueue.Enqueue(queueItem);
                _getQueue.Enqueue(false);

                if (timeout == null)
                {
                    timeout = Policy.SyncGetTimeout;
                }

                try
                {
                    if (queueItem.Wait.Wait(timeout.Value))
                    {
                        obj = queueItem.ReturnValue;
                    }
                }
                catch { }

                if (obj == null)
                {
                    obj = queueItem.ReturnValue;
                }
                if (obj == null)
                {
                    lock (queueItem.Lock) queueItem.IsTimeout = (obj = queueItem.ReturnValue) == null;
                }
                if (obj == null)
                {
                    obj = queueItem.ReturnValue;
                }

                if (obj == null)
                {
                    Policy.OnGetTimeout();

                    if (Policy.IsThrowGetTimeoutException)
                    {
                        throw new TimeoutException($"SafeObjectPool.Get 获取超时({timeout.Value.TotalSeconds}秒)。");
                    }

                    return(null);
                }
            }

            try
            {
                Policy.OnGet(obj);
            }
            catch
            {
                Return(obj);
                throw;
            }

            obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId;
            obj.LastGetTime     = DateTime.Now;
            Interlocked.Increment(ref obj._getTimes);

            return(obj);
        }
Example #34
0
 /// <summary>
 /// Returns the request timeout value if its value is set,
 /// else returns client timeout value.
 /// </summary>
 internal static TimeSpan?GetTimeoutValue(TimeSpan?clientTimeout, TimeSpan?requestTimeout)
 {
     return(requestTimeout.HasValue ? requestTimeout
         : (clientTimeout.HasValue ? clientTimeout : null));
 }
Example #35
0
        public static void WaitForIndexing(IDocumentStore store, string dbName = null, TimeSpan?timeout = null, bool allowErrors = false)
        {
            var admin = store.Maintenance.ForDatabase(dbName);

            timeout = timeout ?? (Debugger.IsAttached
                          ? TimeSpan.FromMinutes(15)
                          : TimeSpan.FromMinutes(1));

            var sp = Stopwatch.StartNew();

            while (sp.Elapsed < timeout.Value)
            {
                var databaseStatistics = admin.Send(new GetStatisticsOperation());
                var indexes            = databaseStatistics.Indexes
                                         .Where(x => x.State != IndexState.Disabled);

                if (indexes.All(x => x.IsStale == false && x.Name.StartsWith("ReplacementOf/") == false))
                {
                    return;
                }

                if (databaseStatistics.Indexes.Any(x => x.State == IndexState.Error))
                {
                    break;
                }
                Thread.Sleep(32);
            }

            if (allowErrors)
            {
                return;
            }

            var perf   = admin.Send(new GetIndexPerformanceStatisticsOperation());
            var errors = admin.Send(new GetIndexErrorsOperation());
            var stats  = admin.Send(new GetIndexesStatisticsOperation());

            var total = new
            {
                Errors      = errors,
                Stats       = stats,
                Performance = perf
            };

            var file = Path.GetTempFileName() + ".json";

            using (var stream = File.Open(file, FileMode.OpenOrCreate))
                using (var context = JsonOperationContext.ShortTermSingleUse())
                    using (var writer = new BlittableJsonTextWriter(context, stream))
                    {
                        var djv  = (DynamicJsonValue)TypeConverter.ToBlittableSupportedType(total);
                        var json = context.ReadObject(djv, "errors");
                        writer.WriteObject(json);
                        writer.Flush();
                    }

            var statistics = admin.Send(new GetStatisticsOperation());

            var corrupted = statistics.Indexes.Where(x => x.State == IndexState.Error).ToList();

            if (corrupted.Count > 0)
            {
                throw new InvalidOperationException(
                          $"The following indexes are with error state: {string.Join(",", corrupted.Select(x => x.Name))} - details at " + file);
            }

            throw new TimeoutException("The indexes stayed stale for more than " + timeout.Value + ", stats at " + file);
        }
 public bool StringSet(RedisKey key, RedisValue value, TimeSpan?expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
 {
     return(Inner.StringSet(ToInner(key), value, expiry, when, flags));
 }
 public void KeyRestore(RedisKey key, byte[] value, TimeSpan?expiry = null, CommandFlags flags = CommandFlags.None)
 {
     Inner.KeyRestore(ToInner(key), value, expiry, flags);
 }
Example #38
0
 /// <summary>
 /// 保存单个key value
 /// </summary>
 /// <param name="key">Redis Key</param>
 /// <param name="value">保存的值</param>
 /// <param name="expiry">过期时间</param>
 /// <returns></returns>
 public bool StringSet(string key, string value, TimeSpan?expiry = default(TimeSpan?))
 {
     key = AddSysCustomKey(key);
     return(Do(db => db.StringSet(key, value, expiry)));
 }
Example #39
0
 public TriggerEventArgs(bool[] playersReady, TimeSpan?timeLeft = null)
 {
     PlayersReady = playersReady.ToArray();
     TimeLeft     = timeLeft?.ToString("mm\\:ss") ?? "-";
 }
Example #40
0
 /// <summary>
 /// 设置Key的时间
 /// </summary>
 /// <param name="key">redis key</param>
 /// <param name="expiry"></param>
 /// <returns></returns>
 public bool KeyExpire(string key, TimeSpan?expiry = default(TimeSpan?))
 {
     key = AddSysCustomKey(key);
     return(Do(db => db.KeyExpire(key, expiry)));
 }
        public async Task <MessageContext> WaitForMessageAsync(Func <DiscordMessage, bool> predicate, TimeSpan?timeoutoverride = null)
        {
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            TimeSpan timeout = Config.Timeout;

            if (timeoutoverride != null)
            {
                timeout = (TimeSpan)timeoutoverride;
            }

            var tsc = new TaskCompletionSource <MessageContext>();
            var ct  = new CancellationTokenSource(timeout);

            ct.Token.Register(() => tsc.TrySetResult(null));

            try
            {
                this.Client.MessageCreated += Handler;
                var result = await tsc.Task.ConfigureAwait(false);

                return(result);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Client.MessageCreated -= Handler;
            }

            #region Handler
            async Task Handler(MessageCreateEventArgs e)
            {
                await Task.Yield();

                if (predicate(e.Message))
                {
                    var mc = new MessageContext()
                    {
                        Interactivity = this,
                        Message       = e.Message
                    };
                    tsc.TrySetResult(mc);
                    return;
                }
            }

            #endregion
        }
Example #42
0
 /// <summary>
 /// 保存单个key value
 /// </summary>
 /// <param name="key">Redis Key</param>
 /// <param name="value">保存的值</param>
 /// <param name="expiry">过期时间</param>
 /// <returns></returns>
 public async Task <bool> StringSetAsync(string key, string value, TimeSpan?expiry = default(TimeSpan?))
 {
     key = AddSysCustomKey(key);
     return(await Do(db => db.StringSetAsync(key, value, expiry)));
 }
        public async Task <TypingContext> WaitForTypingChannelAsync(DiscordUser user, TimeSpan?timeoutoverride = null)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            TimeSpan timeout = Config.Timeout;

            if (timeoutoverride != null)
            {
                timeout = (TimeSpan)timeoutoverride;
            }

            var user_id = user.Id;
            var tsc     = new TaskCompletionSource <TypingContext>();
            var ct      = new CancellationTokenSource(timeout);

            ct.Token.Register(() => tsc.TrySetResult(null));

            AsyncEventHandler <TypingStartEventArgs> handler = async(e) =>
            {
                await Task.Yield();

                if (e.User.Id == user_id)
                {
                    var tc = new TypingContext()
                    {
                        Channel       = e.Channel,
                        Interactivity = this,
                        StartedAt     = e.StartedAt,
                        User          = e.User
                    };
                    tsc.TrySetResult(tc);
                    return;
                }
            };

            try
            {
                this.Client.TypingStarted += handler;

                var result = await tsc.Task.ConfigureAwait(false);

                return(result);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Client.TypingStarted -= handler;
            }
        }
Example #44
0
 protected RequestClient(IRequestPipeConnector connector, Uri responseAddress, TimeSpan timeout, TimeSpan?timeToLive = default(TimeSpan?),
                         Action <SendContext <TRequest> > callback = null)
 {
     _connector       = connector;
     _responseAddress = responseAddress;
     _timeout         = timeout;
     _timeToLive      = timeToLive;
     _callback        = callback;
 }
        public async Task <ReactionCollectionContext> CreatePollAsync(DiscordMessage message, IEnumerable <DiscordEmoji> emojis, TimeSpan?timeoutoverride = null)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (emojis == null)
            {
                throw new ArgumentNullException(nameof(emojis));
            }
            if (emojis.Count() < 1)
            {
                throw new InvalidOperationException("A minimum of one emoji is required to execute this method!");
            }

            TimeSpan timeout = Config.Timeout;

            if (timeoutoverride != null)
            {
                timeout = (TimeSpan)timeoutoverride;
            }

            foreach (var em in emojis)
            {
                await message.CreateReactionAsync(em).ConfigureAwait(false);
            }

            var rcc = new ReactionCollectionContext();
            var tsc = new TaskCompletionSource <ReactionCollectionContext>();
            var ct  = new CancellationTokenSource(timeout);

            ct.Token.Register(() => tsc.TrySetResult(rcc));

            try
            {
                this.Client.MessageReactionAdded    += ReactionAddHandler;
                this.Client.MessageReactionRemoved  += ReactionRemoveHandler;
                this.Client.MessageReactionsCleared += ReactionClearHandler;

                var result = await tsc.Task.ConfigureAwait(false);

                return(result);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Client.MessageReactionAdded    -= ReactionAddHandler;
                this.Client.MessageReactionRemoved  -= ReactionRemoveHandler;
                this.Client.MessageReactionsCleared -= ReactionClearHandler;
            }

            #region Handlers
            async Task ReactionAddHandler(MessageReactionAddEventArgs e)
            {
                if (e.Client.CurrentUser.Id != e.User.Id)
                {
                    await Task.Yield();

                    if (e.Message.Id == message.Id && emojis.Count(x => x == e.Emoji) > 0)
                    {
                        if (rcc._membersvoted.Contains(e.User.Id))
                        {
                            await e.Message.DeleteReactionAsync(e.Emoji, e.User);
                        }
                        else
                        {
                            rcc.AddReaction(e.Emoji, e.User.Id);
                        }
                    }
                    else
                    {
                        await e.Message.DeleteReactionAsync(e.Emoji, e.User);
                    }
                }
            }

            async Task ReactionRemoveHandler(MessageReactionRemoveEventArgs e)
            {
                if (e.Client.CurrentUser.Id != e.User.Id)
                {
                    await Task.Yield();

                    if (e.Message.Id == message.Id && emojis.Count(x => x == e.Emoji) > 0)
                    {
                        rcc.RemoveReaction(e.Emoji, e.User.Id);
                    }
                }
            }

            async Task ReactionClearHandler(MessageReactionsClearEventArgs e)
            {
                await Task.Yield();

                if (e.Message.Id == message.Id)
                {
                    rcc.ClearReactions();
                    foreach (var em in emojis)
                    {
                        await message.CreateReactionAsync(em).ConfigureAwait(false);
                    }
                }
            }

            #endregion
        }
        public async Task SendPaginatedMessage(DiscordChannel channel, DiscordUser user, IEnumerable <Page> message_pages, TimeSpan?timeoutoverride = null,
                                               TimeoutBehaviour?timeoutbehaviouroverride = null, PaginationEmojis emojis = null)
        {
            if (channel == null)
            {
                throw new ArgumentNullException(nameof(channel));
            }
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (message_pages == null)
            {
                throw new ArgumentNullException(nameof(message_pages));
            }
            if (message_pages.Count() < 1)
            {
                throw new InvalidOperationException("This method can only be executed with a minimum of one page!");
            }

            if (message_pages.Count() == 1)
            {
                await this.Client.SendMessageAsync(channel, string.IsNullOrEmpty(message_pages.First().Content)? "" : message_pages.First().Content, embed : message_pages.First().Embed).ConfigureAwait(false);

                return;
            }

            TimeSpan timeout = Config.Timeout;

            if (timeoutoverride != null)
            {
                timeout = (TimeSpan)timeoutoverride;
            }

            TimeoutBehaviour timeout_behaviour = Config.PaginationBehavior;

            if (timeoutbehaviouroverride != null)
            {
                timeout_behaviour = (TimeoutBehaviour)timeoutbehaviouroverride;
            }

            List <Page> pages = message_pages.ToList();

            if (pages.Count() == 0)
            {
                throw new ArgumentException("You need to provide at least 1 page!");
            }

            var tsc = new TaskCompletionSource <string>();
            var ct  = new CancellationTokenSource(timeout);

            ct.Token.Register(() => tsc.TrySetResult(null));

            DiscordMessage m = await this.Client.SendMessageAsync(channel, string.IsNullOrEmpty(pages.First().Content)? "" : pages.First().Content, embed : pages.First().Embed).ConfigureAwait(false);

            PaginatedMessage pm = new PaginatedMessage()
            {
                CurrentIndex = 0,
                Pages        = pages,
                Timeout      = timeout
            };

            emojis = emojis ?? new PaginationEmojis(this.Client);

            await this.GeneratePaginationReactions(m, emojis).ConfigureAwait(false);

            try
            {
                this.Client.MessageReactionsCleared += ReactionClearHandler;
                this.Client.MessageReactionAdded    += ReactionAddHandler;
                this.Client.MessageReactionRemoved  += ReactionRemoveHandler;

                await tsc.Task.ConfigureAwait(false);

                switch (timeout_behaviour)
                {
                case TimeoutBehaviour.Ignore:
                    await m.DeleteAllReactionsAsync().ConfigureAwait(false);

                    break;

                case TimeoutBehaviour.DeleteMessage:
                    // deleting a message deletes all reactions anyway
                    //await m.DeleteAllReactionsAsync().ConfigureAwait(false);
                    await m.DeleteAsync().ConfigureAwait(false);

                    break;

                case TimeoutBehaviour.DeleteReactions:
                    await m.DeleteAllReactionsAsync().ConfigureAwait(false);

                    break;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Client.MessageReactionsCleared -= ReactionClearHandler;
                this.Client.MessageReactionAdded    -= ReactionAddHandler;
                this.Client.MessageReactionRemoved  -= ReactionRemoveHandler;
            }

            #region Handlers
            async Task ReactionAddHandler(MessageReactionAddEventArgs e)
            {
                if (e.Message.Id == m.Id && e.User.Id != this.Client.CurrentUser.Id && e.User.Id == user.Id)
                {
                    ct.Dispose();
                    ct = new CancellationTokenSource(timeout);
                    ct.Token.Register(() => tsc.TrySetResult(null));
                    await this.DoPagination(e.Emoji, m, pm, ct, emojis).ConfigureAwait(false);
                }
            }

            async Task ReactionRemoveHandler(MessageReactionRemoveEventArgs e)
            {
                if (e.Message.Id == m.Id && e.User.Id != this.Client.CurrentUser.Id && e.User.Id == user.Id)
                {
                    ct.Dispose();
                    ct = new CancellationTokenSource(timeout);
                    ct.Token.Register(() => tsc.TrySetResult(null));
                    await this.DoPagination(e.Emoji, m, pm, ct, emojis).ConfigureAwait(false);
                }
            }

            async Task ReactionClearHandler(MessageReactionsClearEventArgs e)
            {
                await this.GeneratePaginationReactions(m, emojis).ConfigureAwait(false);
            }

            #endregion
        }
Example #47
0
        /// <summary>
        /// Receive a series of messages.
        /// It will continue to receive messages until the <paramref name="shouldIgnore"/> predicate returns <c>false</c> or the idle
        /// timeout is met (disabled by default) or the overall
        /// maximum duration is elapsed or expected messages count is reached.
        /// If a message that isn't of type <typeparamref name="T"/> the parameter <paramref name="shouldIgnoreOtherMessageTypes"/>
        /// declares if the message should be ignored or not.
        /// <para>Returns the sequence of messages.</para>
        ///
        /// Note that it is not an error to hit the `max` duration in this case.
        /// The max duration is scaled by <see cref="Dilated(TimeSpan)"/>
        /// </summary>
        /// <typeparam name="T">TBD</typeparam>
        /// <param name="shouldIgnore">TBD</param>
        /// <param name="max">TBD</param>
        /// <param name="idle">TBD</param>
        /// <param name="msgs">TBD</param>
        /// <param name="shouldIgnoreOtherMessageTypes">TBD</param>
        /// <returns>TBD</returns>
        public IReadOnlyList <T> ReceiveWhile <T>(Predicate <T> shouldIgnore, TimeSpan?max = null, TimeSpan?idle = null, int msgs = int.MaxValue, bool shouldIgnoreOtherMessageTypes = true) where T : class
        {
            var start    = Now;
            var maxValue = RemainingOrDilated(max);
            var stop     = start + maxValue;

            ConditionalLog("Trying to receive {0}messages of type {1} while predicate returns true during {2}. Messages of other types will {3}", msgs == int.MaxValue ? "" : msgs + " ", typeof(T), maxValue, shouldIgnoreOtherMessageTypes ? "be ignored" : "cause this to stop");

            var             count     = 0;
            var             acc       = new List <T>();
            var             idleValue = idle.GetValueOrDefault(Timeout.InfiniteTimeSpan);
            MessageEnvelope msg       = NullMessageEnvelope.Instance;

            while (count < msgs)
            {
                MessageEnvelope envelope;
                if (!TryReceiveOne(out envelope, (stop - Now).Min(idleValue)))
                {
                    _testState.LastMessage = msg;
                    break;
                }
                var message      = envelope.Message;
                var typedMessage = message as T;
                var shouldStop   = false;
                if (typedMessage != null)
                {
                    if (shouldIgnore(typedMessage))
                    {
                        acc.Add(typedMessage);
                        count++;
                    }
                    else
                    {
                        shouldStop = true;
                    }
                }
                else
                {
                    shouldStop = !shouldIgnoreOtherMessageTypes;
                }
                if (shouldStop)
                {
                    _testState.Queue.AddFirst(envelope);  //Put the message back in the queue
                    _testState.LastMessage = msg;
                    break;
                }
                msg = envelope;
            }
            ConditionalLog("Received {0} messages with filter during {1}", count, Now - start);

            _testState.LastWasNoMsg = true;
            return(acc);
        }
        public async Task <ReactionCollectionContext> CollectReactionsAsync(DiscordMessage message, TimeSpan?timeoutoverride = null)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            TimeSpan timeout = Config.Timeout;

            if (timeoutoverride != null)
            {
                timeout = (TimeSpan)timeoutoverride;
            }

            var rcc = new ReactionCollectionContext();
            var tsc = new TaskCompletionSource <ReactionCollectionContext>();
            var ct  = new CancellationTokenSource(timeout);

            ct.Token.Register(() => tsc.TrySetResult(rcc));

            try
            {
                this.Client.MessageReactionAdded    += ReactionAddHandler;
                this.Client.MessageReactionRemoved  += ReactionRemoveHandler;
                this.Client.MessageReactionsCleared += ReactionClearHandler;

                var result = await tsc.Task.ConfigureAwait(false);

                return(result);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Client.MessageReactionAdded    -= ReactionAddHandler;
                this.Client.MessageReactionRemoved  -= ReactionRemoveHandler;
                this.Client.MessageReactionsCleared -= ReactionClearHandler;
            }

            #region Handlers
            async Task ReactionAddHandler(MessageReactionAddEventArgs e)
            {
                await Task.Yield();

                if (e.Message.Id == message.Id)
                {
                    rcc.AddReaction(e.Emoji);
                }
            }

            async Task ReactionRemoveHandler(MessageReactionRemoveEventArgs e)
            {
                await Task.Yield();

                if (e.Message.Id == message.Id)
                {
                    rcc.RemoveReaction(e.Emoji, e.User.Id);
                }
            }

            async Task ReactionClearHandler(MessageReactionsClearEventArgs e)
            {
                await Task.Yield();

                if (e.Message.Id == message.Id)
                {
                    rcc.ClearReactions();
                }
            }

            #endregion
        }
Example #49
0
        /// <summary>
        /// Receive a series of messages until the function returns null or the idle
        /// timeout is met (disabled by default) or the overall
        /// maximum duration is elapsed or expected messages count is reached.
        /// Returns the sequence of messages.
        ///
        /// Note that it is not an error to hit the `max` duration in this case.
        /// The max duration is scaled by <see cref="Dilated(TimeSpan)"/>
        /// </summary>
        /// <typeparam name="T">TBD</typeparam>
        /// <param name="filter">TBD</param>
        /// <param name="max">TBD</param>
        /// <param name="idle">TBD</param>
        /// <param name="msgs">TBD</param>
        /// <returns>TBD</returns>
        public IReadOnlyList <T> ReceiveWhile <T>(Func <object, T> filter, TimeSpan?max = null, TimeSpan?idle = null, int msgs = int.MaxValue) where T : class
        {
            var maxValue = RemainingOrDilated(max);
            var start    = Now;
            var stop     = start + maxValue;

            ConditionalLog("Trying to receive {0}messages of type {1} while filter returns non-nulls during {2}", msgs == int.MaxValue ? "" : msgs + " ", typeof(T), maxValue);
            var             count     = 0;
            var             acc       = new List <T>();
            var             idleValue = idle.GetValueOrDefault(Timeout.InfiniteTimeSpan);
            MessageEnvelope msg       = NullMessageEnvelope.Instance;

            while (count < msgs)
            {
                MessageEnvelope envelope;
                if (!TryReceiveOne(out envelope, (stop - Now).Min(idleValue)))
                {
                    _testState.LastMessage = msg;
                    break;
                }
                var message = envelope.Message;
                var result  = filter(message);
                if (result == null)
                {
                    _testState.Queue.AddFirst(envelope);  //Put the message back in the queue
                    _testState.LastMessage = msg;
                    break;
                }
                msg = envelope;
                acc.Add(result);
                count++;
            }
            ConditionalLog("Received {0} messages with filter during {1}", count, Now - start);

            _testState.LastWasNoMsg = true;
            return(acc);
        }
        public async Task <ReactionContext> WaitForMessageReactionAsync(DiscordMessage message, DiscordUser user = null, TimeSpan?timeoutoverride = null)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            TimeSpan timeout = Config.Timeout;

            if (timeoutoverride != null)
            {
                timeout = (TimeSpan)timeoutoverride;
            }

            var message_id = message.Id;
            var tsc        = new TaskCompletionSource <ReactionContext>();
            var ct         = new CancellationTokenSource(timeout);

            ct.Token.Register(() => tsc.TrySetResult(null));

            try
            {
                this.Client.MessageReactionAdded += Handler;

                var result = await tsc.Task.ConfigureAwait(false);

                return(result);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Client.MessageReactionAdded -= Handler;
            }

            #region Handler
            async Task Handler(MessageReactionAddEventArgs e)
            {
                await Task.Yield();

                if (e.Message.Id == message_id)
                {
                    if (user == null || e.User.Id == user?.Id)
                    {
                        var rc = new ReactionContext()
                        {
                            Channel       = e.Channel,
                            Emoji         = e.Emoji,
                            Message       = e.Message,
                            User          = e.User,
                            Interactivity = this
                        };
                        tsc.TrySetResult(rc);
                        return;
                    }
                }
            }

            #endregion
        }
Example #51
0
 /// <summary>
 /// Receive one message from the internal queue of the TestActor within
 /// the specified duration.
 /// <para><c>True</c> is returned if a message existed, and the message
 /// is returned in <paramref name="envelope" />. The method blocks the
 /// specified duration, and can be cancelled using the
 /// <paramref name="cancellationToken" />.
 /// </para>
 /// <remarks>This method does NOT automatically scale its duration parameter using <see cref="Dilated(TimeSpan)" />!</remarks>
 /// </summary>
 /// <param name="envelope">The received envelope.</param>
 /// <param name="max">The maximum duration to wait.
 ///     If <c>null</c> the config value "akka.test.single-expect-default" is used as timeout.
 ///     If set to <see cref="Timeout.InfiniteTimeSpan"/>, blocks forever (or until cancelled).
 ///     <remarks>This method does NOT automatically scale its Duration parameter using <see cref="Dilated(TimeSpan)" />!</remarks>
 /// </param>
 /// <param name="cancellationToken">A token used to cancel the operation.</param>
 /// <returns><c>True</c> if a message was received within the specified duration; <c>false</c> otherwise.</returns>
 public bool TryReceiveOne(out MessageEnvelope envelope, TimeSpan?max, CancellationToken cancellationToken)
 {
     return(InternalTryReceiveOne(out envelope, max, cancellationToken, true));
 }
Example #52
0
 /// <summary>
 /// Receives messages until <paramref name="isMessage"/> returns <c>true</c>.
 /// Use it to ignore certain messages while waiting for a specific message.
 /// </summary>
 /// <param name="isMessage">The is message.</param>
 /// <param name="max">The maximum.</param>
 /// <param name="hint">The hint.</param>
 /// <returns>Returns the message that <paramref name="isMessage"/> matched</returns>
 public object FishForMessage(Predicate <object> isMessage, TimeSpan?max = null, string hint = "")
 {
     return(FishForMessage <object>(isMessage, max, hint));
 }
Example #53
0
        protected override int RunServerCore(string pipeName, IClientConnectionHost connectionHost, IDiagnosticListener listener, TimeSpan?keepAlive, CancellationToken cancellationToken)
        {
            // Grab the server mutex to prevent multiple servers from starting with the same
            // pipename and consuming excess resources. If someone else holds the mutex
            // exit immediately with a non-zero exit code
            var  mutexName = BuildServerConnection.GetServerMutexName(pipeName);
            bool holdsMutex;

            using (var serverMutex = new Mutex(initiallyOwned: true,
                                               name: mutexName,
                                               createdNew: out holdsMutex))
            {
                if (!holdsMutex)
                {
                    return(CommonCompiler.Failed);
                }

                try
                {
                    return(base.RunServerCore(pipeName, connectionHost, listener, keepAlive, cancellationToken));
                }
                finally
                {
                    serverMutex.ReleaseMutex();
                }
            }
        }
Example #54
0
 /// <summary>
 /// Receive a series of messages until the function returns null or the idle
 /// timeout is met or the overall maximum duration is elapsed or
 /// expected messages count is reached.
 /// Returns the sequence of messages.
 ///
 /// Note that it is not an error to hit the `max` duration in this case.
 /// The max duration is scaled by <see cref="Dilated(TimeSpan)"/>
 /// </summary>
 /// <typeparam name="T">TBD</typeparam>
 /// <param name="max">TBD</param>
 /// <param name="idle">TBD</param>
 /// <param name="filter">TBD</param>
 /// <param name="msgs">TBD</param>
 /// <returns>TBD</returns>
 public IReadOnlyList <T> ReceiveWhile <T>(TimeSpan?max, TimeSpan?idle, Func <object, T> filter, int msgs = int.MaxValue) where T : class
 {
     return(ReceiveWhile(filter, max, idle, msgs));
 }
Example #55
0
        public void WaitForCompletion(TaskResource[] tasks, int pollIntervalSeconds = 4, TimeSpan?timeoutAfter = null, Action <TaskResource[]> interval = null)
        {
            var start = Stopwatch.StartNew();

            if (tasks == null || tasks.Length == 0)
            {
                return;
            }

            while (true)
            {
                var stillRunning =
                    (from task in tasks
                     let currentStatus = Client.Get <TaskResource>(task.Link("Self"))
                                         select currentStatus).ToArray();

                interval?.Invoke(stillRunning);

                if (stillRunning.All(t => t.IsCompleted))
                {
                    return;
                }

                if (timeoutAfter.HasValue && timeoutAfter > TimeSpan.Zero && start.Elapsed > timeoutAfter)
                {
                    throw new TimeoutException(string.Format("One or more tasks did not complete before the timeout was reached. We waited {0:n1} minutes for the tasks to complete.", start.Elapsed.TotalMinutes));
                }

                Thread.Sleep(TimeSpan.FromSeconds(pollIntervalSeconds));
            }
        }
Example #56
0
 /// <summary>
 /// Receive one message from the internal queue of the TestActor within
 /// the specified duration. The method blocks the specified duration.
 /// <remarks><b>Note!</b> that the returned <paramref name="envelope"/>
 /// is a <see cref="MessageEnvelope"/> containing the sender and the message.</remarks>
 /// <remarks>This method does NOT automatically scale its Duration parameter using <see cref="Dilated(TimeSpan)" />!</remarks>
 /// </summary>
 /// <param name="envelope">The received envelope.</param>
 /// <param name="max">Optional: The maximum duration to wait.
 ///     If <c>null</c> the config value "akka.test.single-expect-default" is used as timeout.
 ///     If set to a negative value or <see cref="Timeout.InfiniteTimeSpan"/>, blocks forever.
 ///     <remarks>This method does NOT automatically scale its Duration parameter using <see cref="Dilated(TimeSpan)" />!</remarks></param>
 /// <returns><c>True</c> if a message was received within the specified duration; <c>false</c> otherwise.</returns>
 public bool TryReceiveOne(out MessageEnvelope envelope, TimeSpan?max = null)
 {
     return(TryReceiveOne(out envelope, max, CancellationToken.None));
 }
        public static void SaveSession(this IAuthProvider provider, IServiceBase authService, IAuthSession session, TimeSpan?sessionExpiry = null)
        {
            var persistSession = !(provider is AuthProvider authProvider) || authProvider.PersistSession;

            if (persistSession)
            {
                authService.SaveSession(session, sessionExpiry);
            }
            else
            {
                authService.Request.Items[Keywords.Session] = session;
            }
        }
Example #58
0
        internal static new int RunServer(string pipeName, IClientConnectionHost clientConnectionHost = null, IDiagnosticListener listener = null, TimeSpan?keepAlive = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            BuildServerController controller = new DesktopBuildServerController(new NameValueCollection());

            return(controller.RunServer(pipeName, clientConnectionHost, listener, keepAlive, cancellationToken));
        }
Example #59
0
 /// <summary>
 /// Creates a <see cref="Source{TOut,TMat}"/> which when materialized will return an <see cref="Stream"/> which it is possible
 /// to write the ByteStrings to the stream this Source is attached to.
 ///
 /// This Source is intended for inter-operation with legacy APIs since it is inherently blocking.
 ///
 /// You can configure the default dispatcher for this Source by changing the "akka.stream.blocking-io-dispatcher" or
 /// set it for a given Source by using <see cref="ActorAttributes.CreateDispatcher"/>.
 ///
 /// The created <see cref="Stream"/> will be closed when the <see cref="Source{TOut,TMat}"/> is cancelled, and closing the <see cref="Stream"/>
 /// will complete this <see cref="Source{TOut,TMat}"/>.
 /// </summary>
 /// <param name="writeTimeout">The max time the write operation on the materialized OutputStream should block, defaults to 5 seconds</param>
 /// <returns>TBD</returns>
 public static Source <ByteString, Stream> AsOutputStream(TimeSpan?writeTimeout = null)
 => Source.FromGraph(new OutputStreamSourceStage(writeTimeout ?? TimeSpan.FromSeconds(5)));
        /// <summary>
        /// Instantiate a rate limited IZipkinSender which use an underlying IZipkinSender to send data.
        /// The average sending rate is given by maxSendRequest / duration, instantaneous rate can be much higher.
        /// </summary>
        /// <param name="sender">The underlying IZipkinSender</param>
        /// <param name="maxSendRequest">The maximum send requests per duration aka the bucket size</param>
        /// <param name="duration">TimeSpan necessary to refill the bucket</param>
        public RateLimiterZipkinSender(IZipkinSender sender, int maxSendRequest = 15, TimeSpan?duration = null)
        {
            _underlyingSender = sender;
            MaxSendRequests   = maxSendRequest;
            Duration          = duration ?? TimeSpan.FromSeconds(1);

            _logPeriod         = TimeSpan.FromTicks(Duration.Ticks * 10);
            _requestsReceived  = 0;
            _throttledRequests = 0;
            _currentLogPeriod  = new Stopwatch();

            _bucket = MaxSendRequests;
            _timeSinceLastRequest = Stopwatch.StartNew();
            Rate = MaxSendRequests / Duration.TotalMilliseconds;
        }