protected BaseSteamCommand(ISteamSessionFactory factory) { _factory = factory; _app = SystemExtensions.CreateLazy(() => new App(AppId)); HasRequiredOption <uint>("a|appid=", "AppID", s => AppId = s); HasFlag("v|verbose", "Verbose", f => Common.Flags.Verbose = f); }
// Gets the full game ranking entries private async Task <List <RankingDto> > GetFullGameRankingAsync(RankingRequest request) { var rankingEntries = new ConcurrentBag <RankingDto>(); var tasks = new List <Task>(); foreach (var stage in request.Game.GetStages()) { tasks.Add(Task.Run(async() => { foreach (var level in SystemExtensions.Enumerate <Level>()) { if (!request.SkipStages.Contains(stage)) { var stageLevelRankings = await GetStageLevelRankingAsync(request, stage, level) .ConfigureAwait(false); rankingEntries.AddRange(stageLevelRankings); } } })); } await Task.WhenAll(tasks).ConfigureAwait(false); return(rankingEntries.ToList()); }
/// <summary> /// <para> /// Looks up the specified full type name in all loaded assemblies, /// ignoring assembly version. /// </para> /// <para> /// In order to understand how to access generic types, /// see http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx. /// </para> /// </summary> /// <param name="fullName">Full name of the type to find.</param> /// <returns>Type with the specified name.</returns> /// <exception cref="TypeLoadException">If the type couldn't be found.</exception> public static Type FindType(string fullName) { if (string.IsNullOrEmpty(fullName)) { return(null); } // Split type name from .dll version. fullName = SystemExtensions.RemoveAssemblyInfo(fullName); Type t = Type.GetType(fullName); if (t != null) { return(t); } foreach (Assembly asm in AssemblyUtils.GetLoadedAssemblies()) { t = asm.GetType(fullName); if (t != null) { return(t); } } throw new TypeLoadException(string.Format("Unable to find type {0}.", fullName)); }
public virtual void DoWait(IQueuedSync sync) { lock (this) { if (!sync.Recheck(this)) { try { while (_waiting) { Monitor.Wait(this); } } catch (ThreadInterruptedException ex) { if (_waiting) { // no notification _waiting = false; // invalidate for the signaller throw SystemExtensions.PreserveStackTrace(ex); } // thread was interrupted after it was notified Thread.CurrentThread.Interrupt(); return; } } } }
private void SerializeValueWithType(ValueWithType valueWithType) { string typeName = SystemExtensions.RemoveAssemblyInfo(valueWithType.TypeFullName); this.writer.Write(typeName); this.Serialize(valueWithType.Value, valueWithType.Type); }
/// <summary> /// Retrieves and removes the head of this queue, waiting up to the /// specified wait time if necessary for an element to become available. /// </summary> /// <param name="element"> /// Set to the head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <param name="duration">How long to wait before giving up.</param> /// <returns> /// <c>false</c> if the queue is still empty after waited for the time /// specified by the <paramref name="duration"/>. Otherwise <c>true</c>. /// </returns> public override bool Poll(TimeSpan duration, out T element) { DateTime deadline = WaitTime.Deadline(duration); using (_lock.LockInterruptibly()) { while (!_wrapped.Poll(out element)) { if (duration.Ticks <= 0) { element = default(T); return(false); } try { _notEmptyCondition.Await(WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } catch (ThreadInterruptedException e) { _notEmptyCondition.Signal(); throw SystemExtensions.PreserveStackTrace(e); } } _notFullCondition.Signal(); return(true); } }
/// <inheritdoc /> public async Task <IReadOnlyCollection <EntryWebDto> > ExtractStageAllTimeEntriesAsync(Stage stage) { var entries = new List <EntryWebDto>(); var logs = new List <string>(); string pageContent = await GetPageStringContentAsync($"/ajax/stage/{(long)stage}/{_configuration.AjaxKey}").ConfigureAwait(false); if (string.IsNullOrWhiteSpace(pageContent)) { throw new FormatException($"Unables to load the page content for stage {stage}."); } var jsonContent = Newtonsoft.Json.JsonConvert.DeserializeObject <IReadOnlyCollection <IReadOnlyCollection <object> > >(pageContent); if (jsonContent == null || jsonContent.Count != SystemExtensions.Count <Level>()) { throw new FormatException($"The list of entries by level is invalid."); } Dictionary <Level, List <long> > links = ExtractEntryIdListFromJsonContent(jsonContent, logs); foreach (Level levelKey in links.Keys) { foreach (long entryId in links[levelKey]) { var entryDetails = await ExtractEntryDetailsAsync(entryId, stage, levelKey, logs).ConfigureAwait(false); entries.AddRange(entryDetails); } } return(entries); }
public override void LockInterruptibly() { Thread caller = Thread.CurrentThread; lock (this) { if (GetHold(caller)) { return; } try { do { Monitor.Wait(this); } while (_owner != null); _owner = caller; _holds = 1; return; } catch (ThreadInterruptedException e) { if (_owner == null) { Monitor.Pulse(this); } throw SystemExtensions.PreserveStackTrace(e); } } }
public CompareExcel() { dir1 = SystemExtensions.GetInputStr("请拖入选定文件(.xls|xlsx):", "您选择的文件:"); dir2 = SystemExtensions.GetInputStr("请拖入选定文件(.xls|xlsx):", "您选择的文件:"); var vals1 = new ExcelByNpoi().ReadFromExcels(dir1); var vals2 = new ExcelByNpoi().ReadFromExcels(dir2); var index = 0; foreach (KeyValuePair <string, List <List <object> > > keyValuePair in vals1) { List <List <object> > lst = new List <List <object> >(); if (vals2.TryGetValue(keyValuePair.Key, out lst)) { var haha = keyValuePair.Value.Except(lst).ToList(); var newName = Path.GetDirectoryName(dir1) + "/" + Path.GetFileNameWithoutExtension(dir1) + "-" + Path.GetFileNameWithoutExtension(dir2) + ".xlsx"; new ExcelByNpoi().WriteToExcel(newName, haha); } else { Console.WriteLine(dir2 + " 不存在的sheet:" + keyValuePair.Key); } } }
/** * Tries to cancel on interrupt; if so rethrowing, * else setting interrupt state * * PRE: lock owned */ private void CheckCancellationOnInterrupt(ThreadInterruptedException ie) { if (_state == 0) { _state = Cancel; Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(ie); } Thread.CurrentThread.Interrupt(); }
protected LocalContent(string packageName, Guid gameId, string version) : base(gameId) { if (!(!string.IsNullOrWhiteSpace(packageName))) { throw new ArgumentNullException("!string.IsNullOrWhiteSpace(packageName)"); } PackageName = packageName; Version = version; _source = SystemExtensions.CreateLazy(() => new ContentPublisher(Publisher.withSIX, PackageName)); }
internal RankingEntryLight(Game game, PlayerDto player) { Game = game; Player = new Player(player); Points = 0; UntiedRecordsCount = 0; RecordsCount = 0; CumuledTime = (UnsetTimeValueSeconds * Game.GetStages().Count) * SystemExtensions.Count <Level>(); }
public virtual bool AwaitUntil(DateTime deadline) { int holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } if ((deadline.Subtract(DateTime.UtcNow)).Ticks <= 0) { return(false); } // This requires sleep(0) to implement in .Net, too expensive! // if (Thread.interrupted()) throw new InterruptedException(); try { lock (this) { for (int i = holdCount; i > 0; i--) { _lock.Unlock(); } try { // .Net has DateTime precision issue so we need to retry. TimeSpan durationToWait; while ((durationToWait = deadline.Subtract(DateTime.UtcNow)).Ticks > 0) { // .Net implementation is different than backport 3.1 // by taking advantage of the return value from Monitor.Wait. if (Monitor.Wait(this, durationToWait)) { return(true); } } } catch (ThreadInterruptedException e) { Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(e); } } } finally { for (int i = holdCount; i > 0; i--) { _lock.Lock(); } } return(false); }
protected PackagedContent(string packageName, Guid gameId) : base(gameId) { if (packageName == null) { throw new ArgumentNullException(nameof(packageName)); } if (!(!string.IsNullOrWhiteSpace(packageName))) { throw new ArgumentOutOfRangeException("!string.IsNullOrWhiteSpace(packageName)"); } PackageName = packageName; _source = SystemExtensions.CreateLazy(() => new ContentPublisher(Publisher.withSIX, PackageName)); }
private static bool IsCaptionStream(IDictionary <string, string> streamAttributes) { StreamType result; string type = streamAttributes.GetEntryIgnoreCase(TypeAttribute); string subType = streamAttributes.GetEntryIgnoreCase(SubTypeAttribute); #if SILVERLIGHT3 return(SystemExtensions.TryParse(type, true, out result) #else return Enum.TryParse(type, true, out result) #endif && result == StreamType.Text && AllowedCaptionStreamSubTypes.Any(i => string.Equals(i, subType, StringComparison.CurrentCultureIgnoreCase))); }
/// <summary> /// Inserts the specified element into this queue, waiting if necessary /// for space to become available. /// </summary> /// <remarks> /// <see cref="Break"/> the queue will cause a waiting <see cref="TryPut"/> /// to returned <c>false</c>. This is very useful to indicate that the /// consumer is stopped or going to stop so that the producer should not /// put more items into the queue. /// </remarks> /// <param name="element">the element to add</param> /// <returns> /// <c>true</c> if succesfully and <c>false</c> if queue <see cref="IsBroken"/>. /// </returns> /// <exception cref="ThreadInterruptedException"> /// if interrupted while waiting. /// </exception> public virtual bool TryPut(T element) { int tempCount; lock (_putLock) { /* * Note that count is used in wait guard even though it is * not protected by lock. This works because count can * only decrease at this point (all other puts are shut * out by lock), and we (or some other waiting put) are * signaled if it ever changes from capacity. Similarly * for all other uses of count in other wait guards. */ if (_isBroken) { return(false); } try { while (_activeCount == _capacity) { Monitor.Wait(_putLock); if (_isBroken) { return(false); } } } catch (ThreadInterruptedException e) { Monitor.Pulse(_putLock); throw SystemExtensions.PreserveStackTrace(e); } Insert(element); lock (this) { tempCount = _activeCount++; } if (tempCount + 1 < _capacity) { Monitor.Pulse(_putLock); } } if (tempCount == 0) { SignalNotEmpty(); } return(true); }
/// <summary> /// Returns base64 hash representation of the search scoring model /// </summary> /// <returns>The base64 hash of the scoring settings</returns> public override string ToString() { if (!string.IsNullOrEmpty(this.ScoringProfile)) { string scoringSettingsString = this.ScoringProfile; if (!string.IsNullOrEmpty(this.ScoringParameters)) { scoringSettingsString = $"{scoringSettingsString};{this.ScoringParameters}"; } var encodedScoringSettings = SystemExtensions.Base64Encode(scoringSettingsString); return(encodedScoringSettings); } return(string.Empty); }
public static Dictionary <TKey, TValue> FindAll <TKey, TValue>( this Dictionary <TKey, TValue> dictionary, Predicate <KeyValuePair <TKey, TValue> > match) { Dictionary <TKey, TValue> result = new Dictionary <TKey, TValue>(); SystemExtensions.ForEach <KeyValuePair <TKey, TValue> >((IEnumerable <M0>)dictionary, (Action <M0>)(x => { if (!match(x)) { return; } result.Add(x.Key, x.Value); })); return(result); }
/// <summary> /// Retrieves and removes the head of this queue, waiting up to the /// specified wait time if necessary for another thread to insert it. /// </summary> /// <param name="element"> /// Set to the head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <param name="duration">How long to wait before giving up.</param> /// <returns> /// <c>false</c> if the queue is still empty after waited for the time /// specified by the <paramref name="duration"/>. Otherwise <c>true</c>. /// </returns> public override bool Poll(TimeSpan duration, out T element) { for (; ;) { Node node; bool mustWait; //if (Thread.interrupted()) throw new InterruptedException(); using (_qlock.Lock()) { node = _waitingProducers.Dequeue(); mustWait = (node == null); if (mustWait) { node = _waitingConsumers.Enqueue(default(T)); } } if (mustWait) { try { T x; bool success = node.WaitForPut(duration, out x); if (!success) { UnlinkCancelledConsumer(node); } element = x; return(success); } catch (ThreadInterruptedException e) { UnlinkCancelledConsumer(node); throw SystemExtensions.PreserveStackTrace(e); } } else { T x; if (node.GetItem(out x)) { element = x; return(true); } // else cancelled, so retry } } }
private async Task <IActionResult> SimulateRankingInternalAsync( Game game, DateTime?rankingDate, long?playerId = null, int?monthsPrior = null, Stage[] skipStages = null, bool?excludeWinners = false, int?engine = null) { return(await DoAndCatchAsync( RankingViewName, "The GoldenEye/PerfectDark World Records and Rankings SIMULATOR", async() => { var rankingEntries = await GetRankingsWithParamsAsync(game, rankingDate ?? DateTime.Now, playerId, monthsPrior, skipStages, excludeWinners, engine).ConfigureAwait(false); var pointsRankingEntries = rankingEntries .Where(r => r.Rank <= MaxRankDisplay) .Select(r => r.ToPointsRankingItemData()) .ToList(); // this does not manage equality between two global times // ie one player will be ranked above/below the other one int rank = 1; var timeRankingEntries = rankingEntries .OrderBy(x => x.CumuledTime) .Take(MaxRankDisplay) .Select(r => r.ToTimeRankingItemData(rank++)) .ToList(); var secondsLevel = SystemExtensions.Enumerate <Level>().ToDictionary(l => l, l => 0); var stageWorldRecordEntries = game.GetStages() .Select(s => s.ToStageWorldRecordItemData(rankingEntries, secondsLevel, StageImagePath)) .ToList(); return new SimulatedRankingViewData { CombinedTime = new TimeSpan(0, 0, secondsLevel.Values.Sum()), EasyCombinedTime = new TimeSpan(0, 0, secondsLevel[Level.Easy]), MediumCombinedTime = new TimeSpan(0, 0, secondsLevel[Level.Medium]), HardCombinedTime = new TimeSpan(0, 0, secondsLevel[Level.Hard]), PointsRankingEntries = pointsRankingEntries, TimeRankingEntries = timeRankingEntries, StageWorldRecordEntries = stageWorldRecordEntries }; }).ConfigureAwait(false)); }
public async Task <IActionResult> GetRankingByEngineAsync( [FromRoute] Game game, [FromQuery] DateTime?rankingDate, [FromQuery] int engine) { if (!Enum.TryParse(typeof(Game), game.ToString(), out _)) { return(BadRequest()); } if (!SystemExtensions.Enumerate <Engine>().Any(e => engine == (int)e)) { return(BadRequest()); } return(await SimulateRankingInternalAsync(game, rankingDate, engine : engine) .ConfigureAwait(false)); }
public virtual bool DoTimedWait(IQueuedSync sync, TimeSpan duration) { lock (this) { if (sync.Recheck(this) || !_waiting) { return(true); } if (duration.Ticks <= 0) { _waiting = false; return(false); } DateTime deadline = DateTime.UtcNow.Add(duration); try { for (;;) { Monitor.Wait(this, duration); if (!_waiting) // definitely signalled { return(true); } duration = deadline.Subtract(DateTime.UtcNow); if (duration.Ticks <= 0) // time out { _waiting = false; return(false); } } } catch (ThreadInterruptedException ex) { if (_waiting) // no notification { _waiting = false; // invalidate for the signaller throw SystemExtensions.PreserveStackTrace(ex); } // thread was interrupted after it was notified Thread.CurrentThread.Interrupt(); return(true); } } }
/// <summary> /// Inserts the specified element into this queue, waiting up to the /// specified wait time if necessary for space to become available. /// </summary> /// <param name="element">the element to add</param> /// <param name="duration">how long to wait before giving up</param> /// <returns> <c>true</c> if successful, or <c>false</c> if /// the specified waiting time elapses before space is available /// </returns> /// <exception cref="System.InvalidOperationException"> /// If the element cannot be added at this time due to capacity restrictions. /// </exception> /// <exception cref="ThreadInterruptedException"> /// if interrupted while waiting. /// </exception> public override bool Offer(T element, TimeSpan duration) { DateTime deadline = WaitTime.Deadline(duration); int tempCount; lock (_putLock) { for (; ;) { if (_isBroken) { return(false); } if (_activeCount < _capacity) { Insert(element); lock (this) { tempCount = _activeCount++; } if (tempCount + 1 < _capacity) { Monitor.Pulse(_putLock); } break; } if (duration.Ticks <= 0) { return(false); } try { Monitor.Wait(_putLock, WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } catch (ThreadInterruptedException e) { Monitor.Pulse(_putLock); throw SystemExtensions.PreserveStackTrace(e); } } } if (tempCount == 0) { SignalNotEmpty(); } return(true); }
public override bool TryLock(TimeSpan durationToWait) { Thread caller = Thread.CurrentThread; lock (this) { if (GetHold(caller)) { return(true); } if (durationToWait.Ticks <= 0) { return(false); } DateTime deadline = DateTime.UtcNow.Add(durationToWait); try { for (;;) { Monitor.Wait(this, durationToWait); if (_owner == null) { _owner = caller; _holds = 1; return(true); } durationToWait = deadline.Subtract(DateTime.UtcNow); if (durationToWait.Ticks <= 0) { return(false); } } } catch (ThreadInterruptedException e) { if (_owner == null) { Monitor.Pulse(this); } throw SystemExtensions.PreserveStackTrace(e); } } }
/// <summary> /// Inserts the specified element into this queue, waiting if necessary /// for space to become available. /// </summary> /// <param name="element">the element to add</param> /// <exception cref="System.ArgumentNullException"> /// If the specified element is <see langword="null"/> and this queue /// does not permit <see langword="null"/> elements. /// </exception> /// <exception cref="System.ArgumentException"> /// If some property of the supplied <paramref name="element"/> prevents /// it from being added to this queue. /// </exception> public override void Put(T element) { using (_lock.LockInterruptibly()) { try { while (!_wrapped.Offer(element)) { _notFullCondition.Await(); } _notEmptyCondition.Signal(); } catch (ThreadInterruptedException e) { _notFullCondition.Signal(); throw SystemExtensions.PreserveStackTrace(e); } } }
/// <summary> /// Retrieves and removes the head of this queue, waiting up to the /// specified wait time if necessary for an element to become available. /// </summary> /// <param name="element"> /// Set to the head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <param name="duration">How long to wait before giving up.</param> /// <returns> /// <c>false</c> if the queue is still empty after waited for the time /// specified by the <paramref name="duration"/>. Otherwise <c>true</c>. /// </returns> public override bool Poll(TimeSpan duration, out T element) { DateTime deadline = WaitTime.Deadline(duration); T x; int c; lock (_takeLock) { for (; ;) { if (_activeCount > 0) { x = Extract(); lock (this) { c = _activeCount--; } if (c > 1) { Monitor.Pulse(_takeLock); } break; } if (duration.Ticks <= 0 || _isBroken) { element = default(T); return(false); } try { Monitor.Wait(_takeLock, WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } catch (ThreadInterruptedException e) { Monitor.Pulse(_takeLock); throw SystemExtensions.PreserveStackTrace(e); } } } if (c == _capacity) { SignalNotFull(); } element = x; return(true); }
private static S3StoreInfo OpenS3Store(string path) { string[] parts = path.Split('/'); if (parts.Length < 3) { throw new ArgumentException("The specified S3 resource path (" + path + ") is invalid!"); } EncryptionType encryptionType; switch (parts[0].ToLowerInvariant()) { case "s3:": encryptionType = EncryptionType.None; break; case "s3e:": encryptionType = EncryptionType.SSE_S3; break; case "s3k:": encryptionType = EncryptionType.SSE_KMS; break; case "s3x:": encryptionType = EncryptionType.SSE_C; break; default: throw new ArgumentException("The specified resource path (" + path + ") is not a valid S3 resource path!"); } string bucket = parts[2]; string prefix = String.Join("/", parts, 3, parts.Length - 3) + "/"; if (!String.IsNullOrEmpty(parts[1]) || String.IsNullOrEmpty(bucket) || String.IsNullOrEmpty(prefix) || prefix.StartsWith("/")) { throw new ArgumentException("The specified resource path (" + path + ") is not a valid S3 resource path!"); } int?sliceId = SystemExtensions.TryParseInt(parts[parts.Length - 1]); return(new S3StoreInfo(new AmazonS3Client(), sliceId, bucket, prefix, encryptionType)); }
/// <summary> /// Inserts the specified element into this queue, waiting up to the /// specified wait time if necessary for another thread to receive it. /// </summary> /// <param name="element">The element to add.</param> /// <param name="duration">How long to wait before giving up.</param> /// <returns> /// <see langword="true"/> if successful, or <see langword="false"/> if /// the specified waiting time elapses before space is available. /// </returns> /// <exception cref="ThreadInterruptedException"> /// if interrupted while waiting. /// </exception> public override bool Offer(T element, TimeSpan duration) { for (; ;) { Node node; bool mustWait; //if (Thread.interrupted()) throw new InterruptedException(); using (_qlock.Lock()) { node = _waitingConsumers.Dequeue(); mustWait = (node == null); if (mustWait) { node = _waitingProducers.Enqueue(element); } } if (mustWait) { try { bool x = node.WaitForTake(duration); if (!x) { UnlinkCancelledProducer(node); } return(x); } catch (ThreadInterruptedException tie) { UnlinkCancelledProducer(node); throw SystemExtensions.PreserveStackTrace(tie); } } else if (node.SetItem(element)) { return(true); } // else consumer cancelled, so retry } }
/// <summary> /// Retrieves and removes the head of this queue, waiting if necessary /// until an element becomes available. /// </summary> /// <returns> the head of this queue</returns> public override T Take() { using (_lock.LockInterruptibly()) { try { T element; while (!_wrapped.Poll(out element)) { _notEmptyCondition.Await(); } _notFullCondition.Signal(); return(element); } catch (ThreadInterruptedException e) { _notEmptyCondition.Signal(); throw SystemExtensions.PreserveStackTrace(e); } } }
/// <summary> /// Retrieves and removes the head of this queue, waiting if necessary /// until another thread inserts it. /// </summary> /// <returns> the head of this queue</returns> /// <exception cref="ThreadInterruptedException"> /// if interrupted while waiting. /// </exception> public override T Take() { for (; ;) { Node node; bool mustWait; //if (Thread.interrupted()) throw new InterruptedException(); using (_qlock.Lock()) { node = _waitingProducers.Dequeue(); mustWait = (node == null); if (mustWait) { node = _waitingConsumers.Enqueue(default(T)); } } if (mustWait) { try { return(node.WaitForPut()); } catch (ThreadInterruptedException e) { UnlinkCancelledConsumer(node); throw SystemExtensions.PreserveStackTrace(e); } } else { T x; if (node.GetItem(out x)) { return(x); } // else cancelled, so retry } } }