Example #1
0
        private static void RunTest(
            ICachedObject <DateTime> cachedObject,
            CountdownEvent countdown,
            List <DateTime> refreshOrUpdateDates,
            int intervalSeconds)
        {
            cachedObject.Initialize();

            countdown.Wait(TimeSpan.FromSeconds(15)).Should().BeTrue();

            cachedObject.Dispose();

            refreshOrUpdateDates.Should().HaveCount(3);

            for (var i = 1; i < refreshOrUpdateDates.Count; i++)
            {
                var newValue = refreshOrUpdateDates[i];
                newValue.Millisecond.Should().NotBeInRange(50, 980, "each refresh should happen at the start of a second");

                var previousValue = refreshOrUpdateDates[i - 1];

                var interval = newValue - previousValue;
                interval.Should().BeCloseTo(TimeSpan.FromSeconds(intervalSeconds), TimeSpan.FromMilliseconds(100));
            }
        }
Example #2
0
        // 大文字小文字違いだけのものはCLSに準拠しない(´ω`)

        /// <summary>
        /// 定義ファイルを読み込む
        ///
        /// 定義ファイルに書いてあるファイル名が実行ファイルからの相対pathなのか、それとも
        /// 定義ファイルの存在するフォルダからの相対pathなのかどうかは、
        /// IsDefRelativePathオプションに従う。
        /// </summary>
        public YanesdkResult LoadDefFile(string filename)
        {
            Release();

            basePath = FileSys.GetDirName(filename);
            YanesdkResult result = reader.LoadDefFile(filename, OptNum);

            if (result == YanesdkResult.NoError)
            {
                Dictionary <int, FilenamelistReader.Info> .KeyCollection
                    keys = reader.Data.Keys;
                foreach (int key in keys)
                {
                    // ファイル名は定義ファイル相対pathならそのようにする
                    if (IsDefRelativePath)
                    {
                        reader.Data[key].name =
                            FileSys.MakeFullName(basePath, reader.Data[key].name);
                    }

                    ICachedObject obj = OnDefFileLoaded(reader.Data[key]);
                    dict.Add(key, obj);
                }
            }
            return(result);
        }
Example #3
0
 public virtual void SaveRows(ICachedObject[] rows, int offset, int count)
 {
     try
     {
         this.CopyShadow(rows, offset, count);
         this.SetFileModified();
         for (int i = offset; i < (offset + count); i++)
         {
             ICachedObject row = rows[i];
             this.SaveRowNoLock(row);
             rows[i] = null;
         }
     }
     catch (CoreException exception)
     {
         this.database.logger.LogSevereEvent(FwNs.Core.LC.cResources.SR.DataFileCache_SaveRows_saveRows_failed, exception);
         throw;
     }
     catch (Exception exception2)
     {
         this.database.logger.LogSevereEvent(FwNs.Core.LC.cResources.SR.DataFileCache_SaveRows_saveRows_failed, exception2);
         throw Error.GetError(0x1d2, exception2);
     }
     finally
     {
         this.InitBuffers();
     }
 }
Example #4
0
        public virtual ICachedObject Get(ICachedObject obj, IPersistentStore store, bool keep)
        {
            int pos;

            lock (this.Lock)
            {
                if (obj.IsInMemory())
                {
                    if (keep)
                    {
                        obj.KeepInMemory(true);
                    }
                    return(obj);
                }
                pos = obj.GetPos();
                if (pos < 0)
                {
                    return(null);
                }
                obj = this.cache.Get(pos);
                if (obj != null)
                {
                    if (keep)
                    {
                        obj.KeepInMemory(true);
                    }
                    return(obj);
                }
            }
            return(this.GetFromFile(pos, store, keep));
        }
