public void GetTextTest() { for (var round = 0; round < 100; round++) { var count = ConcurrentRandom.Next(1, 100); var profilers = new Profiler[count]; for (var i = 0; i < count; i++) { var name = nameof(GetTextTest) + string.Format("{0:0000}", (int)(i / 2)); profilers[i] = ProfilerGroup.Default.CreateInstance(new ProfilerOptions(ProfilerType.Counter), name); profilers[i].Set(i + 10); } ; var list = ProfilerGroup.Default.GetMeasurements(); for (var i = 0; i < profilers.Length; i++) { var name = nameof(GetTextTest) + string.Format("{0:0000}", (int)(i / 2)); Assert.Equal(name, list[i].Key); Assert.Equal((i + 10).ToString(), list[i].Value); } for (var i = 0; i < profilers.Length; i++) { profilers[i].Dispose(); } } }
/// <summary> /// The Diffie–Hellman key exchange method allows two parties that have no prior knowledge of each /// other to jointly establish a shared secret key over an insecure communications channel. This /// key can then be used to encrypt subsequent communications using a symmetric key cipher. This /// class controls communication between the client and server using NetDragon Websoft's exchange /// request packet. Once keys are set, Blowfish will be reinitialized and the message server will /// begin to receive packets. /// </summary> static NetDragonDHKeyExchange() { DiffieHellmanKeyExchange exchange = new DiffieHellmanKeyExchange(PRIMATIVE_ROOT, GENERATOR); _serverRequestKey = exchange.GenerateRequest(); RandomGenerator = new ConcurrentRandom(); }
private void FindNewMessageSender(string path) { if (!string.Equals(this.Backlog.Path, path, StringComparison.OrdinalIgnoreCase) || this.Options.BacklogQueueCount <= 1) { return; } lock (this.backlogLock) { if (string.Equals(this.Backlog.Path, path, StringComparison.OrdinalIgnoreCase)) { int num = ConcurrentRandom.Next(0, this.Options.BacklogQueueCount); string str = this.Options.FetchBacklogQueueName(num); if (string.Equals(path, str, StringComparison.OrdinalIgnoreCase)) { num++; if (num >= this.Options.BacklogQueueCount) { num = 0; } str = this.Options.FetchBacklogQueueName(num); } this.Backlog = this.Options.SecondaryMessagingFactory.CreateMessageSender(str); this.Backlog.ShouldLinkRetryPolicy = true; this.Backlog.RetryPolicy = this.Options.SecondaryMessagingFactory.RetryPolicy; } } }
protected override bool OnShouldRetry(TimeSpan remainingTime, int currentRetryCount, out TimeSpan retryInterval) { if (currentRetryCount > this.MaxRetryCount) { retryInterval = TimeSpan.Zero; return(false); } int totalMilliseconds = (int)(this.DeltaBackoff.TotalMilliseconds * 0.8); TimeSpan deltaBackoff = this.DeltaBackoff; int num = ConcurrentRandom.Next(totalMilliseconds, (int)(deltaBackoff.TotalMilliseconds * 1.2)); double num1 = (Math.Pow(2, (double)currentRetryCount) - 1) * (double)num; TimeSpan minimalBackoff = this.MinimalBackoff; TimeSpan maximumBackoff = this.MaximumBackoff; double num2 = Math.Min(minimalBackoff.TotalMilliseconds + num1, maximumBackoff.TotalMilliseconds); retryInterval = TimeSpan.FromMilliseconds(num2); if (base.IsServerBusy) { retryInterval = retryInterval + RetryPolicy.ServerBusyBaseSleepTime; } if (retryInterval < (remainingTime - this.TerminationTimeBuffer)) { return(true); } retryInterval = TimeSpan.Zero; return(false); }
public void MaxHistoryTest() { for (var max = 1; max < 100; max++) { var profiler = new Profiler(new ProfilerOptions(ProfilerType.SampleAverageTimeMs, max, 1000, null), nameof(MaxHistoryTest)); Int64 totalCount = 0; var avgCount = 0; for (var i = 0; i < 1000; i++) { var r = ConcurrentRandom.NextInt32(); var a = ConcurrentRandom.Next(1, 100); profiler.AddTimeMeasurement(r, a); } for (var i = 0; i < max; i++) { var r = ConcurrentRandom.NextInt32(); var a = ConcurrentRandom.Next(1, 100); totalCount += r; avgCount += a; profiler.AddTimeMeasurement(r, a); } var avg = ((double)totalCount / 10_000D) / avgCount; Assert.InRange(profiler.GetValue(), avg - 0.1D, avg + 0.1D); Assert.Equal(String.Format("{0:0,0.00}", profiler.GetValue()), profiler.GetText()); } }
/// <summary> /// Choose random index in the list of available numbers /// and pick the number placed by this index. /// </summary> /// <returns>Guessed number</returns> public override int GuessNumber() { var randomIndex = ConcurrentRandom.Generate(0, _numbersToGuess.Count - 1); lock (_numbersToGuess) return(_numbersToGuess[randomIndex]); }
public void TimeExpireTest() { for (var max = 100; max < 200; max++) { var profiler = new Profiler(new ProfilerOptions(ProfilerType.SampleAverageTimeMs, max, 10, null), nameof(TimeExpireTest)); Int64 totalCount = 0; var avgCount = 0; for (var i = 0; i < 100; i++) { var r = ConcurrentRandom.NextInt32(); var a = ConcurrentRandom.Next(1, 100); profiler.AddTimeMeasurement(r, a); } Thread.Sleep(10); for (var i = 0; i < max - 100; i++) { var r = ConcurrentRandom.NextInt32(); var a = ConcurrentRandom.Next(1, 100); totalCount += r; avgCount += a; profiler.AddTimeMeasurement(r, a); } if (avgCount != 0 && totalCount != 0) { var avg = ((double)totalCount / 10_000D) / avgCount; Assert.InRange(profiler.GetValue(), avg - 0.1D, avg + 0.1D); } Assert.Equal(String.Format("{0:0,0.00}", profiler.GetValue()), profiler.GetText()); Assert.Throws <ArgumentOutOfRangeException>(() => profiler.AddTimeMeasurement(1, 0)); Assert.Throws <ArgumentOutOfRangeException>(() => profiler.AddTimeMeasurement(1, -1)); } }
/// <summary> /// If <see cref="JitterMaxDuration"/> is greater than <see cref="TimeSpan.Zero"/>, this method returns a randomized duration (in ms) between 0 and <see cref="JitterMaxDuration"/> that will be added to the entry's specified <see cref="Duration"/> . /// This is done to avoid a variation of the so called <a href="https://en.wikipedia.org/wiki/Thundering_herd_problem">thundering herd problem</a> that may happen when the entry for the same key expires on multiple nodes at the same time, because of high synchronization. /// </summary> /// <returns>An additional cache duration (in ms) to slightly vary the entry duration</returns> public double GetJitterDurationMs() { if (JitterMaxDuration <= TimeSpan.Zero) { return(0d); } return(ConcurrentRandom.NextDouble() * JitterMaxDuration.TotalMilliseconds); }
public static IEnumerable <TValue> RandomValues <TKey, TValue>(this IDictionary <TKey, TValue> dict, ConcurrentRandom rand = null) { rand = rand ?? new ConcurrentRandom(); List <TValue> values = Enumerable.ToList(dict.Values); int size = dict.Count; while (true) { yield return(values[rand.Next(size)]); } }
public void GetRandomNumber_WhereLowAndHighAreEqual_LowHighValueReturned() { // Arrange double low = 100; double high = 100; var concurrentRandom = new ConcurrentRandom(); // Act double result = concurrentRandom.Uniform(low, high); // Assert result.Should().BeInRange(low, high); }
public void GetRandomNumber_ThatIsGreaterThan100AndLessThan1000_RandomNumberReturned() { // Arrange double low = 100; double high = 1000; var concurrentRandom = new ConcurrentRandom(); // Act double result = concurrentRandom.Uniform(low, high); // Assert result.Should().BeInRange(low, high); }
public void SetTextTest() { var profiler = new Profiler(new ProfilerOptions(ProfilerType.Text), nameof(SetTextTest)); Assert.Null(profiler.Text); for (var r = 0; r < 100; r++) { var text = ConcurrentRandom.NextString("abcdefghijklmnopqrstuvwxyz0123456789", 10); profiler.Set(text); Assert.Equal(text, profiler.Text); Assert.Equal(text, profiler.GetText()); } }
/// <summary> /// Randomize an actual delay with a value between <paramref name="minDelay"/> and <paramref name="maxDelay"/>. /// </summary> /// <param name="minDelay">The minimun amount of delay.</param> /// <param name="maxDelay">The maximum amount of delay.</param> /// <returns>The randomized delay.</returns> public static TimeSpan RandomizeDelay(TimeSpan minDelay, TimeSpan maxDelay) { if (minDelay <= TimeSpan.Zero && maxDelay <= TimeSpan.Zero) { return(TimeSpan.Zero); } if (minDelay >= maxDelay) { return(minDelay); } return(minDelay + TimeSpan.FromMilliseconds(ConcurrentRandom.NextDouble() * (maxDelay - minDelay).TotalMilliseconds)); }
/// <summary> /// Determines if an exception should be thrown. /// </summary> /// <param name="throwProbability">The probabilty that an exception will be thrown.</param> /// <returns>True if an exception should be thrown, false otherwise.</returns> public static bool ShouldCreateChaos(float throwProbability) { if (throwProbability <= 0f) { return(false); } if (throwProbability >= 1f) { return(true); } return(ConcurrentRandom.NextDouble() < throwProbability); }
public void TotalTest() { for (var max = 1; max < 100; max++) { var profiler = new Profiler(new ProfilerOptions(ProfilerType.TimeTotal, max, 1000, null), nameof(TotalTest)); var queue = new Queue <int>(); for (var i = 0; i < 1000; i++) { var r = ConcurrentRandom.NextInt32(); queue.Enqueue(r); profiler.AddTimeMeasurement(r, Math.Abs(ConcurrentRandom.NextInt32())); } var s = queue.Select(s => (Int64)s).Sum() / 10_000D; Assert.Equal(s, profiler.GetValue()); Assert.Equal(String.Format("{0:0,0.00}", s), profiler.GetText()); } }
public bool MoveNextUri() { if (this.firstUriIndex != -1) { if (!this.roundRobin && this.IsLastUri()) { return(false); } this.currentUriIndex = this.GetNextUriValue(); } else { int num = ConcurrentRandom.Next(0, this.uriAddresses.Count); int num1 = num; this.currentUriIndex = num; this.firstUriIndex = num1; } return(true); }
public void FormatterTest() { for (var round = 0; round < 100; round++) { var profiler = new Profiler(new ProfilerOptions(ProfilerType.SampleAverageTimeMs, 100, 100, "{0:0}"), nameof(FormatterTest)); Int64 totalCount = 0; var avgCount = 0; for (var i = 0; i < 100; i++) { var r = ConcurrentRandom.NextInt32(); var a = ConcurrentRandom.Next(1, 100); totalCount += r; avgCount += a; profiler.AddTimeMeasurement(r, a); } var avg = Math.Round(((double)totalCount / 10_000D) / avgCount); Assert.Equal(avg.ToString(), profiler.GetText()); } }
public Basket(int min, int max) { Weight = ConcurrentRandom.Generate(min, max); }
public override int GuessNumber() { return(ConcurrentRandom.Generate(_min, _max)); }
protected override IEnumerator <IteratorAsyncResult <GetRuntimeEntityDescriptionAsyncResult> .AsyncStep> GetAsyncSteps() { MessagingClientEtwProvider.TraceClient(() => { }); if (!this.executeOnce) { while (this.ShouldGetEntityInfo(MessagingExceptionHelper.Unwrap(base.LastAsyncStepException as CommunicationException))) { if (!RuntimeEntityDescriptionCache.TryGet(this.entityAddress, out this.runtimeEntityDescription)) { this.request = this.CreateOrGetRequestMessage(); GetRuntimeEntityDescriptionAsyncResult getRuntimeEntityDescriptionAsyncResult = this; IteratorAsyncResult <GetRuntimeEntityDescriptionAsyncResult> .BeginCall beginCall = (GetRuntimeEntityDescriptionAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.factory.Channel.BeginRequest(thisPtr.request, t, c, s); yield return(getRuntimeEntityDescriptionAsyncResult.CallAsync(beginCall, (GetRuntimeEntityDescriptionAsyncResult thisPtr, IAsyncResult a) => thisPtr.response = thisPtr.factory.Channel.EndRequest(a), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Continue)); if (base.LastAsyncStepException == null) { this.runtimeEntityDescription = GetRuntimeEntityDescriptionAsyncResult.BuildRuntimeEntityDescription(this.response); RuntimeEntityDescriptionCache.AddOrUpdate(this.entityAddress, this.runtimeEntityDescription); this.clientEntity.RuntimeEntityDescription = this.runtimeEntityDescription; } else { if (!base.LastAsyncStepException.IsWrappedExceptionTransient()) { yield return(base.CallAsyncSleep(Constants.GetRuntimeEntityDescriptionNonTransientSleepTimeout)); } else { yield return(base.CallAsyncSleep(TimeSpan.FromSeconds((double)(this.attempt % 60)) + TimeSpan.FromMilliseconds((double)ConcurrentRandom.Next(1, 1000)))); } GetRuntimeEntityDescriptionAsyncResult getRuntimeEntityDescriptionAsyncResult1 = this; getRuntimeEntityDescriptionAsyncResult1.attempt = getRuntimeEntityDescriptionAsyncResult1.attempt + 1; } } else { this.clientEntity.RuntimeEntityDescription = this.runtimeEntityDescription; } } } else { if (!RuntimeEntityDescriptionCache.TryGet(this.entityAddress, out this.runtimeEntityDescription)) { this.request = this.CreateOrGetRequestMessage(); GetRuntimeEntityDescriptionAsyncResult getRuntimeEntityDescriptionAsyncResult2 = this; IteratorAsyncResult <GetRuntimeEntityDescriptionAsyncResult> .BeginCall beginCall1 = (GetRuntimeEntityDescriptionAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.factory.Channel.BeginRequest(thisPtr.request, t, c, s); yield return(getRuntimeEntityDescriptionAsyncResult2.CallAsync(beginCall1, (GetRuntimeEntityDescriptionAsyncResult thisPtr, IAsyncResult a) => thisPtr.response = thisPtr.factory.Channel.EndRequest(a), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer)); this.runtimeEntityDescription = GetRuntimeEntityDescriptionAsyncResult.BuildRuntimeEntityDescription(this.response); RuntimeEntityDescriptionCache.AddOrUpdate(this.entityAddress, this.runtimeEntityDescription); } this.clientEntity.RuntimeEntityDescription = this.runtimeEntityDescription; } }