示例#1
0
        public void EmptyCacheCanBeCreated()
        {
            var cache = CacheFactory.CreateCache(new List <string>());

            Assert.IsNotNull(cache);
            CollectionAssert.AreEquivalent(cache.ToList(), new List <string>());
        }
 /// <summary>
 /// used to customise user configuration caching options; in most cases defaults will be ok
 /// </summary>
 /// <param name="cacheType"></param>
 /// <param name="cacheTimeout"></param>
 public UserConfigurationActionFilterAtribute(CacheType cacheType, int cacheTimeout)
 {
     if (Cache == null)
     {
         Cache = CacheFactory.CreateCache <MapHive.Core.Configuration.UserConfiguration>(cacheType, cacheTimeout);
     }
 }
示例#3
0
        public void TestAddAndReadInDifferentThreadsWorkQuickly()
        {
            var cache1 = CacheFactory.CreateCache <string>("testCache1");

            var t1 = Task.Factory.StartNew(() =>
            {
                int i = 0;
                while (i < 1000)
                {
                    var key = "key" + (i % 10);
                    // Debug.WriteLine("1  | " + key);
                    cache1.Add(key, "A");
                    i++;
                }
            });

            var t2 = Task.Factory.StartNew(() =>
            {
                int i = 0;
                while (i < 1000)
                {
                    var key = "key" + (i % 10);
                    //Debug.WriteLine("2  | " + key);
                    cache1.Add(key, "A");
                    i++;
                }
            });

            Task.WaitAll(t1, t2);
        }
示例#4
0
        public void ExceptionIsThrownIfIndexerIsRemovedFromProperty()
        {
            var cache = CacheFactory.CreateCache(Person.CreateTestData());

            cache.AddIndexer(new Indexer <Person, string>(p => p.Name));
            cache.RemoveIndexer(new Indexer <Person, string>(p => p.Name));
            Assert.ThrowsException <ArgumentException>(() => { cache.Get(p => p.Name, "Jane"); });
        }
示例#5
0
 public TokenAuthorizeMiddleware(RequestDelegate next, CacheType cacheType, int cacheTimeout)
 {
     this._next = next;
     if (Cache == null)
     {
         Cache = CacheFactory.CreateCache <bool>(cacheType, cacheTimeout);
     }
 }
示例#6
0
        public void TestTwoInstancesDontHaveCommonObjects()
        {
            var cache1 = CacheFactory.CreateCache <string>("testCache1");
            var cache2 = CacheFactory.CreateCache <string>("testCache2");

            cache1.Add("first", "stam1");
            cache2.Add("first", "stam2");

            Assert.AreNotEqual(cache1.Get("first"), cache2.Get("first"));
        }
示例#7
0
        public void ItemIsReturnedIfIndexed()
        {
            var cache = CacheFactory.CreateCache(Person.CreateTestData());

            cache.AddIndexer(new Indexer <Person, string>(p => p.Name));
            var janes = cache.Get(p => p.Name, "Jane").ToList();

            Assert.AreEqual(2, janes.Count);
            Assert.AreEqual(1, janes.Count(j => j.Name == "Jane" && j.LastName == "Smith"));
            Assert.AreEqual(1, janes.Count(j => j.Name == "Jane" && j.LastName == "Johnes"));
        }
示例#8
0
        public void ItemsRemovedFromHolderAreIndexed()
        {
            var cache = CacheFactory.CreateCache(Person.CreateTestData());

            cache.AddIndexer(new Indexer <Person, string>(p => p.Name));
            Person janeJohnes = Person.CreateTestData().Single(p => p.Name == "Jane" && p.LastName == "Johnes");

            cache.RemoveItems(janeJohnes);
            var janes = cache.Get(p => p.Name, "Jane").ToList();

            Assert.AreEqual(1, janes.Count(j => j.Name == "Jane" && j.LastName == "Smith"));
        }
