public void call_on_each_test() { var target1 = MockRepository.GenerateMock <ITypeTarget>(); var target2 = MockRepository.GenerateMock <ITypeTarget>(); var target3 = MockRepository.GenerateMock <ITypeTarget>(); var target4 = MockRepository.GenerateMock <ITypeTarget>(); var cache = new InstanceCache(); cache.Set(typeof(int), new SmartInstance <int>(), target1); cache.Set(typeof(int), new SmartInstance <int>(), new object()); cache.Set(typeof(int), new SmartInstance <int>(), new object()); cache.Set(typeof(bool), new SmartInstance <int>(), target2); cache.Set(typeof(bool), new SmartInstance <int>(), new object()); cache.Set(typeof(string), new SmartInstance <int>(), target3); cache.Set(typeof(string), new SmartInstance <int>(), new object()); cache.Set(typeof(string), new SmartInstance <int>(), new object()); cache.Set(typeof(string), new SmartInstance <int>(), target4); cache.Each <ITypeTarget>(x => x.Go()); target1.AssertWasCalled(x => x.Go()); target2.AssertWasCalled(x => x.Go()); target3.AssertWasCalled(x => x.Go()); target4.AssertWasCalled(x => x.Go()); }
/// <summary> /// Sets an instance for a binding. /// </summary> /// <param name="binding">The binding to set an instance for.</param> /// <param name="instance">The instance to set.</param> /// <param name="type">The type to set the instance for.</param> /// <param name="name">The name to set the instance for.</param> internal void SetInstance(IBinding binding, object instance, Type type, string name) { if (instance == null) { throw new InvalidOperationException($"Attempted to bind null to instance for binding of type {binding.BaseType}"); } else if (name != null) { if (!InstanceCache.IsCached(type, name)) { InstanceCache.Cache(instance, type, name); } else { throw new InvalidOperationException($"Binding for type {binding.BaseType} with name {binding.Name} attempts to override cached instance for {type}."); } } else { if (!InstanceCache.IsCached(type)) { InstanceCache.Cache(instance, type); } else { throw new InvalidOperationException($"Binding for type {binding.BaseType} attempts to override cached instance for {type}."); } } }
public void CannotConstructACacheWithNegativeEntries() { // ReSharper disable once NotAccessedVariable InstanceCache <string> x; Assert.Throws <ArgumentOutOfRangeException>(() => x = new InstanceCache <string>(-10, () => string.Empty)); }
internal object GetDestination(object source, Type destinationType) { object destination; InstanceCache.TryGetValue(new ContextCacheKey(source, destinationType), out destination); return(destination); }
public BalancerFactory( IServiceProvider serviceProvider, InstanceCache instanceCache) { _serviceProvider = serviceProvider; _instanceCache = instanceCache; }
public void call_on_each_test() { var target1 = MockRepository.GenerateMock<ITypeTarget>(); var target2 = MockRepository.GenerateMock<ITypeTarget>(); var target3 = MockRepository.GenerateMock<ITypeTarget>(); var target4 = MockRepository.GenerateMock<ITypeTarget>(); var cache = new InstanceCache(); cache.Set(typeof (int), new SmartInstance<int>(), target1); cache.Set(typeof (int), new SmartInstance<int>(), new object()); cache.Set(typeof (int), new SmartInstance<int>(), new object()); cache.Set(typeof (bool), new SmartInstance<int>(), target2); cache.Set(typeof (bool), new SmartInstance<int>(), new object()); cache.Set(typeof (string), new SmartInstance<int>(), target3); cache.Set(typeof (string), new SmartInstance<int>(), new object()); cache.Set(typeof (string), new SmartInstance<int>(), new object()); cache.Set(typeof (string), new SmartInstance<int>(), target4); cache.Each<ITypeTarget>(x => x.Go()); target1.AssertWasCalled(x => x.Go()); target2.AssertWasCalled(x => x.Go()); target3.AssertWasCalled(x => x.Go()); target4.AssertWasCalled(x => x.Go()); }
public void CacheLockNeverExpiresTest() { Assert.AreEqual(TimeSpan.FromMilliseconds(-1), CacheSettings.DefaultLockTimeout); var cache = new InstanceCache <string>(); var startTime = DateTime.Now; var value = cache.Get(CacheDuration, () => { var result = "Initial"; var thread = new Thread(new ThreadStart(() => { try { result = cache.Get(CacheDuration, () => { return("Hello"); }); } catch (ThreadAbortException) { Thread.ResetAbort(); } })); thread.Start(); thread.Join(TwoSeconds); thread.Abort(); return(result); }); var endTime = DateTime.Now; var diff = endTime.Subtract(startTime); Assert.AreEqual("Initial", value); Assert.IsTrue(diff.TotalSeconds >= 1.8 && diff.TotalSeconds < 3); }
private void Awake() { YouLose.gameObject.SetActive(false); InstanceCache.Flush(); gameRepository = InstanceCache.GetOrInstanciate <InMemoryGameRepository>(() => new InMemoryGameRepository()); resultRepository = InstanceCache.GetOrInstanciate <InMemoryResultRepository>(() => new InMemoryResultRepository()); scoreService = InstanceCache.GetOrInstanciate <LocalScoreService>(() => new LocalScoreService()); resultRepository.Clear(); gameRepository.Clear(); scoreService.Reset(); gamePresenter = InstanceCache.GetOrInstanciate <GamePresenter>( () => { resultGenerator = new ResultGenerator(4, new AdditionOperator(), new RandomNumberGenerator(5, 15)); return(new GamePresenter( this, new CreateGame(gameRepository, new FixedInitialNumber(), resultGenerator, resultRepository), new Guess(gameRepository, resultRepository, resultGenerator, scoreService), scoreService)); }); }
internal object GetDestination(object source, Type destinationType) { if (source == null) { return(null); } return(InstanceCache.GetOrDefault(new ContextCacheKey(source, destinationType))); }
protected override void Dispose(bool disposing) { InstanceCache.Remove(NativeInstance); if (OwnsNativeInstance) { Urho3D_HashMap_StringHash_Variant_destructor(NativeInstance); } }
protected override void Dispose(bool disposing) { InstanceCache.Remove(NativeInstance); if (OwnsNativeInstance) { Urho3D_StringVector_destructor(NativeInstance); } }
public InstancesQueryMiddleware( RequestDelegate next, IOptions <DiscoveryOptions> discoveryOptions, InstanceCache instanceRegistry) { _next = next; _instanceCache = instanceRegistry ?? throw new ArgumentNullException(nameof(instanceRegistry)); _options = discoveryOptions?.Value ?? throw new ArgumentNullException(nameof(discoveryOptions)); }
public TypeDescriptor(Type t, PropertyInfo propertyInfo, MemberInfo memberInfo) { this.EntityType = t; PropertyInfo = propertyInfo; MemberInfo = memberInfo; DbContextMemberInfo = propertyInfo.PropertyType.GetMember("DbContext")[0]; this.Init(); InstanceCache.TryAdd(t, this); }
public StaticDiscoveryClient( ILogger <StaticDiscoveryClient> logger, IOptionsMonitor <StaticDiscoveryOptions> options, InstanceCache instanceCache) { _logger = logger; _options = options; _instanceCache = instanceCache; }
public ZooPickerDiscoveryClient( ILogger <ZooPickerDiscoveryClient> logger, IOptionsMonitor <ZooPickerOptions> options, InstanceCache instanceCache) { _logger = logger; _options = options; _instanceCache = instanceCache; }
public override void Dispose() { if (Interlocked.Increment(ref disposed_) == 1) { InstanceCache.Remove(instance_); Urho3D_StringVector_destructor(instance_); } instance_ = IntPtr.Zero; }
internal override void OnDispose(bool disposing) { // In order to allow clean exit we first must release all cached instances because they hold references to // native objects and that prevents them being deallocated. If we failed to do that then Context destructor // would run before destroctors of other objects (subsystems, etc). Everything that inherits from // Urho3D.Object accesses Context on destruction and that would cause a crash. Instance = null; InstanceCache.Dispose(); }
public void GetCachedValueTest() { var cache = new InstanceCache <string>(); var firstValue = "Hello"; var value = cache.Get(CacheDuration, () => firstValue); value = cache.Get(CacheDuration, () => "World"); Assert.AreEqual("Hello", value); }
public T GetResource <T>(string name, bool sendEventOnFailure = true) where T : Resource { var typeHash = new StringHash(typeof(T).Name); var componentInstance = Urho3D__ResourceCache__GetResource_Urho3D__StringHash_Urho3D__String_const__bool_(NativeInstance, typeHash.Hash, name, sendEventOnFailure); return(InstanceCache.GetOrAdd(componentInstance, ptr => { Type type = typeof(T); return (T)Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { ptr, false }, null); })); }
public void GetValueTest() { var cache = new InstanceCache <string>(); var value = cache.Get(CacheDuration, () => { return("Hello"); }); Assert.AreEqual("Hello", value); }
public void ACacheWithASingleEntryShouldAlwaysReturnThatEntry() { var cache = new InstanceCache <string>(1, UniqueStringCreator); var firstInstance = cache.GetNext(); for (int i = 0; i < 100; i++) { Assert.AreEqual(firstInstance, cache.GetNext()); } }
public T GetComponent <T>(bool recursive = false) where T : Component { var componentInstance = Urho3D__Node__GetComponent_Urho3D__StringHash_bool__const(NativeInstance, StringHash.Calculate(typeof(T).Name), recursive); if (componentInstance == IntPtr.Zero) { return(default(T)); } return(InstanceCache.GetOrAdd(componentInstance, ptr => (T)Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { ptr, false }, null))); }
public T CreateComponent <T>(CreateMode mode = CreateMode.REPLICATED, uint id = 0) where T : Component { var componentInstance = Urho3D__Node__CreateComponent_Urho3D__StringHash_Urho3D__CreateMode_unsigned_int_(NativeInstance, StringHash.Calculate(typeof(T).Name), mode, id); if (componentInstance == IntPtr.Zero) { return(default(T)); } return(InstanceCache.GetOrAdd(componentInstance, ptr => (T)Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { ptr, false }, null))); }
public void Dispose() { SaveTimeouTimer.Dispose(); InstanceCache.ForEach (model => { DataBlockWrapperBuffer wb = model.ExtraData["PLAY_DATA"] as DataBlockWrapperBuffer; wb.Dispose(); model.Dispose(); }); //throw new NotImplementedException(); }
public override void Dispose() { if (Interlocked.Increment(ref DisposedCounter) == 1) { InstanceCache.Remove(NativeInstance); if (OwnsNativeInstance) { Urho3D_StringVector_destructor(NativeInstance); } } NativeInstance = IntPtr.Zero; }
public void ACacheWithThreeeEntriesShouldAlwaysReturnThreeDistinctValues() { var cache = new InstanceCache <string>(3, UniqueStringCreator); var list = new List <string>(); for (int i = 0; i < 100; i++) { list.Add(cache.GetNext()); } int countOfDistinctEntries = list.Distinct().Count(); Assert.AreEqual(countOfDistinctEntries, 3); }
private CharacterViewModel CreateViewModel(CharacterReference reference) { XDocument scanDocument = Core.LoadPlayDataXDocument(); CharacterFile cf = CharacterFile.Load(reference.CharBytes); CharacterViewModel vm = new CharacterViewModel(cf, reference); DataBlockWrapperBuffer playData = new DataBlockWrapperBuffer(reference.PlayBytes, scanDocument); vm.ExtraData.Add("PLAY_SEAT", reference.Seat); vm.ExtraData.Add("PLAY_DATA", playData); vm.SaveCommand = new RelayCommand(() => SaveViewModel(vm), () => SaveViewModelCanExecute(vm)); vm.ReloadCommand = new RelayCommand(() => ReloadViewModel(vm)); InstanceCache.Add(vm); return(vm); }
public void Dispose() { if (Message != null) { if (Message.ReuseId != ReuseId) { throw new InvalidOperationException("Double free detected for this message"); } Message.ReuseId++; Message.Reset(); lock (InstanceCache) { if (InstanceCache.TryGetValue(Message.GetType(), out var queue)) { queue.Enqueue(Message); } } } }
public void ClearCacheTest() { // set up cache with an initial value var cache = new InstanceCache <string>(); var cachedValue = "Initial value"; // get value from cache and check it matches initial var value = cache.Get(CacheDuration, () => cachedValue); Assert.AreEqual("Initial value", value); // clear the cache cache.Clear(); // change the cached value cachedValue = "Changed value"; // check that it returns the changed value value = cache.Get(CacheDuration, () => cachedValue); Assert.AreEqual("Changed value", value); }
public void TestCache() { var cache = new InstanceCache(); cache.Clear(); var summary = new HtmlSummary(HttpStatusCode.OK, "http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4", RawHtml, "text/html"); cache.Set("first", summary); cache.Set("second", summary); var first = cache.Get<HtmlSummary>("first"); var second = cache.Get<HtmlSummary>("second"); first.Should().NotBeNull(); second.Should().NotBeNull(); first.CreatedAt.Should().Be(second.CreatedAt); cache.Unset("first"); var none = cache.Get<HtmlSummary>("first"); none.Should().BeNull(); }
/// <summary> /// Gets the field values for the specified field on the specified form. /// </summary> /// <param name="formName">The name of the Contour form.</param> /// <param name="fieldCaption">The caption for the field.</param> /// <returns> /// The field values and labels. /// </returns> public static List<ValueLabelStrings> GetFieldValues(string formName, string fieldCaption) { // Validation. if (string.IsNullOrWhiteSpace(formName) || string.IsNullOrWhiteSpace(fieldCaption)) { return null; } // Get cache of values for specified form/field. var cache = null as InstanceCache<List<ValueLabelStrings>>; lock (FieldValuesLock) { var key = new KeyValueStrings(formName, fieldCaption); if (!FieldValues.TryGetValue(key, out cache)) { cache = new InstanceCache<List<ValueLabelStrings>>(); FieldValues[key] = cache; } } // Get values from cache. return cache.Get(TimeSpan.FromHours(3), () => { var results = new List<ValueLabelStrings>(); using (var formStorage = new FormStorage()) { var form = formStorage.GetForm(formName); using (var recordService = new RecordService(form)) { recordService.Open(); foreach (var field in recordService.Form.AllFields) { if (fieldCaption.InvariantEquals(field.Caption)) { field.PreValueSource.Type.LoadSettings(field.PreValueSource); foreach (var item in field.PreValueSource.Type.GetPreValues(field)) { results.Add(new ValueLabelStrings(item.Id.ToString(), item.Value)); } } } } } return results; }); }
public void CacheLockExpiresOnTimeTest() { var cache = new InstanceCache <string>(TwoSeconds); var startTime = DateTime.Now; var value = cache.Get(CacheDuration, () => { var result = default(string); var thread = new Thread(new ThreadStart(() => { result = cache.Get(CacheDuration, () => { return("Hello"); }); })); thread.Start(); thread.Join(); return(result); }); var endTime = DateTime.Now; var diff = endTime.Subtract(startTime); Assert.IsNull(value); Assert.IsTrue(diff.TotalSeconds >= 1.8 && diff.TotalSeconds < 3); }
public void ClearInstances() { PageCache.Clear(); InstanceCache.Clear(); }
public InstanceCacheTester() { cache = new InstanceCache(); }
public void Setup() { cache = new InstanceCache(); }