public void LocalCache_will_retrieve_content_from_cache_if_it_exists()
        {
            // Arrange
            var cachedContent = new Content
            {
                RefreshDate = new DateTime(2014, 01, 01),
                Sections = new List<ContentSection>
                {
                    new ContentSection
                    {
                        Id = ContentTypes.HeaderWithoutMegaNav.ToString(),
                        Html = "<div id='header' />"
                    }
                }
            };
            var storageHandler = new Mock<IStorageHandler<Content>>();
            storageHandler.Setup(x => x.ReadFromStorage(ContentTypes.HeaderWithoutMegaNav)).Returns(cachedContent);
            var cache = new LocalCache<Content>(storageHandler.Object);

            // Act
            var footerWithoutMegaNav = cache.ReadFromCache(ContentTypes.HeaderWithoutMegaNav);

            // Assert
            Assert.That(footerWithoutMegaNav, Is.Not.Null);
        }
Example #2
0
 protected LocalCacheTable(LocalCache cache, string name, TableOptions options)
 {
    m_Name = name;
    m_Cache = cache;
    m_Options = options!=null ? options.Clone() : new TableOptions(name);
    m_Options.m_Name = name;
 } 
Example #3
0
        static Current()
        {
            var connection = new AsyncRedisConnection(null, "127.0.0.1:6379,connectTimeout=10", () => false, "", "ryujit-debug");
            var syncRoot = new object();
            var localCache = new LocalCache(syncRoot, 0);
            var redis = new AsyncDelayedRedisCache("connect", new Messaging(connection), connection, localCache, new NullCache(0), 0, "dev");
            SiteCache = new ImmediateCache(redis, 0);

            #pragma warning disable 618
            LocalCache.LogDuration += (string key, string caller, int? duration) =>
            #pragma warning restore 618
            {
                if (key.Contains("guid-test"))
                {
                    switch (caller)
                    {
                        case "LocalCache.Set":
                            CurrentTest.LocalCacheSetDuration = duration;
                            break;
                        case "LocalCache.SetWithPriority":
                            CurrentTest.LocalCacheSetWithPriorityDuration = duration;
                            break;
                        case "RawSet":
                            CurrentTest.RawSetDuration = duration;
                            break;
                    }
                }
            };
        }
        public void LocalCache_will_not_store_to_cache_if_content_type_already_added_with_same_refresh_time()
        {
            // Arrange
            var contentRefreshDate = new DateTime(2014, 07, 07, 12, 30, 0);
            var storageHandler = new Mock<IStorageHandler<Content>>();

            storageHandler.Setup(x => x.WriteToStorage(It.IsAny<ContentTypes>(), It.IsAny<Content>()));
            var cache = new LocalCache<Content>(storageHandler.Object);
            var footerContent = new Content
            {
                Sections = new List<ContentSection>
                {
                    new ContentSection
                    {
                        Id = ContentTypes.Footer.ToString(),
                        Html = "<div id='footer' />"
                    }
                },
                RefreshDate = contentRefreshDate
            };

            // Act
            cache.WriteToCache(ContentTypes.Footer, footerContent, footerContent.RefreshDate);
            cache.WriteToCache(ContentTypes.Footer, footerContent, footerContent.RefreshDate);

            // Assert
            storageHandler.Verify(x => x.WriteToStorage(It.IsAny<ContentTypes>(), It.IsAny<Content>()), Times.Once);
        }
        public void LocalCache_will_return_null_if_content_does_not_exist_in_cache()
        {
            // Arrange
            var storageHandler = new Mock<IStorageHandler<Content>>();
            storageHandler.Setup(x => x.ReadFromStorage(ContentTypes.HeaderWithoutMegaNav)).Returns((Content)null);
            var cache = new LocalCache<Content>(storageHandler.Object);

            // Act
            var footerWithoutMegaNav = cache.ReadFromCache(ContentTypes.HeaderWithoutMegaNav);

            // Assert
            Assert.That(footerWithoutMegaNav, Is.Null);
        }
 public InMemoryNetworkCache(long maxCacheSize)
 {
     heapCache = new LocalCache(Cache.ClosestPrime(12000), maxCacheSize);
     s2BlockCache = new Dictionary<BlockId, BlockCacheElement>(1023);
     pathInfoMap = new Dictionary<string, PathInfo>(255);
 }
 /// <summary>
 /// Removes all elements from the <b>IDictionary</b> object.
 /// </summary>
 public virtual void Clear()
 {
     LocalCache.Clear();
 }
 /// <summary>
 /// Determines whether the <see cref="IDictionary"/> object contains
 /// an element with the specified key.
 /// </summary>
 /// <returns>
 /// <b>true</b> if the <b>IDictionary</b> contains an element with
 /// the key; otherwise, <b>false</b>.
 /// </returns>
 public virtual bool Contains(object key)
 {
     return(LocalCache.Contains(key));
 }
 /// <summary>
 /// Copies all of the mappings from the specified dictionary to this
 /// cache (optional operation).
 /// </summary>
 /// <remarks>
 /// These mappings will replace any mappings that this cache had for
 /// any of the keys currently in the specified dictionary.
 /// </remarks>
 /// <param name="dictionary">
 /// Mappings to be stored in this cache.
 ///  </param>
 /// <exception cref="InvalidCastException">
 /// If the class of a key or value in the specified dictionary
 /// prevents it from being stored in this cache.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// If the lock could not be succesfully obtained for some key.
 /// </exception>
 /// <exception cref="NullReferenceException">
 /// This cache does not permit <c>null</c> keys or values, and the
 /// specified key or value is <c>null</c>.
 /// </exception>
 public virtual void InsertAll(IDictionary dictionary)
 {
     LocalCache.InsertAll(dictionary);
 }