示例#9
0
        public void CreateCache_WithDuplicatedName_ThrowsDuplicatedNameException()
        {
            //Arrange
            var cacheName             = Guid.NewGuid().ToString();
            ICache <User, int> cache1 = CacheFactory.CreateCache <User, int>(cacheName, _sizeLimit);

            //Act & Assert
            Exception ex = Assert.Throws <DuplicateNameException>(() =>
            {
                ICache <User, int> cache2 = CacheFactory.CreateCache <User, int>(cacheName, _sizeLimit);
            });
        }
示例#10
0
        public void CreateCache_WithValidParameters_RegistersCahceInCacheManager()
        {
            //Arrange
            var cacheName = Guid.NewGuid().ToString();

            //Act
            ICache <User, int> cache = CacheFactory.CreateCache <User, int>(cacheName, _sizeLimit);
            var result = CacheManager.Instance.CacheExists(cacheName);

            //Assert
            Assert.True(result);
        }
示例#11
0
        public void TestAddTwiceSameKeyGetTheLastOne()
        {
            // Arrange
            var cache = CacheFactory.CreateCache <string>("testCache");

            cache.Add("first", "stam");

            // Act
            cache.Add("first", "stam2");

            // Assert
            Assert.AreEqual(cache.Get("first"), "stam2");
        }
示例#12
0
        public void ConfigureServices(IServiceCollection services)
        {
            CacheConfiguration cacheConfig = new CacheConfiguration();

            Configuration.GetSection("cache").Bind(cacheConfig);
            services.AddSingleton(cacheConfig);

            services.Configure <RouteOptions>(routeOptions =>
            {
                routeOptions.ConstraintMap.Add("nationalCode", typeof(NationalCodeConstraint));
            });
            services.AddCachingStrategy(cacheConfig);
            services.AddTransient(c => CacheFactory.CreateCache(c));
        }
示例#13
0
        private bool Has(Type type, string fieldType, string fieldName)
        {
            if (!properties.ContainsKey(fieldType))
            {
                properties.Add(fieldType, CacheFactory.CreateCache <bool>(fieldType));
            }

            if (!properties[fieldType].ContainsKey(fieldName))
            {
                properties[fieldType].Add(fieldName, type != null && type.GetProperty(fieldName) != null);
            }

            return(properties[fieldType][fieldName]);
        }
示例#14
0
        public void ItemAddedToHolderIsIndexed()
        {
            var cache = CacheFactory.CreateCache(Person.CreateTestData());

            cache.AddIndexer(new Indexer <Person, string>(p => p.Name));
            cache.AddItems(new Person("Jane", "Dow", new DateTime()), new Person("Jill", "Jungle", new DateTime()));

            var janes = cache.Get(p => p.Name, "Jane").ToList();

            Assert.AreEqual(3, janes.Count);
            Assert.AreEqual(1, janes.Count(j => j.Name == "Jane" && j.LastName == "Smith"));
            Assert.AreEqual(1, janes.Count(j => j.Name == "Jane" && j.LastName == "Johnes"));
            Assert.AreEqual(1, janes.Count(j => j.Name == "Jane" && j.LastName == "Dow"));
        }
示例#15
0
        public App()
        {
            CacheFactory.CreateCache().Init();
            LogUtil.Info($"IsFreshInstall={CacheFactory.CreateCache().IsFreshInstall()}");
            var service = TeslaService;

            if (service.RequiresLogin())
            {
                MainPage = new LoginPage(service, profileService, teslaAPIWrapper);
            }
            else
            {
                MainPage = new NavigationPage(new VehicleNavigation(service, profileService, teslaAPIWrapper));
            }
        }
示例#16
0
        public void ItemsCanBeRemovedFromCache()
        {
            var cache = CacheFactory.CreateCache(new List <string>
            {
                "first",
                "second",
                "third",
                "fourth"
            });

            cache.RemoveItems("first", "fourth");
            var expected = new List <string>
            {
                "second",
                "third"
            };

            CollectionAssert.AreEquivalent(cache.ToList(), expected);
        }
