/// <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.º 2
0
        private void DisplayResultMessage(FeedbackItem feedbackItem)
        {
            RemoveCommentControls();
            Message = new Label();

            if (feedbackItem.Approved)
            {
                Message.Text     = Resources.PostComment_ThanksForComment;
                Message.CssClass = "success";
                Controls.Add(Message); //This needs to be here for ajax calls.
                Cacher.ClearCommentCache(feedbackItem.EntryId, SubtextContext);
                OnCommentApproved(feedbackItem);
                return;
            }
            if (feedbackItem.NeedsModeratorApproval)
            {
                Message.Text     = Resources.PostComment_ThanksForComment + " It will be displayed soon.";
                Message.CssClass = "error moderation";
            }
            else
            {
                Message.Text     = "Sorry, but your comment was flagged as spam and will be moderated.";
                Message.CssClass = "error";
            }
            Controls.Add(Message);
        }
Ejemplo n.º 3
0
        public void Handle_concurrent_access()
        {
            // Arrange
            const string testKey        = "key";
            const string result         = "Ok";
            var          timesRetrieved = 0;

            Task <string> RetrievalFuncAsync()
            {
                timesRetrieved++;
                Thread.Sleep(2);
                return(Task.FromResult(result));
            }

            // Act
            var task1 = Task.Run(() => Cacher.GetAsync(testKey, (Func <Task <string> >)RetrievalFuncAsync));
            var task2 = Task.Run(() => Cacher.GetAsync(testKey, (Func <Task <string> >)RetrievalFuncAsync));

            Task.WaitAll(task1, task2);

            //Assert
            task1.Result.Should().Be(result);
            task2.Result.Should().Be(result);
            timesRetrieved.Should()
            .Be(1, "Retrival function should be called only the first time. Second time should be retrieved from cache");
        }