Example #10
0
      public void T060_PileNonOwnership()
      {
        var pile = new DefaultPile();
        pile.Start();
        try
        {
              var cache = new LocalCache();
              cache.Pile = pile;
              cache.Configure(null);
              cache.Start();
                
        
              var tA = cache.GetOrCreateTable<string>("A");
              tA.Put("aaa", "avalue");
              tA.Put("bbb", "bvalue");
              Assert.AreEqual("avalue", tA.Get("aaa"));

              Assert.AreEqual(2, cache.Count);
              Assert.AreEqual(2, pile.ObjectCount);

              cache.WaitForCompleteStop();
              Assert.AreEqual(NFX.ServiceModel.ControlStatus.Inactive, cache.Status);
        
              Assert.AreEqual(NFX.ServiceModel.ControlStatus.Active, pile.Status);
              Assert.AreEqual(0, pile.ObjectCount);
       
              cache = new LocalCache();
              cache.Pile = pile;
              cache.Configure(null);
              cache.Start();

              var tAbc = cache.GetOrCreateTable<string>("Abc");
              tAbc.Put("aaa", "avalue");
              tAbc.Put("bbb", "bvalue");
              tAbc.Put("ccc", "cvalue");
              tAbc.Put("ddd", "cvalue");

              Assert.AreEqual(4, pile.ObjectCount);

              var cache2 = new LocalCache();
              cache2.Pile = pile;
              cache2.Configure(null);
              cache2.Start();
                
        
              var t2 = cache2.GetOrCreateTable<string>("A");
              t2.Put("aaa", "avalue");
              t2.Put("bbb", "bvalue");
        
              Assert.AreEqual(2, cache2.Count);
              Assert.AreEqual(6, pile.ObjectCount);

              cache.WaitForCompleteStop();
              Assert.AreEqual(NFX.ServiceModel.ControlStatus.Active, pile.Status);
              Assert.AreEqual(2, pile.ObjectCount);

              cache2.WaitForCompleteStop();
              Assert.AreEqual(NFX.ServiceModel.ControlStatus.Active, pile.Status);
              Assert.AreEqual(0, pile.ObjectCount);

              pile.WaitForCompleteStop();
              Assert.AreEqual(NFX.ServiceModel.ControlStatus.Inactive, pile.Status);
        }
        finally
        {
          pile.Dispose();
        }
      }
 /// <summary>
 /// Invoke the passed <see cref="IEntryProcessor"/> against the set
 /// of entries that are selected by the given <see cref="IFilter"/>,
 /// returning the result of the invocation for each.
 /// </summary>
 /// <remarks>
 /// <p>
 /// Unless specified otherwise, IInvocableCache implementations
 /// will perform this operation in two steps: (1) use the filter to
 /// retrieve a matching entry collection; (2) apply the agent to
 /// every filtered entry. This algorithm assumes that the agent's
 /// processing does not affect the result of the specified filter
 /// evaluation, since the filtering and processing could be
 /// performed in parallel on different threads.</p>
 /// <p>
 /// If this assumption does not hold, the processor logic has to be
 /// idempotent, or at least re-evaluate the filter. This could be
 /// easily accomplished by wrapping the processor with the
 /// <see cref="ConditionalProcessor"/>.</p>
 /// </remarks>
 /// <param name="filter">
 /// An <see cref="IFilter"/> that results in the collection of keys to
 /// be processed.
 /// </param>
 /// <param name="agent">
 /// The <see cref="IEntryProcessor"/> to use to process the specified
 /// keys.
 /// </param>
 /// <returns>
 /// A dictionary containing the results of invoking the
 /// <b>IEntryProcessor</b> against the keys that are selected by the
 /// given <b>IFilter</b>.
 /// </returns>
 public virtual IDictionary InvokeAll(IFilter filter, IEntryProcessor agent)
 {
     return(LocalCache.InvokeAll(filter, agent));
 }
 /// <summary>
 /// Invoke the passed <see cref="IEntryProcessor"/> against the
 /// entries specified by the passed keys, returning the result of the
 /// invocation for each.
 /// </summary>
 /// <param name="keys">
 /// The keys to process; these keys are not required to exist within
 /// the dictionary.
 /// </param>
 /// <param name="agent">
 /// The <b>IEntryProcessor</b> to use to process the specified keys.
 /// </param>
 /// <returns>
 /// A dictionary containing the results of invoking the
 /// <b>IEntryProcessor</b> against each of the specified keys.
 /// </returns>
 public virtual IDictionary InvokeAll(ICollection keys, IEntryProcessor agent)
 {
     return(LocalCache.InvokeAll(keys, agent));
 }
 /// <summary>
 /// Invoke the passed <see cref="IEntryProcessor"/> against the entry
 /// specified by the passed key, returning the result of the
 /// invocation.
 /// </summary>
 /// <param name="key">
 /// The key to process; it is not required to exist within the
 /// dictionary.
 /// </param>
 /// <param name="agent">
 /// The <b>IEntryProcessor</b> to use to process the specified key.
 /// </param>
 /// <returns>
 /// The result of the invocation as returned from the
 /// <b>IEntryProcessor</b>.
 /// </returns>
 public virtual object Invoke(object key, IEntryProcessor agent)
 {
     return(LocalCache.Invoke(key, agent));
 }
 /// <summary>
 /// Remove an index from this IQueryCache.
 /// </summary>
 /// <param name="extractor">
 /// The <see cref="IValueExtractor"/> object that is used to extract
 /// an indexable object from a value stored in the cache.
 /// </param>
 public virtual void RemoveIndex(IValueExtractor extractor)
 {
     LocalCache.RemoveIndex(extractor);
 }