示例#17
0
        public void NonEmptyCacheCanBeCreated()
        {
            var cache = CacheFactory.CreateCache(new List <string>
            {
                "first",
                "second",
                "third"
            });

            Assert.IsNotNull(cache);
            var expected = new List <string>
            {
                "first",
                "second",
                "third"
            };

            CollectionAssert.AreEquivalent(cache.ToList(), expected);
        }
示例#18
0
        public RedisFarmTransport(string connectionString, string roomName = "BackandElb")
        {
            this.roomName     = roomName;
            this.SubscriberID = Guid.NewGuid().ToString();

            this.lockers = CacheFactory.CreateCache <ManualResetEvent>("RedisFarmTransport" + roomName);
            //todo: log

            redis = CreateRedisConnection(connectionString);

            subscriber = redis.GetSubscriber();

            database = redis.GetDatabase();

            Status = new Status(database, SubscriberID);

            subscriber.Subscribe(roomName, (channel, message) =>
            {
                MessageCount++;

                // todo: log info
                var messageAsObject = JsonConvert.DeserializeObject <FarmMessageWrapper>((string)message);

                if (messageAsObject.SenderId != SubscriberID)
                {
                    ValidMessageCount++;
                    OnMessage(this, new FarmEventArgs {
                        Message = messageAsObject.Message
                    });
                }
                else // message sent by myself, check another thread wait for ack
                {
                    var key = messageAsObject.Message.Id.ToString();

                    if (lockers.ContainsKey(key))
                    {
                        lockers[key].Set();
                    }
                }
            });
        }
示例#19
0
        public void TestCanAddDataSetObjects()
        {
            var       cache = CacheFactory.CreateCache <DataSet>("testCache");
            DataSet   ds    = new DataSet();
            DataTable table = new DataTable();

            table.Columns.Add("a", typeof(int));
            table.Columns.Add("b", typeof(string));
            table.Columns.Add("c", typeof(bool));
            table.Rows.Add(1, "s", true);
            ds.Tables.Add(table);

            // Act
            cache.Add("first", ds);

            var fetchedDs = cache.Get("first");
            var row       = ds.Tables[0].Rows[0];

            Assert.AreEqual(row[0], 1);
            Assert.AreEqual(row[1], "s");
            Assert.AreEqual(row[2], true);
        }
示例#20
0
 private void Initialize()
 {
     _cache = CacheFactory.CreateCache <User, int>(Guid.NewGuid().ToString(), _sizeLimit);
 }
示例#21
0
文件: Program.cs 项目: eqr/Grid.NET
        static void Main(string[] args)
        {
            var sw = Stopwatch.StartNew();

            sw.Start();
            int dataSize      = 2 * 1000 * 1000;
            var testData      = PrepareTestData(dataSize);
            int sampleSize    = 2000;
            var sampleQueries = new List <Item>(sampleSize);
            var random        = new Random();

            for (int i = 0; i < sampleSize; i++)
            {
                sampleQueries.Add(testData[random.Next(dataSize)]);
            }

            sw.Stop();
            Console.WriteLine($"Preparing data took {sw.Elapsed}");
            sw.Reset();

            sw.Start();
            foreach (var sampleQuery in sampleQueries)
            {
                var r = testData.First(i => i.Equals(sampleQuery));
            }

            sw.Stop();
            Console.WriteLine($"Plain old search {sampleSize} from {dataSize}: {sw.Elapsed}");
            sw.Reset();

            Dictionary <string, Item> dict =
                testData.ToDictionary(d => d.Value, d => d, StringComparer.OrdinalIgnoreCase);

            sw.Start();
            foreach (var sampleQuery in sampleQueries)
            {
                var r = dict[sampleQuery.Value];
            }

            sw.Stop();
            Console.WriteLine($"Searching in dictionary took {sw.Elapsed}");
            sw.Reset();

            sw.Start();
            var cache = CacheFactory.CreateCache(testData);

            sw.Stop();
            Console.WriteLine($"Creating cache took {sw.Elapsed}");
            sw.Reset();

            sw.Start();
            cache.AddIndexer(new Indexer <Item, string>(i => i.Value));
            sw.Stop();
            Console.WriteLine($"Indexing took {sw.Elapsed}");
            sw.Reset();

            sw.Start();
            foreach (var sampleQuery in sampleQueries)
            {
                var r = cache.Get(i => i.Value, sampleQuery.Value);
            }
            sw.Stop();
            Console.WriteLine($"Lookup in cache took {sw.Elapsed}");
        }