Ejemplo n.º 4
0
        public void InitializeControls(ISkinControlLoader controlLoader)
        {
            IEnumerable <string> controlNames = _controls;

            if (controlNames != null)
            {
                var apnlCommentsWrapper = new UpdatePanel {
                    Visible = true, ID = CommentsPanelId
                };
                if (!controlNames.Contains("HomePage", StringComparer.OrdinalIgnoreCase) && !String.IsNullOrEmpty(Query))
                {
                    int   entryId = -1;
                    Entry entry   = Cacher.GetEntryFromRequest(true, SubtextContext);
                    if (entry != null)
                    {
                        entryId = entry.Id;
                    }
                    var query = Query;
                    if (!String.IsNullOrEmpty(query))
                    {
                        var searchResults = SearchEngineService.Search(query, 5, Blog.Id, entryId);
                        if (searchResults.Any())
                        {
                            AddMoreResultsControl(searchResults, controlLoader, apnlCommentsWrapper);
                        }
                    }
                }

                foreach (string controlName in controlNames)
                {
                    Control control = controlLoader.LoadControl(controlName);
                    AddControlToBody(controlName, control, apnlCommentsWrapper, CenterBodyControl);
                }
            }
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
        public virtual List <Entity> List(DateTime from, DateTime to, TimeSpan step)
        {
            var list = new List <Entity>();

            if (Cacher.Need)
            {
                Cacher.Initialize();
                list = Cacher.Entries
                       .Where(x => x.Date >= from && x.Date < to)
                       .OrderBy(x => x.Date)
                       .Select(x => (Entity)x)
                       .ToList();
            }
            else
            {
                list = Repository.Table()
                       .Where(x => x.Date >= from && x.Date < to)
                       .OrderBy(x => x.Date)
                       .Select(x => (Entity)x)
                       .ToList();
            }
            var result = TakeLastProductForEachStep(list, step);

            return(result);
        }
Ejemplo n.º 7
0
        private void Downloader_FetchCompleted(object Sender, FetchCompleteEventArgs args)
        {
            try
            {
                Cacher.GenerateCacheFor(args);
            }
            catch (IOException ex)
            {
                log.Error(ex, "Failed to generate cache with an IO Exception. Spider will be paused");
                Configuration.Paused = true;
                OnError?.Invoke(this, new ErrorEventArgs()
                {
                    Source = FetchEventArgs.EventSource.Downloader, Exception = ex
                });
            }
            catch (Exception ex)
            {
                log.Error(ex, "Failed to generate cache");
                OnError?.Invoke(this, new ErrorEventArgs()
                {
                    Source = FetchEventArgs.EventSource.Downloader, Exception = ex
                });
            }
            args.Source = FetchEventArgs.EventSource.Downloader;

            if (args.Link.MovedUri != null)
            {
                SpiderWorkData.Moved301[args.Link.MovedUri.ToString()] = args.Link.Uri.ToString();
            }

            fetchCompleted(args);
        }
Ejemplo n.º 8
0
        public MainGenerator(string gameLocation = @"..\..\..\Extra")
        {
            _characterdata = ReadFromFile.GetDictionaryFromFile(gameLocation + @"/racepng.txt");
            _features      = ReadFromFile.GetDictionaryFromFile(gameLocation + @"/features.txt");
            _cloudtiles    = ReadFromFile.GetDictionaryFromFile(gameLocation + @"/clouds.txt");
            _itemdata      = ReadFromFile.GetDictionaryFromFile(gameLocation + @"/items.txt");
            _weapondata    = ReadFromFile.GetDictionaryFromFile(gameLocation + @"/weapons.txt");

            _floorandwall             = ReadFromFile.GetFloorAndWallNamesForDungeons(gameLocation + @"/tilefloor.txt");
            _floorandwallColor        = ReadFromFile.GetFloorAndWallNamesForDungeons(gameLocation + @"/tilefloorColors.txt");
            _monsterdata              = ReadFromFile.GetMonsterData(gameLocation + @"/mon-data.h", gameLocation + @"/monsteroverrides.txt");
            _namedMonsterOverrideData = ReadFromFile.GetNamedMonsterOverrideData(gameLocation + @"/namedmonsteroverrides.txt");

            _floorpng      = ReadFromFile.GetSKBitmapDictionaryFromFolder(gameLocation + @"/rltiles/dngn/floor");
            _wallpng       = ReadFromFile.GetSKBitmapDictionaryFromFolder(gameLocation + @"/rltiles/dngn/wall");
            _alldngnpng    = ReadFromFile.GetSKBitmapDictionaryFromFolder(gameLocation + @"/rltiles/dngn");
            _alleffects    = ReadFromFile.GetSKBitmapDictionaryFromFolder(gameLocation + @"/rltiles/effect");
            _miscallaneous = ReadFromFile.GetSKBitmapDictionaryFromFolder(gameLocation + @"/rltiles/misc");
            _itempng       = ReadFromFile.GetSKBitmapDictionaryFromFolder(gameLocation + @"/rltiles/item");

            _characterpng = ReadFromFile.GetCharacterPNG(gameLocation);
            _monsterpng   = ReadFromFile.GetMonsterPNG(gameLocation);

            _outOfSightCache = new Cacher();
            _weaponpng       = ReadFromFile.GetWeaponPNG(gameLocation);
        }
Ejemplo n.º 9
0
        protected override void OnLoad(EventArgs e)
        {
            int blogId          = Blog.Id >= 1 ? Blog.Id : 0;
            var urlRelatedLinks = FindControl("Links") as Repeater;

            if (urlRelatedLinks != null)
            {
                if (SearchResults == null)
                {
                    int   entryId = -1;
                    Entry entry   = Cacher.GetEntryFromRequest(true, SubtextContext);
                    if (entry != null)
                    {
                        entryId = entry.Id;
                    }
                    SearchResults = SearchEngineService.Search(Query, RowCount, blogId, entryId);
                }
                urlRelatedLinks.DataSource = SearchResults;
                urlRelatedLinks.DataBind();
            }
            var keywords = FindControl("keywords") as Literal;

            if (keywords != null)
            {
                keywords.Text = HttpUtility.HtmlEncode(Query);
            }

            base.OnLoad(e);
        }
Ejemplo n.º 10
0
 public void Init(Cacher cacher)
 {
     this.lbName.Text = cacher.Name;
     this.simpleClampUC1.Init(cacher.Stations[0]);
     this.simpleClampUC2.Init(cacher.Stations[1]);
     this.simpleClampUC3.Init(cacher.Stations[2]);
 }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Start searching");
            var configs    = Greeter.Search();
            var sel_addr   = "";
            var sel_config = new Config();

            foreach (KeyValuePair <string, Config> config in configs)
            {
                Console.WriteLine("IP: " + config.Key);
                Console.WriteLine("IP: " + config.Value.VersionStr);
                sel_addr   = config.Key;
                sel_config = config.Value;
            }
            Console.WriteLine("Done searching");

            var cacher = new Cacher();

            cacher.Changed += HandleCacher;
            cacher.Connect(sel_config, sel_addr);
            while (true)
            {
                cacher.Check();
            }
        }