Example #5
0
        public void SetTransactionInfo(ICachedObject obj)
        {
            Row       row    = (Row)obj;
            RowAction action = base.RowActionMap.Get(row.Position);

            row.rowAction = action;
        }
        public void DisposePropagatesToAllChildren()
        {
            using var source = CachedObjectFactory
                               .ConfigureFor(() => DateTime.UtcNow)
                               .Build();

            var cachedObjects = new ICachedObject <DateTime> [10];

            var previous = source;

            for (var i = 0; i < 10; i++)
            {
                var current = previous.Map(x => x.AddDays(1));
                cachedObjects[i] = current;
                previous         = current;
            }

            cachedObjects.Last().Initialize();

            foreach (var cachedObject in cachedObjects)
            {
                cachedObject.State.Should().Be(CachedObjectState.Ready);
            }

            source.Dispose();

            foreach (var cachedObject in cachedObjects)
            {
                cachedObject.State.Should().Be(CachedObjectState.Disposed);
            }
        }
        public void MappedCachedObjectsCanBeChained()
        {
            using var source = CachedObjectFactory
                               .ConfigureFor(() => DateTime.UtcNow)
                               .Build();

            var cachedObjects = new ICachedObject <DateTime> [10];

            var previous = source;

            for (var i = 0; i < 10; i++)
            {
                var current = previous.Map(x => x.AddDays(1));
                cachedObjects[i] = current;
                previous         = current;
            }

            foreach (var cachedObject in cachedObjects)
            {
                cachedObject.State.Should().Be(CachedObjectState.PendingInitialization);
            }

            cachedObjects.Last().Initialize();

            foreach (var cachedObject in cachedObjects)
            {
                cachedObject.State.Should().Be(CachedObjectState.Ready);
            }

            for (var i = 0; i < 10; i++)
            {
                cachedObjects[i].Value.Should().Be(source.Value.AddDays(i + 1));
            }
        }
        public void StaticUsage(bool compressValues, bool useBasic)
        {
            TimeSpan            cacheLifeTime = TimeSpan.FromSeconds(1);
            RedisCachingService service       = RedisHelpers.GetCustomRedis(compressValues: compressValues, useBasic: useBasic, defaultExpireTimeSpanSeconds: (int)cacheLifeTime.TotalSeconds);

            service.Clear();
            Foobar cachable = RedisHelpers.GetCachableObject();

            string   cachableKey    = RedisHelpers.CachableKey;
            DateTime startedCaching = DateTime.UtcNow;

            service.Cache(cachableKey, cachable);
            DateTime endedCaching = DateTime.UtcNow;
            ICachedObject <Foobar> existsRetrievedWrapper = service.Retrieve <Foobar>(cachableKey);

            RedisCachingService    service2 = RedisHelpers.GetCustomRedis(compressValues: compressValues, useBasic: useBasic, defaultExpireTimeSpanSeconds: (int)cacheLifeTime.TotalSeconds);
            ICachedObject <Foobar> existsRetrievedWrapper2 = service2.Retrieve <Foobar>(cachableKey);

            Assert.True(RedisHelpers.CheckFooBarEquality(cachable, existsRetrievedWrapper.Value));
            Assert.True(RedisHelpers.CheckFooBarEquality(existsRetrievedWrapper.Value, existsRetrievedWrapper2.Value));
            // they aren't reference equal
            Assert.NotEqual(existsRetrievedWrapper.Value, existsRetrievedWrapper2.Value);
            service2.Clear();
            Assert.Null(service.Retrieve <Foobar>(cachableKey));
        }
Example #9
0
 public override void Add(ICachedObject obj)
 {
     lock (this)
     {
         base.Add(obj);
     }
 }
Example #10
0
 public virtual void Add(ICachedObject obj)
 {
     lock (this.Lock)
     {
         int key = this.SetFilePos(obj);
         this.cache.Put(key, obj);
     }
 }
Example #11
0
        public override void Add(ICachedObject obj)
        {
            int realSize = obj.GetRealSize(this.RowOut);

            realSize = this.RowOut.GetStorageSize(realSize);
            obj.SetStorageSize(realSize);
            this._cache.Add(obj);
        }
