public void AddRemoveTest()
        {
            var cache = new WeakCache <string, TestClass>(false, value => value.Text);

            TestClass item = new TestClass("1");

            cache.Add(item);
            Assert.AreEqual(1, cache.Count);

            item = new TestClass("2");
            cache.Add(item);
            Assert.AreEqual(2, cache.Count);
            Assert.AreEqual(item, cache[item.Text, false]);

            ICache <string, TestClass> icache = cache;

            Assert.AreEqual(item, icache[item.Text, false]);
            Assert.AreEqual(null, icache["3", false]);

            cache.Remove(item);
            Assert.AreEqual(1, cache.Count);

            cache.Clear();
            Assert.AreEqual(0, cache.Count);
        }
        public void IEnumerableTest()
        {
            var cache = new WeakCache <string, TestClass>(false, value => value.Text);

            for (int i = 0; i < 100; i++)
            {
                cache.Add(new TestClass("item " + i));
            }

            Assert.IsTrue(cache.Count >= 0);
            Assert.IsTrue(cache.Count <= 100);

            int itemsCount = 0;

            foreach (TestClass testClass in cache)
            {
                Assert.IsTrue(testClass == null || testClass.Text.StartsWith("item"), "Line 182");
                itemsCount++;
            }
            Assert.IsTrue(itemsCount >= 0);
            Assert.IsTrue(itemsCount <= 100);

            TestHelper.CollectGarbage(true);

            itemsCount = 0;
            foreach (TestClass testClass in cache)
            {
                Assert.IsTrue(testClass == null || testClass.Text.StartsWith("item"), "Line 196");
                itemsCount++;
            }
            Assert.IsTrue(itemsCount >= 0);
            Assert.IsTrue(itemsCount <= 100);
        }
示例#3
0
        public void WeakCache_Get_works()
        {
            WeakCache <string> wc = new WeakCache <string>();
            var value             = wc.Get("test", () => "12345");

            Assert.AreEqual("12345", value);
        }
        public BearerAuthenticationProvider(WeakCache cache)
        {
            ThrowNullArguments(() => cache);

            _cache = cache;

            //make sure a logon hasnt been invalidated!
            OnValidateIdentity = context => Task.Run(() =>
            {
                var token = context.Request.Headers.Get("Authorization").TrimStart("Bearer").Trim();

                //in future, a realtime event will notify the bearer-provider of changes to a logon, so we dont need to keep quering the database
                var logon = _cache.GetOrRefresh <UserLogon>(token);

                //Note that if "logon"' is null, it means that it was not found either in the cache or in the db - but the fact that this method was called
                //means that the token was verified by the authorization server: this is an anomaly, as the source of the token is in question. What we do
                //is reject this request.
                if (logon?.Invalidated ?? true)
                {
                    context.Rejected();
                }

                //implement traditional session timeout after "WebConstants.Misc_SessionTimeoutMinutes" minutes
                else if ((DateTime.Now - logon.ModifiedOn) >= TimeSpan.FromMinutes(WebConstants.Misc_SessionTimeoutMinutes))
                {
                    logon.ModifiedOn = DateTime.Now;
                    context.Rejected();
                }
                else
                {
                    context.OwinContext.Environment[WebConstants.Misc_UserLogonOwinContextKey] = logon;
                    context.Validated();
                }
            });
        }
示例#5
0
        public void WeakCache_Set_works()
        {
            WeakCache <string> wc = new WeakCache <string>();

            wc.Set("test", "123");
            Assert.AreEqual("123", wc.Get("test", null));
        }
示例#6
0
 internal Factory(WeakCache <K, P, V> outerInstance, K key, P parameter, Object subKey, ConcurrentMap <Object, Supplier <V> > valuesMap)
 {
     this.OuterInstance = outerInstance;
     this.Key           = key;
     this.Parameter     = parameter;
     this.SubKey        = subKey;
     this.ValuesMap     = valuesMap;
 }
        public MessengerManager(LibMessenger pluginInstance)
        {
            _pluginInstance = pluginInstance;
            _categoryCache = new WeakCache<int, Category>(LoadCategory);

            CoreManager.ServerCore.EventManager.StrongBind<CategoryHabboEventArgs>(_pluginInstance.Id + ":habbo_category_request:before", LoadHabboCategoriesFromDatabase);
            CoreManager.ServerCore.EventManager.StrongBind<CategoryBefriendablesEventArgs>(_pluginInstance.Id + ":category_friendship_request:before", LoadCategoryHabboBefriendablesFromDatabase);
        }
示例#8
0
        public void TryGetValue_ValueDoesNotExist_ReturnsSuccessFalse()
        {
            var cache = new WeakCache <string, string>();

            var(success, _) = cache.TryGetValue("Key");

            Assert.That(success, Is.False);
        }