Example #15
0
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UCOrganizationManager_DeleteEvent(object sender, EventArgs e)
        {
            try
            {
                List <string> listField = new List <string>();
                foreach (DataGridViewRow dr in dgvorganization.Rows)
                {
                    object isCheck = dr.Cells["colCheck"].EditedFormattedValue;
                    if (isCheck != null && (bool)isCheck)
                    {
                        listField.Add(dr.Cells["org_id"].Value.ToString());
                    }
                }
                if (listField.Count == 0)
                {
                    MessageBoxEx.Show("请选择删除记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                string tipMsg = "是否确认删除?";
                if (dsCom != null && dsCom.Tables[0] != null)
                {
                    //遍历要删除的组织ID
                    for (int i = 0; i < listField.Count; i++)
                    {
                        //查找组织ID的下级组织
                        DataRow[] drcom = dsCom.Tables[0].Select("parent_id='" + listField[i] + "'");
                        if (drcom != null && drcom.Length > 0)
                        {
                            //将下级组织也加入到要删除的列表中
                            listField.Add(drcom[0]["id"].ToString());
                        }
                    }
                }
                if (listField.Count > 0)
                {
                    tipMsg = "该组织存在下级组织,是否确认删除?";
                }
                if (MessageBoxEx.ShowQuestion(tipMsg))
                {
                    //DataSet dscom = GetComOrg();

                    Dictionary <string, string> comField = new Dictionary <string, string>();
                    comField.Add("enable_flag", "0");
                    bool flag = DBHelper.BatchUpdateDataByIn("批量删除组织", "tb_organization", comField, "org_id", listField.ToArray());
                    if (flag)
                    {
                        BindPageData();
                        if (dgvorganization.Rows.Count > 0)
                        {
                            dgvorganization.CurrentCell = dgvorganization.Rows[0].Cells[0];
                        }
                        MessageBoxEx.Show("删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LocalCache._Update(CacheList.Org);
                        MessageProcessor.UpdateComOrgInfo();
                    }
                    else
                    {
                        MessageBoxEx.Show("删除失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show("删除失败!" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Example #16
0
        public void T060_PileNonOwnership()
        {
            var pile = new DefaultPile();

            pile.Start();
            try
            {
                var cache = new LocalCache();
                cache.Pile = pile;
                cache.Configure(null);
                cache.Start();


                var tA = cache.GetOrCreateTable <string>("A");
                tA.Put("aaa", "avalue");
                tA.Put("bbb", "bvalue");
                Assert.AreEqual("avalue", tA.Get("aaa"));

                Assert.AreEqual(2, cache.Count);
                Assert.AreEqual(2, pile.ObjectCount);

                cache.WaitForCompleteStop();
                Assert.AreEqual(NFX.ServiceModel.ControlStatus.Inactive, cache.Status);

                Assert.AreEqual(NFX.ServiceModel.ControlStatus.Active, pile.Status);
                Assert.AreEqual(0, pile.ObjectCount);

                cache      = new LocalCache();
                cache.Pile = pile;
                cache.Configure(null);
                cache.Start();

                var tAbc = cache.GetOrCreateTable <string>("Abc");
                tAbc.Put("aaa", "avalue");
                tAbc.Put("bbb", "bvalue");
                tAbc.Put("ccc", "cvalue");
                tAbc.Put("ddd", "cvalue");

                Assert.AreEqual(4, pile.ObjectCount);

                var cache2 = new LocalCache();
                cache2.Pile = pile;
                cache2.Configure(null);
                cache2.Start();


                var t2 = cache2.GetOrCreateTable <string>("A");
                t2.Put("aaa", "avalue");
                t2.Put("bbb", "bvalue");

                Assert.AreEqual(2, cache2.Count);
                Assert.AreEqual(6, pile.ObjectCount);

                cache.WaitForCompleteStop();
                Assert.AreEqual(NFX.ServiceModel.ControlStatus.Active, pile.Status);
                Assert.AreEqual(2, pile.ObjectCount);

                cache2.WaitForCompleteStop();
                Assert.AreEqual(NFX.ServiceModel.ControlStatus.Active, pile.Status);
                Assert.AreEqual(0, pile.ObjectCount);

                pile.WaitForCompleteStop();
                Assert.AreEqual(NFX.ServiceModel.ControlStatus.Inactive, pile.Status);
            }
            finally
            {
                pile.Dispose();
            }
        }
Example #17
0
        public void DeleteSeveral_TwoTables_ByteArray(bool speed, int durationSec, int putMin, int putMax, int delFactor, int payloadSizeMin, int payloadSizeMax, bool isParallel)
        {
            using (var cache = new LocalCache())
              using (var pile = new DefaultPile(cache))
              {
            cache.Pile = pile;
            cache.PileAllocMode = speed ? AllocationMode.FavorSpeed : AllocationMode.ReuseSpace;
            cache.Start();

            var startTime = DateTime.UtcNow;
            var tasks = new List<Task>();
            for (var t = 0; t < (isParallel ? (System.Environment.ProcessorCount - 1) : 1); t++)
              tasks.Add(Task.Factory.StartNew(() =>
            {
              var list = new List<Tuple<int, GDID, int, byte, byte>>();
              var tA = cache.GetOrCreateTable<GDID>("A");
              var tB = cache.GetOrCreateTable<GDID>("B");
              ulong k = 0;
              var wlc = 0;

              while (true)
              {
                if ((DateTime.UtcNow - startTime).TotalSeconds >= durationSec) break;

                var putCount = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(putMin, putMax);
                for (int i = 0; i < putCount; i++)
                {
                  var payloadSize = NFX.ExternalRandomGenerator
                                      .Instance.NextScaledRandomInteger(payloadSizeMin, payloadSizeMax);
                  var val = new byte[payloadSize];
                  val[0] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;
                  val[payloadSize - 1] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;

                  var tableId = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, 1);
                  var table = tableId == 0 ? tA : tB;
                  var key = new GDID((uint)Thread.CurrentThread.ManagedThreadId, k);

                  table.Put(key, val);

                  list.Add(new Tuple<int, GDID, int, byte, byte>(tableId, key, payloadSize - 1, val[0], val[payloadSize - 1]));
                  k++;
                }

                int delCount = putCount / delFactor;
                for (int i = 0; i < delCount; i++)
                {
                  while (true && list.Count > 0)
                  {
                    var idx = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, list.Count - 1);
                    var element = list[idx];
                    var table = element.Item1 == 0 ? tA : tB;
                    var key = element.Item2;

                    var removed = table.Remove(key);
                    list.RemoveAt(idx);
                    if (removed)
                      break;
                  }
                }

                // get several random elements
                if (list.Count > 64 && NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, 100) > 98)
                {
                  var toRead = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(8, 64);
                  wlc++;
                  if (wlc % 125 == 0)
                    Console.WriteLine("Thread {0} is reading {1} elements"
                      .Args(Thread.CurrentThread.ManagedThreadId, toRead));
                  for (var j = 0; j < toRead && list.Count > 0; j++)
                  {
                    var idx = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, list.Count - 1);
                    var element = list[idx];
                    var table = element.Item1 == 0 ? tA : tB;
                    var key = element.Item2;

                    var buf = table.Get(key) as byte[];
                    if (buf == null)
                    {
                      list.RemoveAt(idx);
                      continue;
                    }
                    Assert.AreEqual(element.Item4, buf[0]);
                    Assert.AreEqual(element.Item5, buf[element.Item3]);
                  }
                }

                if (list.Count == Int32.MaxValue)
                  list = new List<Tuple<int, GDID, int, byte, byte>>();
              }

              // total check
              Console.WriteLine("Thread {0} is doing final read of {1} elements".Args(Thread.CurrentThread.ManagedThreadId, list.Count));
              foreach (var element in list)
              {
                var table = element.Item1 == 0 ? tA : tB;
                var val = table.Get(element.Item2) as byte[];
                if (val == null)
                  continue;
                Assert.AreEqual(element.Item4, val[0]);
                Assert.AreEqual(element.Item5, val[element.Item3]);
              }
              return;
            }, TaskCreationOptions.LongRunning));
            Task.WaitAll(tasks.ToArray());
              }
        }
 /// <summary>
 /// Instances a new <see cref="RouteMappingDoubleBufferQueue"/>.
 /// </summary>
 public RouteMappingDoubleBufferQueue()
 {
     m_onStatusMessage = x => { };
     m_onProcessException = x => { };
     m_globalCache = new GlobalCache(new Dictionary<IAdapter, Consumer>(), 0);
     m_injectMeasurementsLocalCache = new LocalCache(this, null);
 }
 /// <summary>
 /// Perform an aggregating operation against the entries specified by
 /// the passed keys.
 /// </summary>
 /// <param name="keys">
 /// The collection of keys that specify the entries within this cache
 /// to aggregate across.
 /// </param>
 /// <param name="agent">
 /// The <see cref="IEntryAggregator"/> that is used to aggregate
 /// across the specified entries of this dictionary.
 /// </param>
 /// <returns>
 /// The result of the aggregation.
 /// </returns>
 public virtual object Aggregate(ICollection keys, IEntryAggregator agent)
 {
     return(LocalCache.Aggregate(keys, agent));
 }
        public PostProcessing(IHttpClientFactory clientFactory, ILogger <PostProcessing> logger, LocalCache localCache, IOptions <ProcessingOptions> options)
        {
            _clientFactory = clientFactory;
            _logger        = logger;
            _saveReport    = options.Value.SaveReport;

            _lazyReportDir = new Lazy <string>(() =>
            {
                var reportDir = Path.Combine(localCache.LocalRootName, "Reports");

                // ensure the directory is exists
                Directory.CreateDirectory(reportDir);

                return(reportDir);
            });
        }
 /// <summary>
 /// Perform an aggregating operation against the collection of
 /// entries that are selected by the given <b>IFilter</b>.
 /// </summary>
 /// <param name="filter">
 /// an <see cref="IFilter"/> that is used to select entries within
 /// this cache to aggregate across.
 /// </param>
 /// <param name="agent">
 /// The <see cref="IEntryAggregator"/> that is used to aggregate
 /// across the selected entries of this dictionary.
 /// </param>
 /// <returns>
 /// The result of the aggregation.
 /// </returns>
 public virtual object Aggregate(IFilter filter, IEntryAggregator agent)
 {
     return(LocalCache.Aggregate(filter, agent));
 }
Example #22
0
      public void T040_PileOwnership()
      {
        var cache = new LocalCache();
        cache.Pile = new DefaultPile(cache);
        cache.Configure(null);
        cache.Start();
                
        
        var tA = cache.GetOrCreateTable<string>("A");
        tA.Put("aaa", "avalue");
        Assert.AreEqual("avalue", tA.Get("aaa"));

        cache.WaitForCompleteStop();
        Assert.AreEqual(NFX.ServiceModel.ControlStatus.Inactive, cache.Status);
        Assert.AreEqual(NFX.ServiceModel.ControlStatus.Inactive, cache.Pile.Status);
      }
 /// <summary>
 /// Construct the LocalNamedCache.
 /// </summary>
 public LocalNamedCache()
 {
     m_localCache = new LocalCache();
 }
Example #24
0
 public CacheService()
 {
     Cache = new LocalCache();
 }
 /// <summary>
 /// Construct the LocalNamedCache.
 /// </summary>
 /// <param name="units">
 /// The number of units that the underlying <b>LocalCache</b> will
 /// cache before pruning the cache.
 /// </param>
 public LocalNamedCache(int units)
 {
     m_localCache = new LocalCache(units);
 }
 /// <summary>
 /// Returns an <see cref="ICacheEnumerator"/> object for the
 /// <b>ICache</b> instance.
 /// </summary>
 /// <returns>An <b>ICacheEnumerator</b> object for the
 /// <b>ICache</b> instance.</returns>
 ICacheEnumerator ICache.GetEnumerator()
 {
     return(LocalCache.GetEnumerator());
 }
 /// <summary>
 /// Construct the LocalNamedCache.
 /// </summary>
 /// <param name="units">
 /// The number of units that the underlying <b>LocalCache</b> will
 /// cache before pruning the cache.
 /// </param>
 /// <param name="expiryMillis">
 /// The number of milliseconds that each cache entry lives before
 /// being automatically expired.
 /// </param>
 public LocalNamedCache(int units, int expiryMillis)
 {
     m_localCache = new LocalCache(units, expiryMillis);
 }
 /// <summary>
 /// Adds an element with the provided key and value to the
 /// <b>IDictionary</b> object.
 /// </summary>
 public virtual void Add(object key, object value)
 {
     LocalCache.Add(key, value);
 }
 /// <summary>
 /// Construct the LocalNamedCache.
 /// </summary>
 /// <param name="units">
 /// The number of units that the underlying <b>LocalCache</b> will
 /// cache before pruning the cache.
 /// </param>
 /// <param name="expiryMillis">
 /// The number of milliseconds that each cache entry lives before
 /// being automatically expired.
 /// </param>
 /// <param name="pruneLevel">
 /// The percentage of the total number of units that will remain
 /// after the underlying <b>LocalCache</b> prunes the cache (i.e.
 /// this is the "low water mark" value); this value is in the range
 /// 0.0 to 1.0.
 /// </param>
 public LocalNamedCache(int units, int expiryMillis, double pruneLevel)
 {
     m_localCache = new LocalCache(units, expiryMillis, pruneLevel);
 }
 /// <summary>
 /// Returns an <b>IDictionaryEnumerator</b> object for the
 /// <b>IDictionary</b> object.
 /// </summary>
 /// <returns>
 /// An <b>IDictionaryEnumerator</b> object for the <b>IDictionary</b>
 /// object.
 /// </returns>
 IDictionaryEnumerator IDictionary.GetEnumerator()
 {
     return(LocalCache.GetEnumerator());
 }
 /// <summary>
 /// Construct the LocalNamedCache.
 /// </summary>
 /// <param name="units">
 /// The number of units that the underlying <b>LocalCache</b> will
 /// cache before pruning the cache.
 /// </param>
 /// <param name="expiryMillis">
 /// The number of milliseconds that each cache entry lives before
 /// being automatically expired.
 /// </param>
 /// <param name="loader">
 /// The <see cref="ICacheLoader"/> or <see cref="ICacheStore"/> to
 /// use.
 /// </param>
 public LocalNamedCache(int units, int expiryMillis, ICacheLoader loader)
 {
     m_localCache = new LocalCache(units, expiryMillis, loader);
 }
Example #32
0
        public void Chessboard_ByteArray(bool speed, int durationSec, int payloadSizeMin, int payloadSizeMax, bool isParallel)
        {
            using (var cache = new LocalCache())
              using (var pile = new DefaultPile(cache))
              {
            cache.Pile = pile;
            cache.PileAllocMode = speed ? AllocationMode.FavorSpeed : AllocationMode.ReuseSpace;
            cache.Start();

            var startTime = DateTime.UtcNow;
            var tasks = new List<Task>();
            for (var t = 0; t < (isParallel ? (System.Environment.ProcessorCount - 1) : 1); t++)
              tasks.Add(Task.Factory.StartNew(() =>
            {
              var list = new List<CheckByteArray>();
              var i = 0;
              var tA = cache.GetOrCreateTable<GDID>("A");
              var wlc = 0;
              while (true)
              {
                if ((DateTime.UtcNow - startTime).TotalSeconds >= durationSec) break;

                var payloadSize = NFX.ExternalRandomGenerator
                                    .Instance.NextScaledRandomInteger(payloadSizeMin, payloadSizeMax);
                var val = new byte[payloadSize];
                val[0] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;
                val[payloadSize - 1] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;

                var key = new GDID((uint)Thread.CurrentThread.ManagedThreadId, (ulong)i);
                tA.Put(key, val);

                var element = new CheckByteArray(key, payloadSize - 1, val[0], val[payloadSize - 1]);
                list.Add(element);

                // delete previous element
                if (list.Count > 1 && i % 2 == 0)
                {
                  key = list[list.Count - 2].Key;
                  tA.Remove(key);
                  list.RemoveAt(list.Count - 2);
                }

                // get several random elements
                if (list.Count > 64 && NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, 100) > 98)
                {
                  var toRead = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(8, 64);
                  wlc++;
                  if (wlc % 125 == 0)
                    Console.WriteLine("Thread {0} is reading {1} elements, total {2}"
                      .Args(Thread.CurrentThread.ManagedThreadId, toRead, list.Count));
                  for (var k = 0; k < toRead && list.Count > 0; k++)
                  {
                    var idx = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, list.Count - 1);
                    element = list[idx];
                    var buf = tA.Get(element.Key) as byte[];
                    if (buf == null)
                    {
                      list.RemoveAt(idx);
                      continue;
                    }
                    Assert.AreEqual(element.FirstByte, buf[0]);
                    Assert.AreEqual(element.LastByte, buf[element.IdxLast]);
                  }
                }

                if (i == Int32.MaxValue)
                  i = 0;
                else
                  i++;

                if (list.Count == Int32.MaxValue)
                  list = new List<CheckByteArray>();
              }

              // total check
              Console.WriteLine("Thread {0} is doing final read of {1} elements, tableCount {2}"
                .Args(Thread.CurrentThread.ManagedThreadId, list.Count, tA.Count));
              foreach (var element in list)
              {
                var buf = tA.Get(element.Key) as byte[];
                if (buf == null)
                  continue;
                Assert.AreEqual(element.FirstByte, buf[0]);
                Assert.AreEqual(element.LastByte, buf[element.IdxLast]);
              }
              return;
            }, TaskCreationOptions.LongRunning));
            Task.WaitAll(tasks.ToArray());
              }
        }
 /// <summary>
 /// Add a standard cache listener that will receive all events
 /// (inserts, updates, deletes) that occur against the cache, with
 /// the key, old-value and new-value included.
 /// </summary>
 /// <remarks>
 /// This has the same result as the following call:
 /// <pre>
 /// AddCacheListener(listener, (IFilter) null, false);
 /// </pre>
 /// </remarks>
 /// <param name="listener">
 /// The <see cref="ICacheListener"/> to add.
 /// </param>
 public virtual void AddCacheListener(ICacheListener listener)
 {
     LocalCache.AddCacheListener(listener);
 }
Example #34
0
        public void NoGrowth_ByteArray(bool speed, int durationSec, int payloadSizeMin, int payloadSizeMax, int countMin, int countMax)
        {
            using (var cache = new LocalCache())
              using (var pile = new DefaultPile(cache))
              {
            cache.Pile = pile;
            cache.PileAllocMode = speed ? AllocationMode.FavorSpeed : AllocationMode.ReuseSpace;
            cache.Start();

            var startTime = DateTime.UtcNow;
            var tasks = new List<Task>();
            for (var t = 0; t < (System.Environment.ProcessorCount - 1); t++)
              tasks.Add(Task.Factory.StartNew(() =>
            {
              var tA = cache.GetOrCreateTable<GDID>("A");
              var list = new List<CheckByteArray>();
              bool put = true;

              while (true)
              {
                if ((DateTime.UtcNow - startTime).TotalSeconds >= durationSec) return;

                if (put)
                {
                  var cnt = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(countMin, countMax);
                  for (int i = 0; i < cnt; i++)
                  {
                    var payloadSize = NFX.ExternalRandomGenerator
                                        .Instance.NextScaledRandomInteger(payloadSizeMin, payloadSizeMax);
                    var val = new byte[payloadSize];
                    val[0] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;
                    val[payloadSize - 1] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;
                    var key = new GDID((uint)Thread.CurrentThread.ManagedThreadId, (ulong)i);

                    tA.Put(key, val);

                    var element = new CheckByteArray(key, payloadSize - 1, val[0], val[payloadSize - 1]);
                    list.Add(element);
                  }
                  Console.WriteLine("Thread {0} put {1} objects".Args(Thread.CurrentThread.ManagedThreadId, list.Count));
                  put = false;
                }
                else
                {
                  var i = 0;
                  for (var j = 0; j < list.Count; j++)
                  {
                    var element = list[j];
                    var buf = tA.Get(element.Key) as byte[];
                    if (buf != null)
                    {
                      Assert.AreEqual(element.FirstByte, buf[0]);
                      Assert.AreEqual(element.LastByte, buf[element.IdxLast]);
                      tA.Remove(element.Key);
                      i++;
                    }
                  }
                  Console.WriteLine("Thread {0} deleted {1} objects".Args(Thread.CurrentThread.ManagedThreadId, i));
                  list.Clear();
                  put = true;
                }
              }
            }, TaskCreationOptions.LongRunning));
            Task.WaitAll(tasks.ToArray());
              }
        }
 /// <summary>
 /// Add a cache listener for a specific key.
 /// </summary>
 /// <remarks>
 /// <p>
 /// The listeners will receive <see cref="CacheEventArgs"/> objects,
 /// but if <paramref name="isLite"/> is passed as <b>true</b>, they
 /// <i>might</i> not contain the
 /// <see cref="CacheEventArgs.OldValue"/> and
 /// <see cref="CacheEventArgs.NewValue"/> properties.</p>
 /// <p>
 /// To unregister the ICacheListener, use the
 /// <see cref="IObservableCache.RemoveCacheListener(ICacheListener,object)"/>
 /// method.</p>
 /// </remarks>
 /// <param name="listener">
 /// The <see cref="ICacheListener"/> to add.
 /// </param>
 /// <param name="key">
 /// The key that identifies the entry for which to raise events.
 /// </param>
 /// <param name="isLite">
 /// <b>true</b> to indicate that the <see cref="CacheEventArgs"/>
 /// objects do not have to include the <b>OldValue</b> and
 /// <b>NewValue</b> property values in order to allow optimizations.
 /// </param>
 public virtual void AddCacheListener(ICacheListener listener, object key, bool isLite)
 {
     LocalCache.AddCacheListener(listener, key, isLite);
 }
        public void LocalCache_will_store_to_cache_if_content_type_not_already_added()
        {
            // Arrange
            var storageHandler = new Mock<IStorageHandler<Content>>();
            storageHandler.Setup(x => x.WriteToStorage(It.IsAny<ContentTypes>(), It.IsAny<Content>()));
            var cache = new LocalCache<Content>(storageHandler.Object);
            var footerContent = new Content
            {
                Sections = new List<ContentSection>
                {
                    new ContentSection
                    {
                        Id = ContentTypes.Footer.ToString(),
                        Html = "<div id='footer' />"
                    }
                }
            };

            // Act
            cache.WriteToCache(ContentTypes.Footer, footerContent, DateTime.Now);

            // Assert
            storageHandler.Verify(x => x.WriteToStorage(It.IsAny<ContentTypes>(), It.IsAny<Content>()), Times.Once);
        }
Example #37
0
 public MemoryNetworkCache(long max_cache_size)
 {
     heap_cache = new LocalCache(Cache.ClosestPrime(4096), max_cache_size);
     s2block_cache = new Dictionary<long, BlockCacheElement>(1024);
 }
 /// <summary>
 /// Remove a cache listener that previously signed up for events
 /// about a specific key.
 /// </summary>
 /// <param name="listener">
 /// The listener to remove.
 /// </param>
 /// <param name="key">
 /// The key that identifies the entry for which to raise events.
 /// </param>
 public virtual void RemoveCacheListener(ICacheListener listener, object key)
 {
     LocalCache.RemoveCacheListener(listener, key);
 }
Example #39
0
 public MbapMapper(string name)
 {
     cache = new LocalCache(name);
 }
        public void LocalCache_will_store_to_cache_if_content_type_exists_with_older_refresh_time()
        {
            // Arrange
            var storageHandler = new Mock<IStorageHandler<Content>>();

            storageHandler.Setup(x => x.WriteToStorage(It.IsAny<ContentTypes>(), It.IsAny<Content>()));
            var cache = new LocalCache<Content>(storageHandler.Object);

            var oldFooterContent = new Content
            {
                Sections = new List<ContentSection>
                {
                    new ContentSection
                    {
                        Id = ContentTypes.Footer.ToString(),
                        Html = "<div id='footer' />"
                    }
                },
                RefreshDate = new DateTime(2014, 07, 07)
            };

            var newFooterContent = new Content
            {
                Sections = new List<ContentSection>
                {
                    new ContentSection
                    {
                        Id = ContentTypes.Footer.ToString(),
                        Html = "<div id='footer'>footer</div>"
                    }
                },
                RefreshDate = new DateTime(2014, 07, 08)
            };

            // Act
            cache.WriteToCache(ContentTypes.Footer, oldFooterContent, oldFooterContent.RefreshDate);
            cache.WriteToCache(ContentTypes.Footer, newFooterContent, newFooterContent.RefreshDate);

            // Assert
            storageHandler.Verify(x => x.WriteToStorage(It.IsAny<ContentTypes>(), It.IsAny<Content>()), Times.Exactly(2));
        }
 /// <summary>
 /// Add a cache listener that receives events based on a filter
 /// evaluation.
 /// </summary>
 /// <remarks>
 /// <p>
 /// The listeners will receive <see cref="CacheEventArgs"/> objects,
 /// but if <paramref name="isLite"/> is passed as <b>true</b>, they
 /// <i>might</i> not contain the <b>OldValue</b> and <b>NewValue</b>
 /// properties.</p>
 /// <p>
 /// To unregister the <see cref="ICacheListener"/>, use the
 /// <see cref="IObservableCache.RemoveCacheListener(ICacheListener,IFilter)"/>
 /// method.</p>
 /// </remarks>
 /// <param name="listener">
 /// The <see cref="ICacheListener"/> to add.</param>
 /// <param name="filter">
 /// A filter that will be passed <b>CacheEventArgs</b> objects to
 /// select from; a <b>CacheEventArgs</b> will be delivered to the
 /// listener only if the filter evaluates to <b>true</b> for that
 /// <b>CacheEventArgs</b>; <c>null</c> is equivalent to a filter
 /// that alway returns <b>true</b>.
 /// </param>
 /// <param name="isLite">
 /// <b>true</b> to indicate that the <see cref="CacheEventArgs"/>
 /// objects do not have to include the <b>OldValue</b> and
 /// <b>NewValue</b> property values in order to allow optimizations.
 /// </param>
 public virtual void AddCacheListener(ICacheListener listener, IFilter filter, bool isLite)
 {
     LocalCache.AddCacheListener(listener, filter, isLite);
 }
 /// <summary>
 /// Remove a cache listener that previously signed up for events
 /// based on a filter evaluation.
 /// </summary>
 /// <param name="listener">
 /// The <see cref="ICacheListener"/> to remove.
 /// </param>
 /// <param name="filter">
 /// A filter used to evaluate events; <c>null</c> is equivalent to a
 /// filter that alway returns <b>true</b>.
 /// </param>
 public virtual void RemoveCacheListener(ICacheListener listener, IFilter filter)
 {
     LocalCache.RemoveCacheListener(listener, filter);
 }
 /// <summary>
 /// Get the values for all the specified keys, if they are in the
 /// cache.
 /// </summary>
 /// <remarks>
 /// <p>
 /// For each key that is in the cache, that key and its corresponding
 /// value will be placed in the dictionary that is returned by this
 /// method. The absence of a key in the returned dictionary indicates
 /// that it was not in the cache, which may imply (for caches that
 /// can load behind the scenes) that the requested data could not be
 /// loaded.</p>
 /// <p>
 /// The result of this method is defined to be semantically the same
 /// as the following implementation, without regards to threading
 /// issues:</p>
 /// <pre>
 /// IDictionary dict = new AnyDictionary();
 /// // could be a Hashtable (but does not have to)
 /// foreach (object key in colKeys)
 /// {
 ///     object value = this[key];
 ///     if (value != null || Contains(key))
 ///     {
 ///         dict[key] = value;
 ///     }
 /// }
 /// return dict;
 /// </pre>
 /// </remarks>
 /// <param name="keys">
 /// A collection of keys that may be in the named cache.
 /// </param>
 /// <returns>
 /// A dictionary of keys to values for the specified keys passed in
 /// <paramref name="keys"/>.
 /// </returns>
 public virtual IDictionary GetAll(ICollection keys)
 {
     return(LocalCache.GetAll(keys));
 }
Example #44
0
 private static LocalCache makeCache()
 {
     var cache = new LocalCache();
        cache.Pile = new DefaultPile(cache);
        cache.Configure(null);
        cache.Start();
        return cache;
 }
 /// <summary>
 /// Associates the specified value with the specified key in this
 /// cache.
 /// </summary>
 /// <remarks>
 /// <p>
 /// If the cache previously contained a mapping for this key, the old
 /// value is replaced.</p>
 /// <p>
 /// Invoking this method is equivalent to the following call:
 /// <pre>
 /// Insert(key, value, CacheExpiration.Default);
 /// </pre></p>
 /// </remarks>
 /// <param name="key">
 /// Key with which the specified value is to be associated.
 /// </param>
 /// <param name="value">
 /// Value to be associated with the specified key.
 /// </param>
 /// <returns>
 /// Previous value associated with specified key, or <c>null</c> if
 /// there was no mapping for key. A <c>null</c> return can also
 /// indicate that the dictionary previously associated <c>null</c>
 /// with the specified key, if the implementation supports
 /// <c>null</c> values.
 /// </returns>
 public virtual object Insert(object key, object value)
 {
     return(LocalCache.Insert(key, value));
 }
Example #46
0
      public void T050_PileNonOwnershipErrorStart()
      {
        var pile = new DefaultPile();

        try
        {
          var cache = new LocalCache();
          cache.Pile = pile;
          cache.Configure(null);
          cache.Start();  //can not start cache that uses inactive pile which is not managed by this cache
        }
        finally
        {
          pile.Dispose();
        }
                
      }
 /// <summary>
 /// Associates the specified value with the specified key in this
 /// cache.
 /// </summary>
 /// <remarks>
 /// <p>
 /// If the cache previously contained a mapping for this key, the old
 /// value is replaced.</p>
 /// This variation of the <see cref="ICache.Insert(object,object)"/>
 /// method allows the caller to specify an expiry (or "time to live")
 /// for the cache entry.
 /// </remarks>
 /// <param name="key">
 /// Key with which the specified value is to be associated.
 /// </param>
 /// <param name="value">
 /// Value to be associated with the specified key.
 /// </param>
 /// <param name="millis">
 /// The number of milliseconds until the cache entry will expire,
 /// also referred to as the entry's "time to live"; pass
 /// <see cref="CacheExpiration.DEFAULT"/> to use the cache's
 /// default time-to-live setting; pass
 /// <see cref="CacheExpiration.NEVER"/> to indicate that the
 /// cache entry should never expire; this milliseconds value is
 /// <b>not</b> a date/time value, but the amount of time object will
 /// be kept in the cache.
 /// </param>
 /// <returns>
 /// Previous value associated with specified key, or <c>null</c> if
 /// there was no mapping for key. A <c>null</c> return can also
 /// indicate that the cache previously associated <c>null</c> with
 /// the specified key, if the implementation supports <c>null</c>
 /// values.
 /// </returns>
 /// <exception cref="NotSupportedException">
 /// If the requested expiry is a positive value and the
 /// implementation does not support expiry of cache entries.
 /// </exception>
 public virtual object Insert(object key, object value, long millis)
 {
     return(LocalCache.Insert(key, value, millis));
 }
Example #48
0
 private LocalCache makeCache(IConfigSectionNode conf = null)
 {
    var cache = new LocalCache();
    cache.Pile = new DefaultPile(cache);
    cache.Configure( conf );
    cache.Start();
    return cache;
 }
Example #49
0
 /// <summary>
 /// Gets a handler for measurements that routes measurements to the appropriate consumers.
 /// </summary>
 /// <returns>The measurement handler used for routing.</returns>
 public virtual EventHandler<EventArgs<ICollection<IMeasurement>>> GetRoutedMeasurementsHandler()
 {
     LocalCache localCache = new LocalCache(this);
     return (sender, args) => localCache.Route(args.Argument);
 }