Ejemplo n.º 12
0
        /// <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.º 13
0
        public void GetEntry_WithEntryNameAndEntryNotInCache_RetrievesFromRepositoryAndInsertsInCache()
        {
            // arrange
            var entry = new Entry(PostType.BlogPost)
            {
                Id = 111, EntryName = "entry-slug", DateSyndicated = DateTime.Now.AddDays(-1)
            };
            var timeZone = new Mock <ITimeZone>();

            timeZone.Setup(tz => tz.Now).Returns(DateTime.Now);
            var blog = new Mock <Blog>();

            blog.Setup(b => b.TimeZone).Returns(timeZone.Object);
            blog.Object.Id = 1001;
            var context = new Mock <ISubtextContext>();

            context.Setup(c => c.Blog).Returns(blog.Object);
            context.Setup(c => c.Cache["EntryNameentry-slugBlogId1001"]).Returns(null);
            context.Setup(c => c.Repository.GetEntry("entry-slug", true /*activeOnly*/, true /*includeCategories*/)).Returns(entry);

            // act
            var cachedEntry = Cacher.GetEntry("entry-slug", context.Object);

            // assert
            Assert.AreEqual(entry, cachedEntry);
            context.Verify(c => c.Cache["EntryNameentry-slugBlogId1001"]);
        }
Ejemplo n.º 14
0
        public void GetEntryFromRequest_WithIdInRouteDataMatchingEntryInRepository_ReturnsEntry()
        {
            //arrange
            var httpContext = new Mock <HttpContextBase>();

            httpContext.FakeRequest("~/archive/123.aspx");
            var routeData = new RouteData();

            routeData.Values.Add("id", "123");
            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.SetupRequestContext(httpContext, routeData, new Blog {
                Id = 123
            })
            .Setup(c => c.Repository.GetEntry(123, true, true)).Returns(new Entry(PostType.BlogPost)
            {
                Id = 123, Title = "Testing 123"
            });

            //act
            Entry entry = Cacher.GetEntryFromRequest(true, subtextContext.Object);

            //assert
            Assert.AreEqual(123, entry.Id);
            Assert.AreEqual("Testing 123", entry.Title);
        }