示例#9
0
        public void TryGetValue_ValueDoesNotExist_ReturnsValueDefault()
        {
            var cache = new WeakCache <string, string>();

            var(_, value) = cache.TryGetValue("Key");

            Assert.That(value, Is.Null);
        }
示例#10
0
        private void AddToCacheInDifferentMethodToAvoidDebugVariableLifetimeProblems([NotNull] WeakCache <string, object> cache)
        {
            cache.GetOrAddValue("Key", key => new object());

            var(success, _) = cache.TryGetValue("Key");

            Assert.That(success, Is.True);
        }
示例#11
0
 private void InitializeMapping()
 {
     if (_mappingInfoContainer == null)
     {
         _mappingInfoContainer = TypeMapping.GetMappingInfo(_mappingOptionSet.GetTypeMappingOptions(typeof(T)));
         _dbWorker             = new DataBaseWorker(_connectionString, this);
         _cache = new WeakCache(_mappingInfoContainer.LoadBehavior == LoadBehavior.OnFirstAccessFullLoad);
     }
 }
示例#12
0
 public SqlPreparationAction(string id, string schemaPath, string connectionString, bool updateOnlyIfNewValueIsNotNull = false)
     : base(id)
 {
     _connectionString = connectionString;
     _schemaPath       = schemaPath;
     _values           = new List <object>();
     _pkCache          = new WeakCache <string[]>();
     _updateOnlyIfNewValueIsNotNull = updateOnlyIfNewValueIsNotNull;
 }
示例#13
0
        public RoomDistributor()
        {
            _idCache         = new WeakCache <int, Room>(ConstructRoom);
            _overrideLoaders = new Dictionary <int, Func <Habbo, Room> >();

            _lastFreeRoomId = -1;
            _roomIdSync     = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

            _modelTypeLookup = new Dictionary <string, Type>();
        }
示例#14
0
        public RoomDistributor()
        {
            _idCache = new WeakCache<int, Room>(ConstructRoom);
            _overrideLoaders = new Dictionary<int, Func<Habbo, Room>>();

            _lastFreeRoomId = -1;
            _roomIdSync = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

            _modelTypeLookup = new Dictionary<string, Type>();
        }
示例#15
0
        public void TryGetValue_ValueExists_ReturnsSuccessTrue()
        {
            var cache = new WeakCache <string, string>();

            cache.GetOrAddValue("Key", key => "Value");

            var(success, _) = cache.TryGetValue("Key");

            Assert.That(success, Is.True);
        }
示例#16
0
        public void Item_should_be_removed_on_demand()
        {
            ICache cache = new WeakCache();

            cache[0] = 0;
            Assert.That(cache[0], Is.Not.Null);

            cache.Remove(0);
            Assert.That(cache[0], Is.Null);
        }
示例#17
0
        public void TryGetValue_ValueExists_ReturnsValue()
        {
            var cache = new WeakCache <string, string>();

            cache.GetOrAddValue("Key", key => "Value");

            var(_, value) = cache.TryGetValue("Key");

            Assert.That(value, Is.EqualTo("Value"));
        }
示例#18
0
 public ConcurrentCacheTest(
     WeakCache <object, object> cache,
     Random rng,
     int rangeStart,
     int rangeEnd)
 {
     this.cache      = cache;
     this.rng        = rng;
     this.rangeStart = rangeStart;
     this.rangeEnd   = rangeEnd;
 }
示例#19
0
        public void GetAndDoNotPreserveAccrossGC()
        {
            int count = 0;
            var cache = new WeakCache <int, IntHolder>(10, key => new IntHolder()
            {
                Int = count++
            });
            var v1Value = GetValue(cache);

            GC.Collect();
            Assert.NotEqual(v1Value, cache.Get(1).Int);
        }
示例#20
0
        public void GetAndPreserveAccrossGC()
        {
            int count = 0;
            var cache = new WeakCache <int, IntHolder>(10, key => new IntHolder()
            {
                Int = count++
            });
            var v1 = cache.Get(1);

            GC.Collect();
            Assert.Equal(v1.Int, cache.Get(1).Int);
        }
示例#21
0
 protected override void OnFinally()
 {
     base.OnFinally();
     if (_db.IsValueCreated)
     {
         _db.Value.Close();
     }
     _schema  = null;
     _db      = null;
     _values  = null;
     _pkCache = null;
 }
示例#22
0
        public void Least_recently_used_item_should_be_removed()
        {
            WeakCache cache = new WeakCache();

            for (int i = 0; i < 1000000; i++)
            {
                cache[i] = i;
            }
            GC.Collect();
            object o = cache[0];

            Assert.That(cache.Size, Is.EqualTo(999999));
        }
