Ejemplo n.º 1
0
        public Task <IList <Country> > GetAll()
        {
            IList <Country> res = _cache.Get("contries") as IList <Country>;

            if (res != null)
            {
                return(Task.FromResult(res));
            }
            else
            {
                var cnt = Task.Run(() => _repository.GetAll().Result);
                _cache.Add("contries", cnt.Result);
                return(cnt);
            }
        }
        /// <summary>
        /// Get the categories in the group specified as nodes.
        /// </summary>
        /// <param name="group">The group the node belong in. e.g. "Posts", or "Events"</param>
        /// <param name="allCategories">If true, get all categories in node structure(parent, child), false, gets only parent level node.</param>
        /// <returns></returns>
        public static Node <Category> ToNodes(string group, bool allCategories)
        {
            string key = "category_nodes_" + group;
            Func <Node <Category> > fetcher = () =>
            {
                IList <Category> categories = null;
                // Get all the categories.
                if (allCategories)
                {
                    categories = Category.Find(Query <Category> .New().Where(c => c.Group).Is(group).OrderBy(c => c.ParentId).OrderBy(c => c.SortIndex));
                }
                else
                {
                    categories = Category.Find(Query <Category> .New().Where(c => c.Group).Is(group).And(c => c.ParentId).Is(0).OrderBy(c => c.SortIndex));
                }

                var nodes = Node <Category> .ToNodes <Category>(categories);

                return(nodes);
            };
            Node <Category> groupNodes = Cacher.Get <Node <Category> >(key, 300, fetcher);

            if (groupNodes == null || !groupNodes.HasChildren)
            {
                groupNodes = fetcher();
                Cacher.Insert(key, groupNodes, 300, false);
            }

            return(groupNodes);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 得到缓存数据
        /// </summary>
        /// <param name="searchQuery"></param>
        protected virtual SearchResultInfo GetSearchResultByCache(SearchQueryInfo searchQuery)
        {
            var name    = string.Format("{0}_{1}_{2}", searchQuery.Key, searchQuery.PageIndex, searchQuery.PageSize);
            var builder = new StringBuilder(name);

            if (searchQuery.Conditions != null)
            {
                foreach (var condition in searchQuery.Conditions)
                {
                    builder.AppendFormat("{0}{1}", condition.Key, condition.Value);
                }
            }
            searchQuery.CacheKey = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(builder.ToString(), "MD5");
            searchQuery.CacheKey = string.Format("{0}{1}_{2}_{3}", CacheTag, searchQuery.Name, searchQuery.Key, searchQuery.CacheKey);
            var result = Cacher.Get <SearchResultInfo>(searchQuery.CacheKey);

            lock (KeyLocker)
            {
                if (result == null)
                {
                    result = GetSearchResultByFind(searchQuery);
                    if (searchQuery.TimeSpan > 0)
                    {
                        Cacher.Set(searchQuery.CacheKey, result, searchQuery.TimeSpan);
                    }
                    else if (searchQuery.CecheTime.HasValue)
                    {
                        Cacher.Set(searchQuery.CacheKey, result, searchQuery.CecheTime.Value);
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Render utility method.
        /// </summary>
        /// <param name="renderer"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public string TryRender(Func <string> renderer, string errorMessage = "")
        {
            string html = string.Empty;

            if (string.IsNullOrEmpty(errorMessage))
            {
                errorMessage = string.Format("Unable to render widget: {0}, {1}, {2}", this.Id, this.DefName, this.GetType().Name);
            }

            try
            {
                string cachekey     = "W_" + this.DefName + "_" + this.Id;
                bool   cacheEnabled = false;
                int    cacheTime    = 10;
                if (this is IEntityCachable)
                {
                    IEntityCachable wc = (IEntityCachable)this;
                    cacheEnabled = wc.CacheEnabled;
                    cacheTime    = wc.CacheTime;
                }
                html = Cacher.Get <string>(cachekey, cacheEnabled, cacheTime.Time(), renderer);
            }
            catch (Exception ex)
            {
                Logging.Logger.Error(errorMessage, ex);
                html = errorMessage;
            }
            return(html);
        }
        /// <summary>
        /// Get all the countries in JSON format.
        /// </summary>
        /// <returns></returns>
        public ActionResult Countries()
        {
            var countries = Cacher.Get <IList <Country> >("countries_list", 300, () => Location.Countries.GetAll().Where(c => !c.IsAlias && c.IsActive).ToList());

            string[] countrynames = countries.Select <Country, string>(c => c.Name).ToArray();
            return(Json(new { Success = true, Message = string.Empty, Data = countrynames }, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 移除公共缓存
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="key"></param>
        protected virtual void RemoveCommonCache(OrmObjectInfo obj, object key)
        {
            var cacheKey   = GetEntityCacheKey(obj, key);
            var cacheValue = Cacher.Get(cacheKey, Type.GetType(obj.ObjectName));

            if (cacheValue == null)
            {
                return;
            }
            if (obj.IsCache)
            {
                Cacher.Remove(cacheKey);
            }
            var ormMaps =
                obj.Properties.Where(it => it.Map != null && it.Map.IsRemoveCache)
                .Select(it => it.Map).ToList();

            if (ormMaps.Count == 0)
            {
                return;
            }
            foreach (var ormMap in ormMaps)
            {
                var value = cacheValue.GetProperty(ormMap.ObjectProperty.PropertyName);
                if (!obj.IsCache)
                {
                    Cacher.Remove(cacheKey);
                }
                RemoveCommonCache(ormMap.GetMapObject(), value);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Get recent blogposts.
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public static IList <Post> GetRecent(int count)
        {
            var recents = Cacher.Get <IList <Post> >("Posts_Recent", Settings.CacheOnRecent, Settings.CacheTime.Seconds(), () =>
                                                     Find(Query <Post> .New().Limit(count).Where(p => p.IsPublished).Is(true)
                                                          .OrderByDescending(p => p.PublishDate)));

            return(recents);
        }
Ejemplo n.º 8
0
        public void ReturnsFuncResult()
        {
            //Arrange
            //Act
            string value = Cacher.Get(key, () => "value");

            //Assert
            value.Should().Be("value");
        }
Ejemplo n.º 9
0
        public void FirstCallThrowsException()
        {
            //Assemble
            //Act
            Action act = () => Cacher.Get <string>(key, () => { throw new Exception("test"); });

            //Assert
            act.ShouldThrow <Exception>().WithMessage("test");
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Do cache example.
        /// </summary>
        public void DoCache()
        {
            Cacher.Insert("sampledata", "http://www.knowledgedrink.com");
            string cacheObject = Cacher.Get <string>("sampledata");

            Logger.Info("====================================================");
            Logger.Info("CACHE ");
            Logger.Info("Obtained from cache : '" + cacheObject + "'");
            Logger.Info(Environment.NewLine);
        }
Ejemplo n.º 11
0
        public void ReturnsCurrentlyCachedValue()
        {
            //Arrange

            //Act
            string value = Cacher.Get(key, () => taskCompletion.Task.Result);

            //Assert
            value.Should().Be(key);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Get the pages to show in the front/menu header.
        /// </summary>
        /// <returns></returns>
        public static IList <MenuEntry> FrontPages()
        {
            // Next version will have Query<T> so it's more convenient than
            // using <T> on each Where<T> And<T> OrderBy<T>
            var items = Cacher.Get <IList <MenuEntry> >(CacheKeyForFrontPages, Settings.CacheOn, Settings.CacheTime.Seconds(), () =>
                                                        Find(Query <MenuEntry> .New().Where(m => m.ParentItem).Is(string.Empty)
                                                             .And(m => m.IsPublic).Is(true)
                                                             .OrderBy(m => m.SortIndex)));

            return(items);
        }
Ejemplo n.º 13
0
        public void SecondaryCallsKeepsCurrentValue()
        {
            // Assemble
            //Act
            string firstResult  = Cacher.Get(key, () => "1");
            string secondResult = Cacher.Get <string>(key, () => { throw new Exception("failed"); });
            string lastResult   = Cacher.Get(key, () => "last");

            //Assert
            lastResult.Should().Be(firstResult).And.Be(secondResult);
        }
Ejemplo n.º 14
0
        public void TestSetup()
        {
            taskCompletion = new TaskCompletionSource <string>();

            Cacher.Remove(key);

            //Set cache value
            Cacher.Get(key, () => key, TimeSpan.FromMilliseconds(10));

            // Make it expired
            Clock.UtcNow = () => DateTime.UtcNow.AddMinutes(1);
        }
Ejemplo n.º 15
0
        public void RefreshesValueInBackgroundThread()
        {
            //Arrange

            //Act
            string value = Cacher.Get(key, () => taskCompletion.Task.Result);

            //Assert
            value.Should().Be(key);

            taskCompletion.SetResult("newValue");
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Return a datatable of the year/month count groupings.
        /// </summary>
        /// <example>
        /// e.g.
        /// 2009, January,  4
        /// 2009, February, 2
        /// 2009, May,      6
        /// </example>
        /// <returns></returns>
        public static DataTable GetArchives()
        {
            var archives = Cacher.Get <DataTable>("Posts_Archive", Settings.CacheOnArchives, Settings.CacheTime.Seconds(), () =>
            {
                var repo         = Post.Repository;
                DataTable groups = repo.Group(Query <Post> .New().Where(p => p.IsPublished).Is(true)
                                              .OrderByDescending(p => p.Year).OrderBy(p => p.Month), "Year", "Month");
                return(groups);
            });

            return(archives);
        }
Ejemplo n.º 17
0
        public void CacheEntryIsRemoved()
        {
            //Arrange
            var key = "removeKey";

            Cacher.Get(key, () => "value");

            //Act
            Cacher.Remove(key);

            //Assert
            Cacher.Get(key, () => "newValue").Should().Be("newValue");
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Get a dictionary of id's to categorys that are associated w/ the TEntity.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public static LookupMulti <Category> LookupFor <TEntity>()
        {
            string key    = "category_lookup_" + typeof(TEntity).Name;
            var    lookup = Cacher.Get <LookupMulti <Category> >(key, 300, () => LookupForInternal <TEntity>());

            if (lookup == null || lookup.Lookup1.Count == 0)
            {
                lookup = LookupForInternal <TEntity>();
                Cacher.Insert(key, lookup, 300, false);
            }

            return(lookup);
        }
Ejemplo n.º 19
0
        private T GetCachedLookup <T>(string key, bool enableCache, int cacheTime, Func <T> fetcher, Func <T, bool> check)
        {
            var latestitems = Cacher.Get <T>(key, enableCache, cacheTime, false, () => fetcher());

            if (check(latestitems))
            {
                latestitems = fetcher();
                if (enableCache)
                {
                    Cacher.Insert(key, latestitems, cacheTime, false);
                }
            }
            return(latestitems);
        }
Ejemplo n.º 20
0
        private IList <T> GetCached <T>(string key, bool enableCache, int cacheTime, Func <IList <T> > fetcher)
        {
            var latestitems = Cacher.Get <IList <T> >(key, enableCache, cacheTime, false, () => fetcher());

            if (latestitems == null || latestitems.Count == 0)
            {
                latestitems = fetcher();
                if (enableCache && latestitems != null && latestitems.Count > 0)
                {
                    Cacher.Insert(key, latestitems, cacheTime, false);
                }
            }
            return(latestitems);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Get all the pages that are "FrontPages" and should appear on the home page
        /// in the menu / footer.
        /// </summary>
        /// <returns></returns>
        public static IList <MenuEntry> FrontPagesAsMenuEntrys()
        {
            var frontpages = Cacher.Get <IEnumerable <Page> >("htmlpages_all", 300, () => GetAll().Where <Page>(page => page.IsFrontPage));
            IList <MenuEntry> menuitems = new List <MenuEntry>();

            foreach (Page page in frontpages)
            {
                menuitems.Add(new MenuEntry()
                {
                    Name = page.Title, Roles = string.Empty, SortIndex = 20, RefId = page.Id, Url = page.ActiveUrl
                });
            }

            return(menuitems);
        }
Ejemplo n.º 22
0
        public void RefreshesValueOnNextCall()
        {
            //Arrange
            var fake = Substitute.For <ITestable>();

            fake.LongRunningProcess(key).Returns(x => taskCompletion.Task.Result);

            //Act
            string value = Cacher.Get(key, () => fake.LongRunningProcess(key));

            //Assert
            taskCompletion.Task.Wait(10);

            fake.Received(1).LongRunningProcess(key);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Run the application.
        /// </summary>
        public override BoolMessageItem Execute()
        {
            // Using default ASP.NET Cache.

            Cacher.Insert("my_site", "http://www.knowledgedrink.com");
            Cacher.Insert("my_show", "ufc: ultimate fighting");
            Cacher.Insert("my_place", "bahamas", 360, true);

            Console.WriteLine("====================================================");
            Console.WriteLine("CACHE ");
            Console.WriteLine("Obtained from cache : '" + Cacher.Get <string>("my_site") + "'");
            Console.WriteLine("Contains cache for 'my_show' : " + Cacher.Contains("my_show"));
            Console.WriteLine(Environment.NewLine);
            return(BoolMessageItem.True);
        }
Ejemplo n.º 24
0
        public void OnlyCallsFuncOnce()
        {
            //Arrange
            var fake = Substitute.For <ITestable>();

            fake.LongRunningProcess(key).Returns(key);

            //Act
            Task <string> value1 = Task.Factory.StartNew(() => Cacher.Get(key, () => fake.LongRunningProcess(key)));
            Task <string> value2 = Task.Factory.StartNew(() => Cacher.Get(key, () => fake.LongRunningProcess(key)));

            //Assert
            value1.Wait();
            fake.Received(1).LongRunningProcess(key);
        }
Ejemplo n.º 25
0
        // GET api/country
        public IHttpActionResult Get()
        {
            IList <Language> res = _cache.Get("languages") as IList <Language>;

            if (res != null)
            {
                return(Ok(Task.FromResult(res)));
            }
            else
            {
                var cnt = Task.Run(() => _service.GetAll().Result);
                _cache.Add("languages", cnt.Result);
                return(Ok(cnt));
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Get the states for the specified country
        /// </summary>
        /// <param name="countryname"></param>
        /// <returns></returns>
        public BoolMessageItem <IList <State> > StatesFor(string countryname)
        {
            BoolMessageItem <Country> countryResult = Country(countryname);

            if (!countryResult.Success)
            {
                return(new BoolMessageItem <IList <State> >(null, false, countryResult.Message));
            }

            var    country = countryResult.Item;
            var    states  = Cacher.Get <IList <State> >("states_list_for_" + country.RealId, 300, () => Location.States.GetAll().Where(s => s.CountryId == country.RealId && !s.IsAlias && s.IsActive).ToList());
            bool   success = states != null && states.Count > 0;
            string message = success ? string.Empty : "States not available for country : " + countryname;

            return(new BoolMessageItem <IList <State> >(states, success, message));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Run the application.
        /// </summary>
        public override BoolMessageItem Execute()
        {
            // Using default ASP.NET Cache.
            //<doc:example>
            Cacher.Insert("my_site", "http://www.ufc.com");
            Cacher.Insert("my_show", "ufc: ultimate fighting");
            Cacher.Insert("my_place", "bahamas", 360, true);
            Cacher.Get <string>("my_framework", 30, () => "commonlibrary.net");

            Console.WriteLine("====================================================");
            Console.WriteLine("CACHE ");
            Console.WriteLine("Obtained from cache : '" + Cacher.Get <string>("my_site") + "'");
            Console.WriteLine("Contains cache for 'my_show' : " + Cacher.Contains("my_show"));
            Console.WriteLine(Environment.NewLine);

            //</doc:example>
            return(BoolMessageItem.True);
        }
Ejemplo n.º 28
0
        public void GetCacheTest()
        {
            var name1 = Cacher.Get("Name", () => "Kevin");
            var name2 = Cacher.Get <string>("Name");

            Assert.AreEqual(name1, name2);

            Cacher.Set("Name", "John");
            var name3 = Cacher.Get <string>("Name");

            Assert.AreEqual(name3, "John");

            var p1 = Cacher.Get <Person>("Kevin", () => new Person("Kevin"));
            var p2 = Cacher.Get <Person>("Cherry", () => new Person("Cherry"));
            var p3 = Cacher.Get <Person>("Kevin");
            var p4 = Cacher.Get <Person>("Jerry");

            Assert.AreEqual(p1.Name, p3.Name);
            Assert.AreEqual(p4, null);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Get the country with the specified name.
        /// </summary>
        /// <param name="countryName"></param>
        /// <returns></returns>
        public BoolMessageItem <Country> Country(string name)
        {
            // Check for null.
            if (string.IsNullOrEmpty(name))
            {
                return(new BoolMessageItem <Country>(null, false, "Country not supplied."));
            }

            var countryLookup = Cacher.Get <LookupMulti <Country> >("countries_lookup", 300, () => Location.Countries.ToLookUpMulti <string>("Name"));

            // Valid country.
            Country country = countryLookup.ContainsKey(name) ? countryLookup[name] : null;

            if (country == null)
            {
                return(new BoolMessageItem <Country>(null, false, "Unknown country supplied."));
            }

            return(new BoolMessageItem <Country>(country, true, string.Empty));
        }
Ejemplo n.º 30
0
        public void BlocksAllRequestThreads()
        {
            //Arrange
            var tcs = new TaskCompletionSource <string>();

            var fake = Substitute.For <ITestable>();

            fake.LongRunningProcess(key).Returns(x => tcs.Task.Result);

            //Act
            Task <string> value1 = Task.Factory.StartNew(() => Cacher.Get(key, () => fake.LongRunningProcess(key)));
            Task <string> value2 = Task.Factory.StartNew(() => Cacher.Get(key, () => fake.LongRunningProcess(key)));

            //Assert
            value1.IsCompleted.Should().BeFalse("First Thread is not blocked");
            value2.IsCompleted.Should().BeFalse("Second Thread is not blocked");

            // Complete the long running process
            tcs.SetResult(key);

            value1.Result.Should().Be(key, "Value1 did not match key");
            value2.Result.Should().Be(key, "Value2 did not match key");
        }