Example #12
0
        private ICachedObject GetFromFile(int pos, IPersistentStore store, bool keep)
        {
            ICachedObject obj2;

            Monitor.Enter(this.Lock);
            try
            {
                ICachedObject row = this.cache.Get(pos);
                if (row != null)
                {
                    if (keep)
                    {
                        row.KeepInMemory(true);
                    }
                    return(row);
                }
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        IRowInputInterface interface2 = this.ReadObject(pos);
                        if (interface2 == null)
                        {
                            return(null);
                        }
                        row = store.Get(interface2);
                        break;
                    }
                    catch (OutOfMemoryException)
                    {
                        this.cache.ForceCleanUp();
                        if (i > 0)
                        {
                            throw;
                        }
                    }
                }
                pos = row.GetPos();
                this.cache.Put(pos, row);
                if (keep)
                {
                    row.KeepInMemory(true);
                }
                store.Set(row);
                obj2 = row;
            }
            catch (CoreException exception)
            {
                this.database.logger.LogSevereEvent(this.DataFileName + FwNs.Core.LC.cResources.SR.DataFileCache_GetFromFile__getFromFile_ + pos, exception);
                throw;
            }
            finally
            {
                Monitor.Exit(this.Lock);
            }
            return(obj2);
        }
Example #13
0
        public int[] WriteTableToDataFile(Table table)
        {
            IPersistentStore    rowStore = this._database.GetSessionManager().GetSysSession().sessionData.GetRowStore(table);
            IRowOutputInterface output   = this._cache.RowOut.Duplicate();
            DoubleIntIndex      lookup   = new DoubleIntIndex(table.GetPrimaryIndex().SizeUnique(rowStore), false);

            int[] indexRootsArray = table.GetIndexRootsArray();
            long  num             = this._fileOffset;
            int   num2            = 0;

            lookup.SetKeysSearchTarget();
            Error.PrintSystemOut(FwNs.Core.LC.cResources.SR.DataFileDefrag_WriteTableToDataFile_lookup_begins__ + this._stopw.ElapsedTime());
            IRowIterator rowIterator = table.GetRowIterator(rowStore);

            while (rowIterator.HasNext())
            {
                ICachedObject nextRow = rowIterator.GetNextRow();
                lookup.AddUnsorted(nextRow.GetPos(), (int)(num / ((long)this._scale)));
                if ((num2 % 0xc350) == 0)
                {
                    Error.PrintSystemOut(string.Concat(new object[] { FwNs.Core.LC.cResources.SR.DataFileDefrag_WriteTableToDataFile_pointer_pair_for_row_, num2, FwNs.Core.LC.cResources.SR.Single_Space, nextRow.GetPos(), FwNs.Core.LC.cResources.SR.Single_Space, num }));
                }
                num += nextRow.GetStorageSize();
                num2++;
            }
            Error.PrintSystemOut(string.Concat(new object[] { FwNs.Core.LC.cResources.SR.DataFileDefrag_WriteTableToDataFile_table__, table.GetName().Name, FwNs.Core.LC.cResources.SR.DataFileDefrag_WriteTableToDataFile__list_done__, this._stopw.ElapsedTime() }));
            num2        = 0;
            rowIterator = table.GetRowIterator(rowStore);
            while (rowIterator.HasNext())
            {
                ICachedObject nextRow = rowIterator.GetNextRow();
                output.Reset();
                nextRow.Write(output, lookup);
                this._fileStreamOut.Write(output.GetOutputStream().GetBuffer(), 0, output.Size());
                this._fileOffset += nextRow.GetStorageSize();
                if ((num2 % 0xc350) == 0)
                {
                    Error.PrintSystemOut(num2 + FwNs.Core.LC.cResources.SR.DataFileDefrag_WriteTableToDataFile__rows_ + this._stopw.ElapsedTime());
                }
                num2++;
            }
            for (int i = 0; i < table.GetIndexCount(); i++)
            {
                if (indexRootsArray[i] != -1)
                {
                    int num4 = lookup.FindFirstEqualKeyIndex(indexRootsArray[i]);
                    if (num4 == -1)
                    {
                        throw Error.GetError(0x1d2);
                    }
                    indexRootsArray[i] = lookup.GetValue(num4);
                }
            }
            this.SetTransactionRowLookups(lookup);
            Error.PrintSystemOut(FwNs.Core.LC.cResources.SR.DataFileDefrag_WriteTableToDataFile_table__ + table.GetName().Name + FwNs.Core.LC.cResources.SR.DataFileDefrag_WriteTableToDataFile____table_converted);
            return(indexRootsArray);
        }