示例#23
0
        public void Demonstrate_that_copies_are_equals()
        {
            ICache cache = new WeakCache();

            cache = new SharedCache(cache);

            for (int i = 0; i < 100000; i++)
            {
                cache[i] = i;
                object value = cache[i];
                Assert.That(value, Is.Null | Is.EqualTo(i));
            }
        }
        public void ConstructorsTest()
        {
            var cache = new WeakCache <string, TestClass>(
                false, value => value.Text);

            Assert.IsNotNull(cache.KeyExtractor);

            var item = new TestClass("100");

            cache.Add(item);

            Assert.AreEqual(1, cache.Count);
        }
示例#25
0
 public void TestCache() {
    WeakCache cache = new WeakCache();
    Dictionary map = new HashMap();
    for(int i = 0; i < LOAD_COUNT; i++) {
       String key = String.valueOf(i);
       cache.cache(key, key);
       map.put(key, key);
    }
    for(int i = 0; i < LOAD_COUNT; i++) {
       String key = String.valueOf(i);
       AssertEquals(cache.fetch(key), key);
       AssertEquals(map.get(key), cache.fetch(key));
    }
 }
示例#26
0
        public void TryGetValue_ValueHasBeenCleared_ReturnsSuccessFalse()
        {
            var cache = new WeakCache <string, object>();

            AddToCacheInDifferentMethodToAvoidDebugVariableLifetimeProblems(cache);

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            var(success, _) = cache.TryGetValue("Key");

            Assert.That(success, Is.False);
        }
示例#27
0
        public void Cache_should_be_clear_on_demand()
        {
            ICache cache = new WeakCache();

            for (int i = 0; i < 5; i++)
            {
                cache[i] = i;
            }

            Assert.That(cache[0], Is.Not.Null);
            Assert.That(cache[4], Is.Not.Null);
            cache.Clear();
            Assert.That(cache[0], Is.Null);
            Assert.That(cache[4], Is.Null);
        }
示例#28
0
                public ContextEnumerable(QueryContext context, WeakCache cache)
                {
                    _disableReportEntryValueChanged = false;
                    _context = context;
                    _cache   = cache;

                    foreach (string propertyName in _context.PredicateRelatedProperties)
                    {
                        if (!_cache._changedHandlers.ContainsKey(propertyName))
                        {
                            _cache._changedHandlers.Add(propertyName, new List <Action <IFillAbleObject> >());
                        }

                        _cache._changedHandlers[propertyName].Add(this.ReportEntryValueChanged);
                    }
                }
示例#29
0
        public void WeakCacheCleanup()
        {
            // Create a weak cache.
            var       newCache = new WeakCache <object, object>(EqualityComparer <object> .Default);
            const int opCount  = 40000;

            // Insert new values and re-shuffle old values. Just check that the cache
            // cleanup code doesn't cause exceptions.
            for (int i = 0; i < opCount; i++)
            {
                newCache.Insert(i, GenerateInt32Object(rng));

                object value;
                if (newCache.TryGet(GenerateInt32Object(rng), out value))
                {
                    newCache.Insert(GenerateInt32Object(rng), value);
                }
            }
        }
示例#30
0
文件: Habbo.cs 项目: habb0/Bluedot
        private void Init()
        {
            _loginId     = new ResettableLazyDirty <int>(() => HabboActions.GetLoginIdFromHabboId(Id));
            _username    = new ResettableLazyDirty <string>(() => HabboActions.GetHabboUsernameFromHabboId(Id));
            _dateCreated = new ResettableLazyDirty <DateTime>(() => HabboActions.GetCreationDateFromHabboId(Id));
            _lastAccess  = new ResettableLazyDirty <DateTime>(() => HabboActions.GetLastAccessDateFromHabboId(Id));
            _credits     = new ResettableLazyDirty <int>(() => HabboActions.GetCreditsFromHabboId(Id));

            _instanceStorage   = new InstanceStorage();
            _persistentStorage = new PersistentStorage(this);

            _permissions = new ResettableLazyDirty <IDictionary <string, PermissionState> >(() => CoreManager.ServerCore.PermissionDistributor.GetHabboPermissions(this));

            _figure = new ResettableLazyDirty <HabboFigure>(() => LoadFigure());
            _motto  = new ResettableLazyDirty <string>(() => HabboActions.GetMottoFromHabboId(Id));

            MessengerCategories = new HashSet <MessengerCategory>();
            Subscriptions       = new WeakCache <string, SubscriptionData>(subscriptionsName => new SubscriptionData(this, subscriptionsName));
        }
