public void AllMetrics_SampleData_Recorded() { const int NumberOfItems = 42; var errors = new KeyValuePair <string, Exception>[] { new KeyValuePair <string, Exception>("1", new Exception()), new KeyValuePair <string, Exception>("2", new ArgumentException()), new KeyValuePair <string, Exception>("3", new KeyNotFoundException()) }; var statistics = new InMemoryTransferStatistics(ErrorDetailsProviderMock.Instance); statistics.Start(); for (var index = 0; index < NumberOfItems; ++index) { statistics.AddTransferred(); } foreach (var error in errors) { statistics.AddError(error.Key, error.Value); } statistics.Stop(); var result = statistics.GetSnapshot(); Assert.IsNotNull(result, TestResources.NullStatisticsSnapshot); Assert.AreNotEqual(TimeSpan.Zero, result.ElapsedTime, TestResources.StatisticsElapsedTimeIsEmpty); Assert.AreEqual(NumberOfItems, result.Transferred, TestResources.StatisticsInvalidTransferredCount); Assert.AreEqual(errors.Length, result.Failed, TestResources.StatisticsInvalidFailedCount); CollectionAssert.AreEquivalent(errors.ToDictionary(e => e.Key, e => ErrorDetailsProviderMock.Instance.Get(e.Value)), result.GetErrors().ToArray(), TestResources.StatisticsInvalidErrors); }
private void AssertTableContents(SlimHashTable <string, string> table) { var dic = table.ToDictionary(x => x.Key, x => x.Value); var keySet = new HashSet <string>(table.Keys); var valueSet = new HashSet <string>(table.Values); var kvp = new KeyValuePair <string, string> [table.Count]; table.CopyTo(kvp, 0); var dic2 = kvp.ToDictionary(x => x.Key, x => x.Value); if (table.Count >= 1) { Assert.IsTrue(table.Contains("foo")); Assert.IsTrue(dic.ContainsKey("foo")); Assert.IsTrue(dic2.ContainsKey("foo")); Assert.IsTrue(keySet.Contains("foo")); Assert.IsTrue(valueSet.Contains("foo")); } for (var i = 0; i < table.Count - 1; i++) { var key = "foo" + (table.Count - 2 - i); Assert.IsTrue(table.Contains(key)); Assert.IsTrue(dic.ContainsKey(key)); Assert.IsTrue(dic2.ContainsKey(key)); Assert.IsTrue(keySet.Contains(key)); Assert.IsTrue(valueSet.Contains(key)); } }
public void MatchesPositionalAndNamedArguments() { // Given TestExecutionContext context = new TestExecutionContext(); KeyValuePair <string, string>[] args = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(null, "1"), new KeyValuePair <string, string>("C", "3"), new KeyValuePair <string, string>("B", "2") }; // When ConvertingDictionary dictionary = args.ToDictionary(context, "A", "B", "C"); // Then dictionary.ShouldBe( new KeyValuePair <string, object>[] { new KeyValuePair <string, object>("A", "1"), new KeyValuePair <string, object>("B", "2"), new KeyValuePair <string, object>("C", "3") }, true); }
void GivenADictionaryWithTokensInTheValues() { var environmentData = new Dictionary <string, string> { { "key1", "value2" }, { "key8", "value3" }, }; var items = new KeyValuePair <string, string> [Expected.Count]; Expected.CopyTo(items, 0); var expectedData = items.ToDictionary(x => x.Key, x => x.Value); foreach (var item in environmentData) { Environment.SetEnvironmentVariable(item.Key, item.Value); } foreach (var item in expectedData.ToArray()) { expectedData[item.Key] = item.Value.Replace("value1", "value2", StringComparison.Ordinal); } expectedData["key8"] = environmentData["key8"]; Expected = expectedData; }
public void AllMetrics_SampleData_Recorded() { const int NumberOfItems = 42; var errors = new KeyValuePair<string, Exception>[] { new KeyValuePair<string, Exception>("1", new Exception()), new KeyValuePair<string, Exception>("2", new ArgumentException()), new KeyValuePair<string, Exception>("3", new KeyNotFoundException()) }; var statistics = new InMemoryTransferStatistics(ErrorDetailsProviderMock.Instance); statistics.Start(); for (var index = 0; index < NumberOfItems; ++index) statistics.AddTransferred(); foreach (var error in errors) statistics.AddError(error.Key, error.Value); statistics.Stop(); var result = statistics.GetSnapshot(); Assert.IsNotNull(result, TestResources.NullStatisticsSnapshot); Assert.AreNotEqual(TimeSpan.Zero, result.ElapsedTime, TestResources.StatisticsElapsedTimeIsEmpty); Assert.AreEqual(NumberOfItems, result.Transferred, TestResources.StatisticsInvalidTransferredCount); Assert.AreEqual(errors.Length, result.Failed, TestResources.StatisticsInvalidFailedCount); CollectionAssert.AreEquivalent(errors.ToDictionary(e => e.Key, e => ErrorDetailsProviderMock.Instance.Get(e.Value)), result.GetErrors().ToArray(), TestResources.StatisticsInvalidErrors); }
private void AssertIndexes(KeyValuePair<int, string>[] data, int[] indexes) { var dic = data.ToDictionary(k => k.Key); Assert.AreEqual(indexes.Length, data.Length, "Found wrong amount"); for (int i = 0; i < data.Length; ++i) { Assert.AreEqual(indexes[i], dic[indexes[i]].Key, "Wrong index found at position " + i); } }
public void Should_Dispatch_Hosts_Correctly() { var mapping = new KeyValuePair <string, object> [4]; mapping[0] = GetMapForDispatchTest("http://foo.org/", "foo.org"); mapping[1] = GetMapForDispatchTest("http://subdomain.foo.org/", "subdomain.foo.org"); mapping[2] = GetMapForDispatchTest("http://bar.org/", "bar.org"); mapping[3] = GetMapForDispatchTest("/", "default.org"); var mappingDictionary = mapping.ToDictionary(pair => pair.Key, pair => pair.Value); var map = new UrlMap(mappingDictionary); var res = new MockRequest(map).Get("/"); Assert.AreEqual(200, res.Status); Assert.AreEqual("default.org", res["X-Position"]); res = new MockRequest(map).Get("/", new Dictionary <string, object> { { "HTTP_HOST", "bar.org" } }); Assert.AreEqual(200, res.Status); Assert.AreEqual("bar.org", res["X-Position"]); res = new MockRequest(map).Get("/", new Dictionary <string, object> { { "HTTP_HOST", "foo.org" } }); Assert.AreEqual(200, res.Status); Assert.AreEqual("foo.org", res["X-Position"]); res = new MockRequest(map).Get("/", new Dictionary <string, object> { { "HTTP_HOST", "subdomain.foo.org" }, { "SERVER_NAME", "foo.org" } }); Assert.AreEqual(200, res.Status); Assert.AreEqual("subdomain.foo.org", res["X-Position"]); res = new MockRequest(map).Get("http://foo.org/"); Assert.AreEqual(200, res.Status); Assert.AreEqual("foo.org", res["X-Position"]); res = new MockRequest(map).Get("/", new Dictionary <string, object> { { "HTTP_HOST", "example.org" } }); Assert.AreEqual(200, res.Status); Assert.AreEqual("default.org", res["X-Position"]); res = new MockRequest(map).Get("/", new Dictionary <string, object> { { "HTTP_HOST", "example.org:9292" }, { "SERVER_PORT", "9292" } }); Assert.AreEqual(200, res.Status); Assert.AreEqual("default.org", res["X-Position"]); }
public void ThrowsForPositionalAfterNamedArguments() { // Given KeyValuePair <string, string>[] args = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(null, "1"), new KeyValuePair <string, string>("C", "3"), new KeyValuePair <string, string>(null, "2") }; // When, Then Should.Throw <ShortcodeArgumentException>(() => args.ToDictionary("A", "B", "C")); }
public JsonObject Copy() { if (_properties.Count == 0) { return(new JsonObject()); } var copy = new KeyValuePair <string, JsonProperty> [_properties.Count]; _properties.CopyTo(copy, 0); var properties = copy.ToDictionary(e => e.Key, e => e.Value); return(new JsonObject(properties)); }
public void ThrowsForDuplicateNamedArguments() { // Given TestExecutionContext context = new TestExecutionContext(); KeyValuePair <string, string>[] args = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(null, "1"), new KeyValuePair <string, string>("C", "3"), new KeyValuePair <string, string>("A", "2") }; // When, Then Should.Throw <ShortcodeArgumentException>(() => args.ToDictionary(context, "A", "B", "C")); }
public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); var controller = filterContext.Controller as Controller; if (controller != null) { var modelState = controller.ViewData.ModelState; if (modelState != null) { var dictionary = new KeyValuePair <string, ModelStateEntry> [modelState.Count]; modelState.CopyTo(dictionary, 0); var listError = dictionary.ToDictionary(m => m.Key, m => m.Value.Errors.Select(s => s.ErrorMessage).FirstOrDefault(s => s != null)); controller.TempData["ModelState"] = JsonConvert.SerializeObject(listError); } } }
public void Should_Not_Squeeze_Slashes() { var mapping = new KeyValuePair <string, object> [2]; mapping[0] = GetMapForRootRouteTest("/", "root"); mapping[1] = GetMapForRootRouteTest("/foo", "foo"); var mappingDictionary = mapping.ToDictionary(pair => pair.Key, pair => pair.Value); var map = new UrlMap(mappingDictionary); var mock = new MockRequest(map); var res = mock.Get("/http://example.org/bar"); Assert.AreEqual(200, res.Status); Assert.AreEqual("root", res["X-Position"]); Assert.AreEqual("/http://example.org/bar", res["X-PathInfo"]); Assert.AreEqual(string.Empty, res["X-ScriptName"]); }
public void MatchesPositionalAndNamedArguments() { // Given KeyValuePair <string, string>[] args = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(null, "1"), new KeyValuePair <string, string>("C", "3"), new KeyValuePair <string, string>("B", "2") }; // When IMetadataDictionary dictionary = args.ToDictionary("A", "B", "C"); // Then dictionary.ShouldBe( new KeyValuePair <string, object>[] { new KeyValuePair <string, object>("A", "1"), new KeyValuePair <string, object>("B", "2"), new KeyValuePair <string, object>("C", "3") }, true); }
public IDictionary<string, string> ToDictionary(KeyValuePair<string, string>[] v) { return v.ToDictionary(); }
/// <summary> /// Run benchmark. /// </summary> /// <param name="log">Logger</param> /// <returns>Dashboard</returns> public Dictionary <string, int> Run(Action <string> log) { var _log = log != null; var _stopwatch = new Stopwatch(); var _activation = this.m_Dictionary[Benchmark.None]; var _action = null as Action; if (_log) { log("Benchmark"); } var _list = new List <KeyValuePair <string, long> >(); var _array = this.m_Dictionary.ToArray(); var _buffer = new KeyValuePair <string, Action> [_array.Length]; if (_log) { log(" Activation : Ticks"); } for (var _loop = 0; _loop < _array.Length; _loop++) { var _name = _array[_loop].Key; var _activate = _array[_loop].Value; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); _stopwatch.Restart(); _action = _activate(); _stopwatch.Stop(); _buffer[_loop] = new KeyValuePair <string, Action>(_name, _action); if (_log) { log($" { _name } = { Benchmark.Round(_stopwatch.ElapsedTicks) }"); } } if (_log) { log(" Warmup : Ticks"); } foreach (var _item in _buffer) { _action = _item.Value; RuntimeHelpers.PrepareDelegate(_action); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); _stopwatch.Restart(); _action(); _stopwatch.Stop(); if (_log) { log($" { _item.Key } = { Benchmark.Round(_stopwatch.ElapsedTicks) }"); } } if (_log) { log(" Loop : iteration / second"); } _action = _activation(); var _sample = 100; _action(); while (true) { var _index = 0; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); _stopwatch.Restart(); while (_index++ < _sample) { _action(); } _stopwatch.Stop(); if (_stopwatch.ElapsedMilliseconds < 80) { _sample = _sample * 10; } else { break; } } var _sampling = _buffer.ToDictionary(_Item => _Item.Key, _Item => new List <long>()); for (var _loop = 0; _loop < 3; _loop++) { foreach (var _item in _buffer) { var _index = 0; _action = _item.Value; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); _stopwatch.Restart(); while (_index++ < 10) { _action(); } _stopwatch.Stop(); _sampling[_item.Key].Add(_stopwatch.ElapsedTicks); } } var _balancing = _sampling.ToDictionary(_Item => _Item.Key, _Item => Convert.ToInt64(_Item.Value.Average())); var _authority = _balancing[Benchmark.None]; _balancing = _balancing.ToDictionary(_Item => _Item.Key, _Item => Convert.ToInt64(_sample * _authority / _Item.Value)); var _random = new Random(); for (var _loop = 0; _loop < 6; _loop++) { if (_log) { log($" [{ _loop + 1 }]"); } var _randomly = _buffer.ToArray(); for (var _index = _randomly.Length - 1; _index > 0; --_index) { var _position = _random.Next(_index + 1); var _item = _randomly[_index]; _randomly[_index] = _randomly[_position]; _randomly[_position] = _item; } foreach (var _item in _randomly) { var _index = 0L; var _iteration = _balancing[_item.Key]; _action = _item.Value; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); _stopwatch.Restart(); while (_index++ < _iteration) { _action(); } _stopwatch.Stop(); if (_log) { log($" { _item.Key } = { Benchmark.Round(Convert.ToInt64(1000 * _iteration / _stopwatch.ElapsedMilliseconds)) }"); } _list.Add(new KeyValuePair <string, long>(_item.Key, Convert.ToInt64(_sample * _stopwatch.ElapsedTicks / _iteration))); } } var _dashboard = _list.GroupBy(_Measure => _Measure.Key, _Measure => _Measure.Value).Select(_Measure => new { Name = _Measure.Key, Duration = Benchmark.Average(_Measure) }).ToArray(); var _native = _dashboard.Single(_Measure => _Measure.Name == Benchmark.None).Duration; var _dictionary = _dashboard.ToDictionary(_Measure => _Measure.Name, _Measure => Convert.ToInt64((_Measure.Duration * 100) / _native)); var _display = _dictionary.OrderBy(_Measure => _Measure.Value * (_Measure.Key == Benchmark.None ? 0 : 1)).ThenBy(_Measure => _Measure.Key).Select(_Measure => new { Name = _Measure.Key, Duration = Benchmark.Round(_Measure.Value) }).ToArray(); if (_log) { var _max = _dictionary.Select(_Measure => _Measure.Key.Length).Max(); var _length = _display.Select(_Measure => _Measure.Duration.Length).Max(); var _size = _display.Count().ToString().Length; var _line = new string('=', _max + _length + 8 + _size); var _index = -1; Console.WriteLine(); Console.WriteLine($" { _line }"); foreach (var _measure in _display) { Console.WriteLine($" { (++_index == 0 ? new string(' ', _size + 2) : string.Concat("[", _index, "]")) } { _measure.Name.PadLeft(_max, ' ') } : { _measure.Duration.PadLeft(_length) } %"); } Console.WriteLine($" { _line }"); } return(_display.ToDictionary(_Measure => _Measure.Name, _Measure => int.Parse(Regex.Replace(_Measure.Duration, "[^0-9]", "")))); }
public void InjectedCache() { TimeSpan cacheLifeTime = TimeSpan.FromMinutes(5); MemoryCachingService service = new MemoryCachingService(cacheLifeTime); Foobar cachable = GetCachableObject(); string cachableKey = this.cachableKey; service.Cache(cachableKey, cachable); ICachedObject <Foobar> existsRetrievedWrapper = service.Retrieve <Foobar>(cachableKey); KeyValuePair <string, ICachedObjectBasic>[] cache = new KeyValuePair <string, ICachedObjectBasic> [1]; service.CopyTo(cache, 0); Assert.NotNull(cache); Assert.NotEmpty(cache); Assert.Single(cache); Assert.Equal(existsRetrievedWrapper.Value, cache[0].Value.UntypedValue); Assert.Equal(cachableKey, cache[0].Key); MemoryCachingService service2 = new MemoryCachingService(cacheLifeTime, cache.ToDictionary(x => x.Key, y => y.Value)); ICachedObject <Foobar> existsRetrievedWrapper2 = service2.Retrieve <Foobar>(cachableKey); Assert.Equal(existsRetrievedWrapper.Value, existsRetrievedWrapper2.Value); }