Ejemplo n.º 15
0
        public void GetFeedback_WithFeedbackNotInCache_RetrievesFromRepositoryAndInsertsInCache()
        {
            // arrange
            var feedback = new FeedbackItem(FeedbackType.Comment)
            {
                Title = "Testing Cacher"
            };
            var parentEntry = new Entry(PostType.BlogPost)
            {
                Id = 322
            };
            var context = new Mock <ISubtextContext>();

            context.Setup(c => c.Blog).Returns(new Blog {
                Id = 1001
            });
            context.Setup(c => c.Cache["ParentEntry:Comments:EntryId322:BlogId1001"]).Returns(null);
            context.Setup(c => c.Repository.GetFeedbackForEntry(parentEntry)).Returns(new List <FeedbackItem> {
                feedback
            });

            // act
            var cachedFeedback = Cacher.GetFeedback(parentEntry, context.Object);

            // assert
            Assert.AreEqual(feedback, cachedFeedback.First());
            context.Verify(c => c.Cache["ParentEntry:Comments:EntryId322:BlogId1001"]);
        }
Ejemplo n.º 16
0
        public void GetEntry_WithEntryNameAndEntryInCacheWithPublishDateInFuture_ReturnsNull()
        {
            // arrange
            var entry = new Entry(PostType.BlogPost)
            {
                Id = 111, EntryName = "entry-slug", DateSyndicated = DateTime.Now.AddDays(2)
            };
            var timeZone = new Mock <ITimeZone>();

            timeZone.Setup(tz => tz.Now).Returns(DateTime.Now);
            var blog = new Mock <Blog>();

            blog.Setup(b => b.TimeZone).Returns(timeZone.Object);
            blog.Object.Id = 1001;
            var context = new Mock <ISubtextContext>();

            context.Setup(c => c.Blog).Returns(blog.Object);
            context.Setup(c => c.Cache["EntryNameentry-slugBlogId1001"]).Returns(entry);
            context.Setup(c => c.Repository.GetEntry("entry-slug", true /*activeOnly*/, true /*includeCategories*/)).Throws(new Exception("Repository should not have been accessed"));

            // act
            var cachedEntry = Cacher.GetEntry("entry-slug", context.Object);

            // assert
            Assert.IsNull(cachedEntry);
        }
Ejemplo n.º 17
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            TagItems = Cacher.GetTopTags(ItemCount, SubtextContext);
            int tagCount = TagItems.Count();

            if (tagCount == 0)
            {
                Visible = false;
            }
            else
            {
                var tagRepeater = FindControl("Tags") as Repeater;
                if (tagRepeater != null)
                {
                    tagRepeater.DataSource = TagItems;
                    tagRepeater.DataBind();
                }

                var defaultTagLink = ControlHelper.FindControlRecursively(this, "DefaultTagLink") as HyperLink;
                if (defaultTagLink != null)
                {
                    defaultTagLink.NavigateUrl = Url.TagCloudUrl();
                }
            }
        }