示例#31
0
        public void WeakCache_callback_called_at_right_times()
        {
            bool called                 = false;
            WeakCache <object> wc       = new WeakCache <object>();
            Func <object>      callback = () => { called = true; return(new object()); };

            wc.Get("test", callback);
            Assert.IsTrue(called);

            called = false;
            wc.Get("test", callback);
            Assert.IsFalse(called);

            GC.Collect();

            called = false;
            wc.Get("test", callback);
            Assert.IsTrue(called);
        }
示例#32
0
        private void ConfigureAuth(IAppBuilder app)
        {
            ///add the run-per-request generators for the services needed for authentication and authorization
            //1. Europa Context
            app.RunPerRequest(nameof(IDataContext), cxt => new EuropaContext(WebConstants.Misc_UniversalEuropaConfig))

            //2. Credential Authentication
            .RunPerRequest(nameof(ICredentialAuthentication), cxt => new CredentialAuthentication(cxt.GetPerRequestValue <IDataContext>(nameof(IDataContext)), new DefaultHasher()));


            //weak cache used for logon processing
            var cache = new WeakCache();

            //Authorization. In this case, it comes before authentication because bearer authentication
            //expects a token to be created already
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath           = new PathString(WebConstants.OAuthPath_TokenPath),
                ApplicationCanDisplayErrors = true,
                AccessTokenExpireTimeSpan   = WebConstants.Misc_TokenValidityDuration,
                AuthenticationType          = OAuthDefaults.AuthenticationType,
                AuthenticationMode          = Microsoft.Owin.Security.AuthenticationMode.Active,
                //AuthorizationCodeProvider = ...,

//#if DEBUG
                AllowInsecureHttp = true,
//#endif

                // Authorization server provider which controls the lifecycle of Authorization Server
                Provider = new Security.AuthorizationServer(cache)
            });

            //configure bearer authentication. This creates a claims-user from the info found in the bearer token
            //user logon is also implemented here
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new Security.BearerAuthenticationProvider(cache)
            });

            //app.UseCors(CorsOptions.AllowAll); //<-- will configure this appropriately when it is needed
        }
示例#33
0
        public void WeakCacheCleanup2()
        {
            int iterations = 100;
            var cache      = new WeakCache <object, object>();

            for (int i = 0; i < iterations; i++)
            {
                var stressTester = new CacheStressTester <object, object>(
                    rng,
                    CacheStressTester <object, object> .DefaultOpCount / iterations);
                stressTester.TestCache(
                    cache,
                    GenerateInt32Object,
                    GenerateInt32Object,
                    true,
                    false);
                stressTester = null;
                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                cache.Cleanup();
            }
        }
示例#34
0
 public HabboDistributor()
 {
     _idCache = new WeakCache<int, HabboController>(CacheInstanceGenerator);
     _usernameCache = new WeakCache<string, HabboController>(CacheInstanceGenerator);
 }
示例#35
0
 public HabboDistributor()
 {
     _idCache = new WeakCache<int, Habbo>(id => new Habbo(id));
     _usernameCache = new WeakCache<string, Habbo>(username => new Habbo(username));
 }
示例#36
0
文件: Habbo.cs 项目: habb0/Bluedot
        private void Init()
        {
            _loginId = new ResettableLazyDirty<int>(() => HabboActions.GetLoginIdFromHabboId(Id));
            _username = new ResettableLazyDirty<string>(() => HabboActions.GetHabboUsernameFromHabboId(Id));
            _dateCreated = new ResettableLazyDirty<DateTime>(() => HabboActions.GetCreationDateFromHabboId(Id));
            _lastAccess = new ResettableLazyDirty<DateTime>(() => HabboActions.GetLastAccessDateFromHabboId(Id));
            _credits = new ResettableLazyDirty<int>(() => HabboActions.GetCreditsFromHabboId(Id));

            _instanceStorage = new InstanceStorage();
            _persistentStorage = new PersistentStorage(this);

            _permissions = new ResettableLazyDirty<IDictionary<string, PermissionState>>(() => CoreManager.ServerCore.PermissionDistributor.GetHabboPermissions(this));

            _figure = new ResettableLazyDirty<HabboFigure>(() => LoadFigure());
            _motto = new ResettableLazyDirty<string>(() => HabboActions.GetMottoFromHabboId(Id));

            MessengerCategories = new HashSet<MessengerCategory>();
            Subscriptions = new WeakCache<string, SubscriptionData>(subscriptionsName => new SubscriptionData(this, subscriptionsName));
        }
示例#37
0
 public WrappedMySqlConnection(string connectionString)
 {
     _connection = new MySqlConnection(connectionString);
     _commandCache = new WeakCache<string, WrappedMySqlCommand>(NewMySqlCommand);
 }