Example #14
0
        public void InvalidateTest()
        {
            Mock <ICachingService> cachingService = GetService();
            ICachedObject <string> cachedObject   = GetCachedObject();

            cachingService.Setup(x => x.Invalidate(key)).Returns(true);

            Assert.True(cachingService.Object.Invalidate(key));
        }
Example #15
0
        public void CacheTest2()
        {
            Mock <ICachingService> cachingService = GetService();
            ICachedObject <string> cachedObject   = GetCachedObject();

            cachingService.Setup(x => x.Cache(key, cachedObject.Value, cachedObject.CachedTime, cachedObject.ExpireTime));

            cachingService.Object.Cache(key, cachedObject.Value, cachedObject.CachedTime, cachedObject.ExpireTime);
        }
Example #16
0
        public void RetrieveTest()
        {
            Mock <ICachingService> cachingService = GetService();
            ICachedObject <string> cachedObject   = GetCachedObject();

            cachingService.Setup(x => x.Retrieve <string>(key)).Returns(cachedObject);

            Assert.Equal(cachedObject, cachingService.Object.Retrieve <string>(key));
        }
Example #17
0
        public void CacheTest()
        {
            Mock <ICachingService> cachingService = GetService();
            ICachedObject <string> cachedObject   = GetCachedObject();

            cachingService.Setup(x => x.Cache(key, cachedObject));

            cachingService.Object.Cache(key, cachedObject);
        }
Example #18
0
        public override void SetAccessor(Index key, int accessor)
        {
            ICachedObject node = this.Get(accessor, false);

            if (node != null)
            {
                node = ((RowAVL)node).GetNode(key.GetPosition());
            }
            this.SetAccessor(key, node);
        }
        private static async Task <T> GetValue(
            ICachedObject <TSource> source,
            Func <TSource, Task <T> > map,
            CancellationToken cancellationToken)
        {
            if (source.State != CachedObjectState.Ready)
            {
                await source.InitializeAsync(cancellationToken).ConfigureAwait(false);
            }

            return(await map(source.Value).ConfigureAwait(false));
        }
        private protected void AddOnValueRefreshedActions(ICachedObject <T> cachedObject)
        {
            if (!(_onValueRefreshedAction is null))
            {
                cachedObject.OnValueRefreshed += (_, e) => _onValueRefreshedAction(e);
            }

            if (!(_onValueRefreshExceptionAction is null))
            {
                cachedObject.OnValueRefreshException += (_, e) => _onValueRefreshExceptionAction(e);
            }
        }
Example #21
0
 public virtual void Remove(int i, IPersistentStore store)
 {
     lock (this.Lock)
     {
         ICachedObject obj2 = this.Release(i);
         if (obj2 != null)
         {
             int storageSize = obj2.GetStorageSize();
             this.FreeBlocks.Add(i, storageSize);
         }
     }
 }
Example #22
0
        private ICachedObject <string> GetCachedObject()
        {
            Mock <ICachedObject <string> > cachedObjectProxy = new Mock <ICachedObject <string> >();

            cachedObjectProxy.SetupAllProperties();
            ICachedObject <string> cachedObject = cachedObjectProxy.Object;

            cachedObject.ExpireTime = expireTime;
            cachedObject.CachedTime = time;
            cachedObject.Value      = value;

            return(cachedObject);
        }
Example #23
0
 protected void CopyShadow(ICachedObject[] rows, int offset, int count)
 {
     if (this._shadowFile != null)
     {
         for (int i = offset; i < (offset + count); i++)
         {
             ICachedObject obj2       = rows[i];
             long          fileOffset = obj2.GetPos() * this.CacheFileScale;
             this._shadowFile.Copy(fileOffset, obj2.GetStorageSize());
         }
         this._shadowFile.Close();
     }
 }