示例#22
0
        public void ExceptionIsThrownIfPropertyIsNotIndexed()
        {
            var cache = CacheFactory.CreateCache(Person.CreateTestData());

            Assert.ThrowsException <ArgumentException>(() => { cache.Get(p => p.Name, "Jane"); });
        }
示例#23
0
 protected virtual ICacheConcurrencyStrategy CreateCache(CacheBase cache, string strategy = CacheFactory.ReadWrite)
 {
     return(CacheFactory.CreateCache(strategy, cache, Sfi.Settings));
 }
示例#24
0
        public void TestGetNonExistingKeyReturnNull()
        {
            var cache = CacheFactory.CreateCache <string>("testCache");

            Assert.IsNull(cache.Get("unexsiting"));
        }
示例#25
0
        public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
        {
            Init();
            log.Info("building session factory");

            properties          = new Dictionary <string, string>(cfg.Properties);
            interceptor         = cfg.Interceptor;
            this.settings       = settings;
            sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
            eventListeners      = listeners;
            filters             = new Dictionary <string, FilterDefinition>(cfg.FilterDefinitions);
            if (log.IsDebugEnabled)
            {
                log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters));
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties));
            }

            try
            {
                if (settings.IsKeywordsImportEnabled)
                {
                    SchemaMetadataUpdater.Update(this);
                }
                if (settings.IsAutoQuoteEnabled)
                {
                    SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
                }
            }
            catch (NotSupportedException)
            {
                // Ignore if the Dialect does not provide DataBaseSchema
            }

            #region Caches
            settings.CacheProvider.Start(properties);
            #endregion

            #region Generators
            identifierGenerators = new Dictionary <string, IIdentifierGenerator>();
            foreach (PersistentClass model in cfg.ClassMappings)
            {
                if (!model.IsInherited)
                {
                    IIdentifierGenerator generator =
                        model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
                                                                   settings.DefaultSchemaName, (RootClass)model);

                    identifierGenerators[model.EntityName] = generator;
                }
            }
            #endregion

            #region Persisters

            Dictionary <string, ICacheConcurrencyStrategy> caches = new Dictionary <string, ICacheConcurrencyStrategy>();
            entityPersisters        = new Dictionary <string, IEntityPersister>();
            implementorToEntityName = new Dictionary <System.Type, string>();

            Dictionary <string, IClassMetadata> classMeta = new Dictionary <string, IClassMetadata>();

            foreach (PersistentClass model in cfg.ClassMappings)
            {
                model.PrepareTemporaryTables(mapping, settings.Dialect);
                string cacheRegion = model.RootClazz.CacheRegionName;
                ICacheConcurrencyStrategy cache;
                if (!caches.TryGetValue(cacheRegion, out cache))
                {
                    cache =
                        CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
                    if (cache != null)
                    {
                        caches.Add(cacheRegion, cache);
                        allCacheRegions.Add(cache.RegionName, cache.Cache);
                    }
                }
                IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
                entityPersisters[model.EntityName] = cp;
                classMeta[model.EntityName]        = cp.ClassMetadata;

                if (model.HasPocoRepresentation)
                {
                    implementorToEntityName[model.MappedClass] = model.EntityName;
                }
            }
            classMetadata = new UnmodifiableDictionary <string, IClassMetadata>(classMeta);

            Dictionary <string, ISet <string> > tmpEntityToCollectionRoleMap = new Dictionary <string, ISet <string> >();
            collectionPersisters = new Dictionary <string, ICollectionPersister>();
            foreach (Mapping.Collection model in cfg.CollectionMappings)
            {
                ICacheConcurrencyStrategy cache =
                    CacheFactory.CreateCache(model.CacheConcurrencyStrategy, model.CacheRegionName, model.Owner.IsMutable, settings,
                                             properties);
                if (cache != null)
                {
                    allCacheRegions[cache.RegionName] = cache.Cache;
                }
                ICollectionPersister persister = PersisterFactory.CreateCollectionPersister(cfg, model, cache, this);
                collectionPersisters[model.Role] = persister;
                IType indexType = persister.IndexType;
                if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)indexType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
                IType elementType = persister.ElementType;
                if (elementType.IsAssociationType && !elementType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)elementType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
            }
            Dictionary <string, ICollectionMetadata> tmpcollectionMetadata = new Dictionary <string, ICollectionMetadata>(collectionPersisters.Count);
            foreach (KeyValuePair <string, ICollectionPersister> collectionPersister in collectionPersisters)
            {
                tmpcollectionMetadata.Add(collectionPersister.Key, collectionPersister.Value.CollectionMetadata);
            }
            collectionMetadata = new UnmodifiableDictionary <string, ICollectionMetadata>(tmpcollectionMetadata);
            collectionRolesByEntityParticipant = new UnmodifiableDictionary <string, ISet <string> >(tmpEntityToCollectionRoleMap);
            #endregion

            #region Named Queries
            namedQueries         = new Dictionary <string, NamedQueryDefinition>(cfg.NamedQueries);
            namedSqlQueries      = new Dictionary <string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
            sqlResultSetMappings = new Dictionary <string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
            #endregion

            imports = new Dictionary <string, string>(cfg.Imports);

            #region after *all* persisters and named queries are registered
            foreach (IEntityPersister persister in entityPersisters.Values)
            {
                persister.PostInstantiate();
            }
            foreach (ICollectionPersister persister in collectionPersisters.Values)
            {
                persister.PostInstantiate();
            }
            #endregion

            #region Serialization info

            name = settings.SessionFactoryName;
            try
            {
                uuid = (string)UuidGenerator.Generate(null, null);
            }
            catch (Exception)
            {
                throw new AssertionFailure("Could not generate UUID");
            }

            SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

            #endregion

            log.Debug("Instantiated session factory");

            #region Schema management
            if (settings.IsAutoCreateSchema)
            {
                new SchemaExport(cfg).Create(false, true);
            }

            if (settings.IsAutoUpdateSchema)
            {
                new SchemaUpdate(cfg).Execute(false, true);
            }
            if (settings.IsAutoValidateSchema)
            {
                new SchemaValidator(cfg, settings).Validate();
            }
            if (settings.IsAutoDropSchema)
            {
                schemaExport = new SchemaExport(cfg);
            }
            #endregion

            #region Obtaining TransactionManager
            // not ported yet
            #endregion

            currentSessionContext = BuildCurrentSessionContext();

            if (settings.IsQueryCacheEnabled)
            {
                updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
                queryCache            = settings.QueryCacheFactory.GetQueryCache(null, updateTimestampsCache, settings, properties);
                queryCaches           = new ThreadSafeDictionary <string, IQueryCache>(new Dictionary <string, IQueryCache>());
            }
            else
            {
                updateTimestampsCache = null;
                queryCache            = null;
                queryCaches           = null;
            }

            #region Checking for named queries
            if (settings.IsNamedQueryStartupCheckingEnabled)
            {
                IDictionary <string, HibernateException> errors = CheckNamedQueries();
                if (errors.Count > 0)
                {
                    StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
                    foreach (KeyValuePair <string, HibernateException> pair in errors)
                    {
                        failingQueries.Append('{').Append(pair.Key).Append('}');
                        log.Error("Error in named query: " + pair.Key, pair.Value);
                    }
                    throw new HibernateException(failingQueries.ToString());
                }
            }
            #endregion

            Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

            // EntityNotFoundDelegate
            IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
            if (enfd == null)
            {
                enfd = new DefaultEntityNotFoundDelegate();
            }
            entityNotFoundDelegate = enfd;
        }
示例#26
0
 public ProfileService() : this(CacheFactory.CreateCache())
 {
 }