예제 #1
0
        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());
        }
예제 #2
0
 /// <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}.");
         }
     }
 }
예제 #3
0
        public void CannotConstructACacheWithNegativeEntries()
        {
            // ReSharper disable once NotAccessedVariable
            InstanceCache <string> x;

            Assert.Throws <ArgumentOutOfRangeException>(() => x = new InstanceCache <string>(-10, () => string.Empty));
        }
예제 #4
0
        internal object GetDestination(object source, Type destinationType)
        {
            object destination;

            InstanceCache.TryGetValue(new ContextCacheKey(source, destinationType), out destination);
            return(destination);
        }
예제 #5
0
 public BalancerFactory(
     IServiceProvider serviceProvider,
     InstanceCache instanceCache)
 {
     _serviceProvider = serviceProvider;
     _instanceCache   = instanceCache;
 }
예제 #6
0
        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());
        }
예제 #7
0
        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);
        }
예제 #8
0
    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));
        });
    }
예제 #9
0
 internal object GetDestination(object source, Type destinationType)
 {
     if (source == null)
     {
         return(null);
     }
     return(InstanceCache.GetOrDefault(new ContextCacheKey(source, destinationType)));
 }
예제 #10
0
 protected override void Dispose(bool disposing)
 {
     InstanceCache.Remove(NativeInstance);
     if (OwnsNativeInstance)
     {
         Urho3D_HashMap_StringHash_Variant_destructor(NativeInstance);
     }
 }
예제 #11
0
 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));
 }
예제 #13
0
 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;
 }
예제 #15
0
 public ZooPickerDiscoveryClient(
     ILogger <ZooPickerDiscoveryClient> logger,
     IOptionsMonitor <ZooPickerOptions> options,
     InstanceCache instanceCache)
 {
     _logger        = logger;
     _options       = options;
     _instanceCache = instanceCache;
 }
예제 #16
0
파일: Vector.cs 프로젝트: elix22/Urho3DNet
 public override void Dispose()
 {
     if (Interlocked.Increment(ref disposed_) == 1)
     {
         InstanceCache.Remove(instance_);
         Urho3D_StringVector_destructor(instance_);
     }
     instance_ = IntPtr.Zero;
 }
예제 #17
0
 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();
 }
예제 #18
0
        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);
        }
예제 #19
0
        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);
            }));
        }
예제 #20
0
        public void GetValueTest()
        {
            var cache = new InstanceCache <string>();
            var value = cache.Get(CacheDuration, () =>
            {
                return("Hello");
            });

            Assert.AreEqual("Hello", value);
        }
예제 #21
0
        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());
            }
        }
예제 #22
0
        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)));
        }
예제 #23
0
        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();
 }
예제 #25
0
 public override void Dispose()
 {
     if (Interlocked.Increment(ref DisposedCounter) == 1)
     {
         InstanceCache.Remove(NativeInstance);
         if (OwnsNativeInstance)
         {
             Urho3D_StringVector_destructor(NativeInstance);
         }
     }
     NativeInstance = IntPtr.Zero;
 }
예제 #26
0
        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);
        }
예제 #28
0
            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);
                        }
                    }
                }
            }
예제 #29
0
        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);
        }
예제 #30
0
        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;
			});

		}
예제 #32
0
        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);
        }
예제 #33
0
 public void ClearInstances()
 {
     PageCache.Clear();
     InstanceCache.Clear();
 }
		public InstanceCacheTester() {
			cache = new InstanceCache();
		}
 public void Setup()
 {
     cache = new InstanceCache();
 }