Example #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected override ICachedObject OnDefFileLoaded(FilenamelistReader.Info info)
        {
            if (Factory == null)
            {
                return(null);                //  YanesdkResult.PreconditionError; // factoryが設定されていない
            }
            ICachedObject obj = Factory();

            // info.name, ColorKey を渡したい
            obj.Construct(new TextrueConstructAdaptor(info.name, ColorKey));

            return(obj);
        }
        public void AddKvp()
        {
            TimeSpan             cacheLifeTime = TimeSpan.FromMinutes(5);
            MemoryCachingService service       = new MemoryCachingService(cacheLifeTime);
            Foobar cachable    = GetCachableObject();
            string cachableKey = this.cachableKey;
            KeyValuePair <string, ICachedObjectBasic> item = GetCachableKvp(DateTime.UtcNow, cacheLifeTime, cachable, cachableKey);

            service.Add(item);
            ICachedObject <Foobar> result = service.Retrieve <Foobar>(cachableKey);

            Assert.Equal(cachable, result.Value);
        }
Example #26
0
 private void SaveRowNoLock(ICachedObject row)
 {
     try
     {
         this.RowOut.Reset();
         row.Write(this.RowOut);
         this.DataFile.Seek(row.GetPos() * this.CacheFileScale);
         this.DataFile.Write(this.RowOut.GetOutputStream().GetBuffer(), 0, this.RowOut.GetOutputStream().Size());
     }
     catch (IOException exception)
     {
         throw Error.GetError(0x1d2, exception);
     }
 }
Example #27
0
 public override ICachedObject Get(ICachedObject obj, bool keep)
 {
     try
     {
         if (this._isCached)
         {
             return(this._cache.Get(obj, this, keep));
         }
         return(obj);
     }
     catch (CoreException)
     {
         return(null);
     }
 }
        public void AddKvp(bool compressValues, bool useBasic)
        {
            TimeSpan            cacheLifeTime = TimeSpan.FromMinutes(5);
            RedisCachingService service       = RedisHelpers.GetRedis(compressValues: compressValues, useBasic: useBasic);

            service.Clear();
            Foobar cachable    = RedisHelpers.GetCachableObject();
            string cachableKey = RedisHelpers.CachableKey;
            KeyValuePair <string, ICachedObjectBasic> item = RedisHelpers.GetCachableKvp(DateTime.UtcNow, cacheLifeTime, cachable, cachableKey);

            service.Add(item);
            ICachedObject <Foobar> result = service.Retrieve <Foobar>(cachableKey);

            Assert.True(RedisHelpers.CheckFooBarEquality(cachable, result.Value));
        }
Example #29
0
        private DataTable GetData(SPList list, SPQuery query)
        {
            if (string.IsNullOrEmpty(query.ViewFields))
            {
                throw new ArgumentException("The ViewFields property for SPQuery hasn't been set.");
            }

            string viewXml = XElement.Parse(query.ViewXml, LoadOptions.None).ToString(SaveOptions.DisableFormatting);

            ICachedObject <SPListQueryCachedData> queryCache =
                SPCache.Cache(() => GetListQueryCachedData(list, viewXml))
                .By(list.ID.ToString(),
                    list.ParentWeb.ID.ToString(),
                    list.ParentWeb.Site.ID.ToString(),
                    list.ParentWeb.CurrentUser.Sid);

            if (CacheTime != default(TimeSpan))
            {
                queryCache.ForSliding(CacheTime);
            }

            SPListQueryCachedData listQueryCachedData = queryCache.CachedObject;

            string keyQuery;

            if (HasListChanged(list, listQueryCachedData))
            {
                listQueryCachedData.Clear();
                listQueryCachedData = GetListQueryCachedData(list);
                keyQuery            = Guid.NewGuid().ToString();
                listQueryCachedData.Add(keyQuery, viewXml);
                queryCache.CachedObject = listQueryCachedData;
                queryCache.Update();
            }
            else
            {
                keyQuery = listQueryCachedData.FindKey(viewXml);
            }

            ICachedObject <DataTable> dataCache = listQueryCachedData.GetDataCache(keyQuery, () => LoadDataTable(list, query));

            if (CacheTime != default(TimeSpan))
            {
                dataCache.ForSliding(CacheTime);
            }

            return(dataCache.CachedObject);
        }
        public static bool AppendCachedObject <T>(string name, ICachedObject <T> obj)
        {
            if (string.IsNullOrEmpty(name) || obj == null)
            {
                throw new Exception("Name and Object cannot be null or empty.");
            }

            if (_CacheContainer == null)
            {
                InitContainer();
            }

            _CacheContainer[name] = obj;

            return(true);
        }