Ejemplo n.º 18
0
        public void GetEntriesForDay_WithEntriesNotInCache_RetrievesFromRepositoryAndInsertsInCache()
        {
            // arrange
            var entry = new Entry(PostType.BlogPost)
            {
                Title = "Testing Cacher"
            };
            var dateTime = DateTime.ParseExact("20090123", "yyyyMMdd", CultureInfo.InvariantCulture);
            var context  = new Mock <ISubtextContext>();

            context.Setup(c => c.Blog).Returns(new Blog {
                Id = 1001
            });
            context.Setup(c => c.Cache["EntryDay:Date20090123Blog1001"]).Returns(null);
            context.Setup(c => c.Repository.GetEntryDay(dateTime)).Returns(new EntryDay(dateTime, new List <Entry> {
                entry
            }));

            // act
            var cachedEntries = Cacher.GetEntriesForDay(dateTime, context.Object);

            // assert
            Assert.AreEqual(entry, cachedEntries.First());
            context.Verify(c => c.Cache["EntryDay:Date20090123Blog1001"]);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// 刷新缓存
 /// </summary>
 public virtual void Flush(string key)
 {
     lock (KeyLocker)
     {
         Cacher.Remove(key);
     }
 }
Ejemplo n.º 20
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.º 21
0
        internal void BindFeedback(Entry entry, bool fromCache)
        {
            try
            {
                CommentList.DataSource = fromCache ? Cacher.GetFeedback(entry, SubtextContext) : Repository.GetFeedbackForEntry(entry);
                CommentList.DataBind();

                if (CommentList.Items.Count == 0)
                {
                    if (entry.CommentingClosed)
                    {
                        Controls.Clear();
                    }
                    else
                    {
                        CommentList.Visible   = false;
                        NoCommentMessage.Text = "No comments posted yet.";
                    }
                }
                else
                {
                    CommentList.Visible   = true;
                    NoCommentMessage.Text = string.Empty;
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message, e);
                Visible = false;
            }
        }
Ejemplo n.º 22
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.º 23
0
        public void GetEntry_WithEntryNameAndEntryNotInCacheAndHasPublishDateInFuture_ReturnsNull()
        {
            // arrange
            var entry = new Entry(PostType.BlogPost)
            {
                Id = 111, EntryName = "entry-slug", DatePublishedUtc = DateTime.UtcNow.AddDays(2)
            };
            var timeZone = new Mock <ITimeZone>();

            timeZone.Setup(tz => tz.Now).Returns(DateTime.UtcNow);
            var blog = new Mock <Blog>();

            blog.Setup(b => b.TimeZone).Returns(timeZone.Object);
            blog.Object.Id = 1001;
            var context = new Mock <ISubtextContext>();

            context.Setup(c => c.Blog).Returns(blog.Object);
            context.Setup(c => c.Cache["EntryNameentry-slugBlogId1001"]).Returns(null);
            context.Setup(c => c.Repository.GetEntry("entry-slug", true /*activeOnly*/, true /*includeCategories*/)).Returns(entry);

            // act
            var cachedEntry = Cacher.GetEntry("entry-slug", context.Object);

            // assert
            Assert.IsNull(cachedEntry);
            context.Verify(c => c.Cache["EntryNameentry-slugBlogId1001"]);
        }
Ejemplo n.º 24
0
        public static bool TryDrawCachedTile(this string tile, string highlight, Cacher outOfSightCache, List <char> noCache, List <string> list, out SKBitmap lastSeen, out bool Cached)
        {
            Cached   = false;
            lastSeen = null;
            if (noCache.Contains(tile[0]))
            {
                return(false);
            }
            if (list.Contains(tile))
            {
                return(false);
            }
            if (tile.Substring(1) == Enum.GetName(typeof(ColorListEnum), ColorListEnum.BLUE) && outOfSightCache.TryGetLastSeenBitmapByChar(tile[0], out lastSeen))
            {
                Cached = true;
                return(true);
            }
            if (tile.Substring(1) == Enum.GetName(typeof(ColorListEnum), ColorListEnum.BLACK) && highlight != Enum.GetName(typeof(ColorListEnum), ColorListEnum.BLACK) &&
                outOfSightCache.TryGetLastSeenBitmapByChar(tile[0], out lastSeen))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 25
0
        private void UpdateFeedback()
        {
            Uri feedbackWebsite = null;

            valtxbWebsite.IsValid = !(txbWebsite.Text.Length > 0) || Uri.TryCreate(txbWebsite.Text, UriKind.RelativeOrAbsolute, out feedbackWebsite);

            if (Page.IsValid)
            {
                FeedbackItem updatedFeedback = FeedbackItem.Get(FeedbackId);
                updatedFeedback.Title = txbTitle.Text;
                updatedFeedback.Body  = richTextEditor.Text;
                if (feedbackWebsite != null)
                {
                    updatedFeedback.SourceUrl = feedbackWebsite;
                }
                FeedbackItem.Update(updatedFeedback);
                Cacher.InvalidateFeedback(updatedFeedback.Entry, SubtextContext);
                if (ReturnToOriginalPost)
                {
                    Response.Redirect(Url.FeedbackUrl(updatedFeedback));
                    return;
                }


                Messages.ShowMessage(Constants.RES_SUCCESSEDIT, false);
            }
        }
Ejemplo n.º 26
0
        public void GetEntryFromRequest_WithSlugInRouteDataMatchingEntryInRepository_ReturnsEntry()
        {
            //arrange
            var httpContext = new Mock <HttpContextBase>();

            httpContext.FakeRequest("~/archive/the-slug.aspx");
            var routeData = new RouteData();

            routeData.Values.Add("slug", "the-slug");
            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.SetupRequestContext(httpContext, routeData)
            .SetupBlog(new Blog {
                Id = 1, TimeZoneId = TimeZonesTest.PacificTimeZoneId                      /* pacific */
            })
            .Setup(c => c.Repository.GetEntry("the-slug", true, true)).Returns(new Entry(PostType.BlogPost)
            {
                Id = 123, EntryName = "the-slug", Title = "Testing 123"
            });

            //act
            Entry entry = Cacher.GetEntryFromRequest(true, subtextContext.Object);

            //assert
            Assert.AreEqual(123, entry.Id);
            Assert.AreEqual("Testing 123", entry.Title);
            Assert.AreEqual("the-slug", entry.EntryName);
        }
Ejemplo n.º 27
0
        public virtual ActionResult Index()
        {
            ViewBag.curPage  = "Home";
            ViewBag.insCount = Cacher <int> .CacheRetrieve(() => { return(Current.DB.Instruments.Count()); }, "inscount", 1800);

            return(View());
        }
Ejemplo n.º 28
0
        public void CanGetCategoryByNameRequest()
        {
            //arrange
            var routeData = new RouteData();

            routeData.Values.Add("slug", "this-is-a-test");
            var requestContext = new RequestContext(new Mock <HttpContextBase>().Object, routeData);
            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.Setup(c => c.RequestContext).Returns(requestContext);
            subtextContext.Setup(c => c.Blog).Returns(new Blog {
                Id = 123
            });
            subtextContext.Setup(c => c.Repository.GetLinkCategory("this-is-a-test", true))
            .Returns(new LinkCategory {
                Id = 99, Title = "this is a test"
            });
            subtextContext.Setup(c => c.Cache[It.IsAny <string>()]).Returns(null);

            //act
            LinkCategory category = Cacher.SingleCategory(subtextContext.Object);

            //assert
            Assert.AreEqual(99, category.Id);
        }
Ejemplo n.º 29
0
        private bool workQueue()
        {
            if (qAdded.TryDequeue(out Link lnk))
            {
                if (alreadyExecuted(lnk.Uri))
                {
                    return(true);
                }

                if (hDispatched.Contains(lnk.Uri.ToString()))
                {
                    return(true);
                }
                hDispatched.Add(lnk.Uri.ToString());

                if (Cacher.HasCache(lnk))
                {
                    qCache.Enqueue(lnk);
                }
                else
                {
                    qDownload.Enqueue(lnk);
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //

        /*
         * NB. page state check.-----------------------------------------------------------------
         *
         */
        PageStateChecker.PageStateChecker_SERVICE(
            "zonaRiservata_candidatoLoad"
            , this.Request
            , this.IsPostBack
            , this.Session
            );
        //----------------------------------------------- END  page state check.-----------------
        if (!this.IsPostBack)
        {
            System.Data.DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("name", typeof(string));
            //
            for (int c = 33; c < 200; c++)
            {
                object[] filler = new object[2];
                filler[0] = c;
                filler[1] = (char)c;
                dt.Rows.Add(filler);
                //
                filler = null;
            }
            //
            Cacher cacher = new Cacher(dt);
            this.Session["Cacher"] = cacher;
        } // else already built.
    }     // end Page_Load().
 public CachedConferenceRepository(ConferenceRepository conferenceRepository,
     ILogger<CachedConferenceRepository> logger,
     Cacher cacher)
 {
     _underlyingRepository = conferenceRepository;
     _logger = logger;
     _cacher = cacher;
 }