예제 #1
0
        /// <summary>
        /// Returns a dictionary where the key is the taxon and value is
        /// the number is the count of the times that the taxon is used(marked)
        /// </summary>
        /// <returns></returns>
        protected override Dictionary <ITaxon, uint> GetTaxaItemsCountForTaxonomy()
        {
            if (ShowItemCount)
            {
                var taxonomyIds = BlogsManager.GetManager(Provider)
                                  .GetBlogPosts()
                                  .Where(b => b.Status == ContentLifecycleStatus.Live && b.Parent.Title == BlogName && b.Visible)
                                  .SelectMany(b => b.GetValue <TrackedList <Guid> >(FieldName))
                                  .GroupBy(id => id);

                return(taxonomyIds.ToDictionary(
                           group => CurrentTaxonomyManager.GetTaxon(group.Key),
                           group => (uint)group.Count()));
            }
            else
            {
                var taxonomyIds = BlogsManager.GetManager(Provider)
                                  .GetBlogPosts()
                                  .Where(b => b.Status == ContentLifecycleStatus.Live && b.Parent.Title == BlogName && b.Visible)
                                  .SelectMany(b => b.GetValue <TrackedList <Guid> >(FieldName))
                                  .Distinct();

                return(taxonomyIds.ToDictionary(
                           id => CurrentTaxonomyManager.GetTaxon(id),
                           id => (uint)1)); // ShowItemCount is false so this doesn't matter.
            }
        }
예제 #2
0
        /// <summary>
        /// Tries to resolve parent filter mode.
        /// </summary>
        /// <param name="urlParams">The URL params.</param>
        /// <param name="requestContext">The request context.</param>
        /// <returns></returns>
        protected virtual bool TryResolveParentFilterMode(string[] urlParams, RequestContext requestContext, BlogsManager manager = null)
        {
            var blogsManager = manager ?? BlogsManager.GetManager(this.Model.ProviderName);

            string param = RouteHelper.GetUrlParameterString(urlParams);

            string redirectUrl;

            var item = blogsManager.GetItemFromUrl(typeof(Blog), param, out redirectUrl);

            if (item != null)
            {
                requestContext.RouteData.Values["action"]     = "Successors";
                requestContext.RouteData.Values["parentItem"] = item;

                if (this.Request["page"] != null)
                {
                    requestContext.RouteData.Values["page"] = int.Parse(this.Request["page"]);
                }

                return(true);
            }
            if (urlParams.Length > 1)
            {
                this.TryResolveParentFilterMode(urlParams.Take(urlParams.Length - 1).ToArray(), requestContext, manager);
            }
            return(false);
        }
예제 #3
0
        public async Task <IActionResult> ModifyBlogAsync(int id, [FromBody] Domain.Blogs.Models.ModifyPost model)
        {
            if (string.IsNullOrWhiteSpace(model.Title))
            {
                return(BadRequest("标题不能为空"));
            }
            if (model.Targets.Length == 0)
            {
                return(BadRequest("标签不能为空"));
            }
            if (string.IsNullOrWhiteSpace(model.Content))
            {
                return(BadRequest("内容不能为空"));
            }

            BlogsManager manager = new BlogsManager();
            var          blog    = await manager.GetBlogAsync(id);

            if (blog is null)
            {
                return(NotFound());
            }
            await blog.ModifyAsync(model);

            return(NoContent());
        }
예제 #4
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="sfContent">The sf content.</param>
        public BlogModel(Blog sfContent)
            : base(sfContent)
        {
            if (sfContent != null)
            {
                Description = sfContent.Description;
                Status      = sfContent.Status;
                Url         = sfContent.GetFullUrl(sfContent.DefaultPageId);
                Slug        = sfContent.UrlName;
                Active      = sfContent.Status == ContentLifecycleStatus.Live &&
                              sfContent.Visible;

                //CALCULATE COMMENTS
                PostsCount = BlogsManager.GetManager().GetBlogPosts()
                             .Count(c => c.Parent.Id == sfContent.Id &&
                                    c.Status == ContentLifecycleStatus.Live &&
                                    c.Visible);


                //CUSTOM PROPERTIES
                if (sfContent.DoesFieldExist("Image"))
                {
                    Image = sfContent.GetValue <string>("Image");
                }

                // Store original content
                OriginalContent = sfContent;
            }
        }
예제 #5
0
        private void RepublishBlogPosts(IEnumerable <string> providers)
        {
            foreach (var provider in providers)
            {
                var blogsManager = BlogsManager.GetManager(provider);
                blogsManager.Provider.SuppressSecurityChecks = false;
                var blogPosts = blogsManager.GetBlogPosts().Where(n => n.Visible && n.Status == ContentLifecycleStatus.Live).ToList();
                var count     = 0;

                foreach (var blogPost in blogPosts)
                {
                    var master = blogsManager.Lifecycle.GetMaster(blogPost);
                    var temp   = blogsManager.Lifecycle.CheckOut(master) as BlogPost;
                    temp.Title = temp.Title.Trim();
                    master     = blogsManager.Lifecycle.CheckIn(temp) as BlogPost;
                    blogsManager.Lifecycle.Publish(master);

                    count++;
                    if (count % 200 == 0)
                    {
                        blogsManager.SaveChanges();
                    }
                }

                blogsManager.SaveChanges();
                blogsManager.Provider.SuppressSecurityChecks = true;
            }
        }
예제 #6
0
        // GET: CustomBlogs
        public ActionResult Index()
        {
            BlogsManager       blogsManager = BlogsManager.GetManager();
            Blog               blog         = blogsManager.GetBlogs().Where(m => m.Title == "Blogs List").FirstOrDefault();
            var                blogPosts    = blogsManager.GetBlogPosts().Where(b => b.Status == ContentLifecycleStatus.Live).ToList();
            List <CustomBlogs> list         = new List <CustomBlogs>();

            foreach (var item in blogPosts)
            {
                var image  = item.GetRelatedItems <Telerik.Sitefinity.Libraries.Model.Image>("Image").FirstOrDefault();
                var image1 = "";
                if (image != null)
                {
                    image1 = image.MediaUrl.ToString();
                }


                var Title       = item.Title;
                var Description = item.Content;


                list.Add(new CustomBlogs
                {
                    Title       = item.Title,
                    Description = item.Content,
                    Image       = image1
                });
            }
            return(View("Index", list));
        }
예제 #7
0
        /// <summary>
        /// Gets the last post dates for each blog in the model that has blog posts.
        /// </summary>
        /// <param name="model">The blog model.</param>
        /// <returns>Prefetched dictionary containing last post date for each blog in the model that has blog posts.</returns>
        public static IDictionary <Guid, DateTime> GetLastPostDates(this ContentListViewModel model)
        {
            const int BatchSize = 200;

            var ids       = model.Items.Select(vm => vm.DataItem.Id).ToArray();
            var blogPosts = BlogsManager.GetManager(model.ProviderName).GetBlogPosts().Where(i => i.Status == ContentLifecycleStatus.Master);
            IEnumerable <KeyValuePair <Guid, DateTime> > blogsWithChildPosts;

            if (ids.Length <= BatchSize)
            {
                blogsWithChildPosts = BlogPostHelper.PartialBlogsLastPostDates(ids, blogPosts);
            }
            else
            {
                var tempResult = new List <KeyValuePair <Guid, DateTime> >(ids.Length);

                // Integer division, rounded up
                var pagesCount = (ids.Length + BatchSize - 1) / BatchSize;
                for (var p = 0; p < pagesCount; p++)
                {
                    var batch = ids.Skip(p * BatchSize).Take(BatchSize).ToArray();
                    tempResult.AddRange(BlogPostHelper.PartialBlogsLastPostDates(batch, blogPosts));
                }

                blogsWithChildPosts = tempResult;
            }

            var result = blogsWithChildPosts.ToDictionary(k => k.Key, k => k.Value);

            return(result);
        }
        private void OnBlogPostCreated(IDataEvent @event)
        {
            if (@event.ItemType == typeof(BlogPost) && @event.Action == "New")
            {
                var blogsManager    = BlogsManager.GetManager(@event.ProviderName);
                var currentBlogPost = blogsManager.GetBlogPost(@event.ItemId);

                currentBlogPost.Content = currentBlogPost + "<br/><i>This is the disclaimer!</i>";
            }
        }
예제 #9
0
        public async Task <IActionResult> GetBlogsAsync(int index, int size, string s)
        {
            var pager = Domain.Paginator.New(index, size, 1);

            pager["s"] = s ?? "";

            BlogsManager blogsManager = new BlogsManager();

            pager = await blogsManager.GetBlogListAsync(BlogsManager.ListType.Search, pager);

            return(Ok(pager));
        }
예제 #10
0
        public async Task <IActionResult> DeleteBlogAsync(int id)
        {
            BlogsManager blogsManager = new BlogsManager();

            (bool isSuccess, string msg) = await blogsManager.DeleteBlogAsync(id, CurrentUserId);

            if (isSuccess)
            {
                return(Ok());
            }
            return(BadRequest(msg));
        }
예제 #11
0
        public async Task <IActionResult> GetBlogsAsync(int index, int size, string s, int?state)
        {
            var pager = Domain.Paginator.New(index, size, 2);

            pager["s"]     = s ?? "";
            pager["state"] = state.HasValue ? state.Value.ToString() : "";

            BlogsManager blogsManager = new BlogsManager();

            pager = await blogsManager.GetBlogListAsync(BlogsManager.ListType.AdministartorSide, pager);

            return(Ok(pager));
        }
예제 #12
0
        public async Task <IActionResult> GetBlogDetailAsync(int id, bool readed)
        {
            BlogsManager blogsManager = new BlogsManager();
            var          blog         = await blogsManager.GetBlogAsync(id);

            if (blog is null)
            {
                return(NotFound());
            }
            Domain.Blogs.Results.BlogDetail detail = await blog.GetDetailAsync(readed);

            return(Ok(detail));
        }
예제 #13
0
        public async Task <IActionResult> LikeAsync(int id)
        {
            BlogsManager manager = new BlogsManager();
            var          blog    = await manager.GetBlogAsync(id);

            if (blog is null)
            {
                return(NotFound());
            }
            await blog.LikeAsync();

            return(NoContent());
        }
        private void migrateComments(BlogPost blogPost, BlogsManager blogsManager, Entry post, Feed feed)
        {
            BlogPost livePost = blogsManager.GetLive(blogPost);

            foreach (Entry cmmnt in feed.Entry.Where(en => en.Categories.Any(c => c.CategoryType == CategoryType.Comment) && en.ReplyTo != null && en.ReplyTo.Id == post.Id))
            {
                Comment comment = blogsManager.CreateComment(livePost);
                comment.AuthorName = cmmnt.Author.Name;
                comment.Email = cmmnt.Author.Email;
                comment.Content = cmmnt.Content;
                comment.DateCreated = cmmnt.Published;

                blogsManager.SaveChanges();
            }
        }
예제 #15
0
        private void migrateComments(BlogPost blogPost, BlogsManager blogsManager, Entry post, Feed feed)
        {
            BlogPost livePost = blogsManager.GetLive(blogPost);

            foreach (Entry cmmnt in feed.Entry.Where(en => en.Categories.Any(c => c.CategoryType == CategoryType.Comment) && en.ReplyTo != null && en.ReplyTo.Id == post.Id))
            {
                Comment comment = blogsManager.CreateComment(livePost);
                comment.AuthorName  = cmmnt.Author.Name;
                comment.Email       = cmmnt.Author.Email;
                comment.Content     = cmmnt.Content;
                comment.DateCreated = cmmnt.Published;

                blogsManager.SaveChanges();
            }
        }
예제 #16
0
        private void ValidateUpdatingComment(Comment comment)
        {
            var catchSpamInComments = Config.Get <AkismetModuleConfig>().ProtectComments;

            if (catchSpamInComments)
            {
                var blogsMan        = BlogsManager.GetManager(string.Empty, "DummyTransaction");
                var existingComment = SystemManager.GetCommentsService().GetComment(comment.Id.ToString());

                if (existingComment != null && existingComment.Status != comment.Status.ToString())
                {
                    Akismet akismetApiClient = new Akismet(Config.Get <AkismetModuleConfig>().ApiKey, "http://www.sitefinity.com", "SitefinityAkismetModule");
                    if (!akismetApiClient.VerifyKey())
                    {
                        return;
                    }

                    var akismetDbContext    = new AkismetEntityContext();
                    var existingAkismetData = akismetDbContext.AkismetDataList.SingleOrDefault(a => a.ContentItemId == comment.Id);
                    if (existingAkismetData != null)
                    {
                        var updatedComment = new AkismetComment()
                        {
                            Blog               = "http://www.sitefinity.com",
                            CommentContent     = comment.Content,
                            CommentType        = "comment",
                            Referrer           = existingAkismetData.Referrer,
                            UserAgent          = existingAkismetData.UserAgent,
                            UserIp             = existingAkismetData.UserIP,
                            CommentAuthor      = comment.AuthorName,
                            CommentAuthorEmail = comment.Email,
                            CommentAuthorUrl   = comment.Website
                        };

                        if (comment.CommentStatus.ToString() == Telerik.Sitefinity.Services.Comments.StatusConstants.Spam)
                        {
                            // the item has been marked as spam
                            akismetApiClient.SubmitSpam(updatedComment);
                        }
                        else
                        {
                            // the item has been marked as ham
                            akismetApiClient.SubmitHam(updatedComment);
                        }
                    }
                }
            }
        }
예제 #17
0
        public override void ConstructArchiveItems()
        {
            if (DateBuildOptions != DateBuildOptions.YearMonth)
            {
                // if we need to support Year or YearMonthDay in the future we can add a switch statement below and remove this check.
                throw new Exception("DateBuildOptions unsupported, must be YearMonth");
            }

            var blogs = BlogsManager.GetManager(Provider).GetBlogPosts();
            var items = (from b in blogs
                         where b.Status == ContentLifecycleStatus.Live && b.Parent.Title == BlogName && b.Visible
                         group b by new { y = b.PublicationDate.Year, m = b.PublicationDate.Month }
                         into grp
                         select new ArchiveItem(new DateTime(grp.Key.y, grp.Key.m, 1), grp.Count()))
                        .OrderByDescending(ai => ai.Date)
                        .ToList();

            DataBindArchiveRepeater(items);
        }
예제 #18
0
        public void MigrateBlogs(StreamReader source)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Feed));
            Feed          feed          = xmlSerializer.Deserialize(source) as Feed;

            BlogsManager blogsManager = BlogsManager.GetManager();
            Blog         blog         = blogsManager.CreateBlog();

            blog.Title       = feed.Title;
            blog.Description = feed.Title;
            blog.UrlName     = Regex.Replace(blog.Title.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");

            blogsManager.SaveChanges();

            foreach (Entry post in feed.Entry.Where(en => en.Categories.Any(c => c.CategoryType == CategoryType.Post)))
            {
                migrateBlogPost(blogsManager, blog, post, feed);
            }
        }
예제 #19
0
        /// <summary>
        /// Creates a blog post with specified publication date.
        /// </summary>
        /// <param name="blogPostTitle">The blog post title.</param>
        /// <param name="blogId">The blog id.</param>
        /// <param name="publicationDate">The blog post publication date.</param>
        /// <returns></returns>
        public Guid CreateBlogPostSpecificPublicationDate(string blogPostTitle, Guid blogId, DateTime publicationDate)
        {
            BlogsManager blogsManager = new BlogsManager();

            var blog = blogsManager.GetBlog(blogId);
            var post = blogsManager.CreateBlogPost();
            post.Parent = blog;
            post.Title = blogPostTitle;
            post.UrlName = ServerArrangementUtilities.GetFormatedUrlName(blogPostTitle);

            Guid blogPostId = post.Id;

            post.SetWorkflowStatus(blogsManager.Provider.ApplicationName, "Published");
            blogsManager.RecompileAndValidateUrls(blog);
            blogsManager.Lifecycle.PublishWithSpecificDate(post, publicationDate);

            blogsManager.SaveChanges();

            return blogPostId;
        }
        public void SaveBlog_Test()
        {
            var database = new BlogsManager();
            database.Truncate();
            var blog = new Blog {Name = "Test Blog"};
            var initialCount = database.Count();

            try
            {
                TransactionHelper.Begin(() => database.Save(blog));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            var finalCount = database.Count();

            Assert.That(finalCount == ++initialCount);
        }
        private void migrateBlogPost(BlogsManager blogsManager, Blog blog, Entry post, Feed feed)
        {
            BlogPost blogPost = blogsManager.CreateBlogPost();
            blogPost.Parent = blog;

            blogPost.Content = post.Content;
            blogPost.Title = post.Title;
            blogPost.DateCreated = post.Published;
            blogPost.PublicationDate = post.Published;
            blogPost.LastModified = post.Updated;
            blogPost.ItemDefaultUrl = "2012/06/net-guy-velocityconf-2012-day-1.html";
            blogsManager.SaveChanges();
            var bag = new Dictionary<string, string>();
            bag.Add("ContentType", typeof(BlogPost).FullName);
            WorkflowManager.MessageWorkflow(blogPost.Id, typeof(BlogPost), null, "Publish", false, bag);

            migrateComments(blogPost, blogsManager, post, feed);

            migrateTags(post, blogPost, blogsManager);
        }
예제 #22
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="sfContent">The sf content.</param>
        public BlogPostModel(BlogPost sfContent)
            : base(sfContent)
        {
            if (sfContent != null)
            {
                Content = sfContent.Content;
                Summary = sfContent.Summary;
                Status  = sfContent.Status;
                Slug    = sfContent.UrlName;
                Active  = sfContent.Status == ContentLifecycleStatus.Live &&
                          sfContent.Visible;

                //GET PARENT BLOG
                Parent = new BlogModel(sfContent.Parent);

                //CONSTRUCT URL BASED ON PARENT BLOG
                Url = sfContent.GetFullUrl(sfContent.DefaultPageId);
                if (sfContent.Parent.DefaultPageId.HasValue)
                {
                    Url = Parent.Url + Url;
                }

                //POPULATE TAXONOMIES TO LIST
                Categories = sfContent.GetTaxa("Category");
                Tags       = sfContent.GetTaxa("Tags");

                //CALCULATE COMMENTS
                CommentsCount = BlogsManager.GetManager().GetComments()
                                .Count(c => c.CommentedItemID == sfContent.Id &&
                                       c.Status == ContentLifecycleStatus.Master);

                //CUSTOM PROPERTIES
                if (sfContent.DoesFieldExist("Image"))
                {
                    Image = sfContent.GetValue <string>("Image");
                }

                // Store original content
                OriginalContent = sfContent;
            }
        }
예제 #23
0
        /// <summary>
        /// Creates a blog post with specified publication date.
        /// </summary>
        /// <param name="blogPostTitle">The blog post title.</param>
        /// <param name="blogId">The blog id.</param>
        /// <param name="publicationDate">The blog post publication date.</param>
        /// <returns></returns>
        public Guid CreateBlogPostSpecificPublicationDate(string blogPostTitle, Guid blogId, DateTime publicationDate)
        {
            BlogsManager blogsManager = new BlogsManager();

            var blog = blogsManager.GetBlog(blogId);
            var post = blogsManager.CreateBlogPost();

            post.Parent  = blog;
            post.Title   = blogPostTitle;
            post.UrlName = ServerArrangementUtilities.GetFormatedUrlName(blogPostTitle);

            Guid blogPostId = post.Id;

            post.SetWorkflowStatus(blogsManager.Provider.ApplicationName, "Published");
            blogsManager.RecompileAndValidateUrls(blog);
            blogsManager.Lifecycle.PublishWithSpecificDate(post, publicationDate);

            blogsManager.SaveChanges();

            return(blogPostId);
        }
예제 #24
0
        private void migrateBlogPost(BlogsManager blogsManager, Blog blog, Entry post, Feed feed)
        {
            BlogPost blogPost = blogsManager.CreateBlogPost();

            blogPost.Parent = blog;

            blogPost.Content         = post.Content;
            blogPost.Title           = post.Title;
            blogPost.DateCreated     = post.Published;
            blogPost.PublicationDate = post.Published;
            blogPost.LastModified    = post.Updated;
            blogPost.ItemDefaultUrl  = "2012/06/net-guy-velocityconf-2012-day-1.html";
            blogsManager.SaveChanges();
            var bag = new Dictionary <string, string>();

            bag.Add("ContentType", typeof(BlogPost).FullName);
            WorkflowManager.MessageWorkflow(blogPost.Id, typeof(BlogPost), null, "Publish", false, bag);

            migrateComments(blogPost, blogsManager, post, feed);

            migrateTags(post, blogPost, blogsManager);
        }
        private void migrateTags(Entry post, BlogPost blogPost, BlogsManager blogsManager)
        {
            TaxonomyManager taxonomyManager = new TaxonomyManager();
            var tax = taxonomyManager.GetTaxonomies<FlatTaxonomy>().Where(t => t.Name == "Tags").SingleOrDefault();

            foreach (Category tag in post.Categories.Where(c => c.CategoryType == CategoryType.Unknown))
            {
                var taxon = taxonomyManager.GetTaxa<FlatTaxon>().Where(t => t.Title == tag.Term).FirstOrDefault();
                if (taxon == null)
                {
                    taxon = taxonomyManager.CreateTaxon<FlatTaxon>();
                    taxon.Name = tag.Term;
                    taxon.Title = tag.Term;

                    tax.Taxa.Add(taxon);
                    taxonomyManager.SaveChanges();
                }

                blogPost.Organizer.AddTaxa("Tags", taxon.Id);
                blogsManager.SaveChanges();
            }
        }
예제 #26
0
        private void migrateTags(Entry post, BlogPost blogPost, BlogsManager blogsManager)
        {
            TaxonomyManager taxonomyManager = new TaxonomyManager();
            var             tax             = taxonomyManager.GetTaxonomies <FlatTaxonomy>().Where(t => t.Name == "Tags").SingleOrDefault();

            foreach (Category tag in post.Categories.Where(c => c.CategoryType == CategoryType.Unknown))
            {
                var taxon = taxonomyManager.GetTaxa <FlatTaxon>().Where(t => t.Title == tag.Term).FirstOrDefault();
                if (taxon == null)
                {
                    taxon       = taxonomyManager.CreateTaxon <FlatTaxon>();
                    taxon.Name  = tag.Term;
                    taxon.Title = tag.Term;

                    tax.Taxa.Add(taxon);
                    taxonomyManager.SaveChanges();
                }

                blogPost.Organizer.AddTaxa("Tags", taxon.Id);
                blogsManager.SaveChanges();
            }
        }
예제 #27
0
        private void RepublishBlogs(IEnumerable <string> providers)
        {
            foreach (var provider in providers)
            {
                var blogsManager = BlogsManager.GetManager(provider);
                blogsManager.Provider.SuppressSecurityChecks = false;
                var blogs = blogsManager.GetBlogs().ToList();
                var count = 0;

                foreach (var blog in blogs)
                {
                    blog.Title = blog.Title.Trim();

                    count++;
                    if (count % 200 == 0)
                    {
                        blogsManager.SaveChanges();
                    }
                }

                blogsManager.SaveChanges();
                blogsManager.Provider.SuppressSecurityChecks = true;
            }
        }
        /// <summary>
        /// Tries to resolve parent filter mode.
        /// </summary>
        /// <param name="urlParams">The URL params.</param>
        /// <param name="requestContext">The request context.</param>
        /// <returns></returns>
        protected virtual bool TryResolveParentFilterMode(string[] urlParams, RequestContext requestContext, BlogsManager manager = null)
        {
            var blogsManager = manager ?? BlogsManager.GetManager(this.Model.ProviderName);

            string param = RouteHelper.GetUrlParameterString(urlParams);

            string redirectUrl;

            var item = blogsManager.GetItemFromUrl(typeof(Blog), param, out redirectUrl);

            if (item != null)
            {
                requestContext.RouteData.Values["action"] = "Successors";
                requestContext.RouteData.Values["parentItem"] = item;

                if (this.Request["page"] != null)
                    requestContext.RouteData.Values["page"] = int.Parse(this.Request["page"]);

                return true;
            }
            if (urlParams.Length > 1)
            {
                this.TryResolveParentFilterMode(urlParams.Take(urlParams.Length - 1).ToArray(), requestContext, manager);
            }
            return false;
        }
        //**************Actions**************//
        //***********************************//
        //***********************************//
        #region HandleUnknownAction

        protected override void HandleUnknownAction(string actionName)
        {
            log.Info("Begin HandleUnknownAction.");
            var blogsManager = BlogsManager.GetManager();

            log.Trace("Got an instance of the BlogsManager.");
            var taxonomyManager = TaxonomyManager.GetManager();

            log.Trace("Got an instance of the TaxonomyManager.");
            var currentContext = System.Web.HttpContext.Current;

            log.Trace("Got the Current Context.");
            var postUrl = currentContext.Request.Url.AbsolutePath;

            if (postUrl.Contains('?'))
            {
                log.Debug("postUrl contains a '?'.");
                postUrl = postUrl.Split('?').First();
                log.Trace("postUrl: {0}", postUrl.IsNullOrEmpty() ? "There is no url available" : postUrl);
            }

            postUrl = currentContext.Request.Url.AbsolutePath.Split('/').Last();
            log.Debug("postUrl: {0}", postUrl.IsNullOrEmpty() ? "There is no url available" : postUrl);

            var item = blogsManager.GetBlogPosts().Where(bp => bp.UrlName == postUrl).FirstOrDefault();

            if (item != null)
            {
                log.Debug("item: {0}", item.Title.Value.IsNullOrEmpty() ? "There is no title set" : item.Title.Value);
                item = blogsManager.Lifecycle.GetLive(item) as BlogPost;
                log.Trace("Got the live version of the Blog Post.");
                try
                {
                    var allCategories = item.GetValue <IList <Guid> >("Category").ToArray();
                    log.Debug("Got a list of category ids for the post, {0}.", allCategories.Count());
                    List <Guid> categories = new List <Guid>();
                    log.Trace("Set the list for Blended List Query.");
                    int hitCount = 0;
                    log.Trace("Set the hitcount variable required for Sitefinity Search.");

                    foreach (var currGuid in allCategories)
                    {
                        var currTaxon = taxonomyManager.GetTaxon <HierarchicalTaxon>(currGuid);

                        if (currTaxon != null)
                        {
                            log.Debug("Got taxonomy, {0}, for the id, {1}", currTaxon.Title.Value.IsNullOrEmpty() ? "There is no title set" : currTaxon.Title.Value);
                            categories.Add(currGuid);
                            log.Trace("Taxon added to the list for the search.");
                        }
                    }

                    log.Info("Calling BlendedListHelper.GetItems.");
                    var resultListItems = BlendedNewsHelper.GetNewsItems(Providers, _searchIndex, out hitCount, categories.ToArray(), null, 0, this.NumberOfPosts + 10);
                    log.Info("Number of results: {0}", hitCount);
                    log.Info("Calling SetBlendedListItems.");
                    var blendedListItems = SetBlendedListItems(resultListItems);
                    log.Debug("Prune the current Item if it is in the list.");
                    blendedListItems = blendedListItems
                                       .Where(bli => !bli.Link.Contains(item.UrlName) &&
                                              !bli.Featured).Take(this.NumberOfPosts).ToList();

                    log.Debug("Prep the template for use.");
                    string template = _viewTemplate;
                    log.Info("Finishing HandleUnknownAction");
                    this.View(template, blendedListItems).ExecuteResult(ControllerContext);
                }
                catch (Exception ex)
                {
                    log.Error("Source: {0}", ex.Source);
                    log.Error("Stack Trace: {0}", ex.StackTrace);
                    log.Error("Message: {0}", ex.Message);
                }
            }
            else
            {
                log.Debug("There was no item for the given url, ({0}).", postUrl.IsNullOrEmpty() ? "There is no url available" : postUrl);
            }
        }
예제 #30
0
        private void CreateSampleWorker(object[] args)
        {
            // ensure news config exists
            if (!this.ContentTypes.ContainsKey(NewsModule.ModuleName))
            {
                var contentType = new ContentType(this.ContentTypes);
                contentType.Name  = NewsModule.ModuleName;
                contentType.Pages = new ConfigElementList <ContentPage>(contentType);
                this.ContentTypes.Add(contentType);
            }

            // ensure news pages config exist
            var newsConfig = this.ContentTypes[NewsModule.ModuleName];

            if (newsConfig.Pages.Count == 0)
            {
                // add one setting for each provider
                var providers = NewsManager.GetManager().Providers;
                foreach (var provider in providers)
                {
                    // retrieve all pages with a NewsView on them
                    var newsPages = App.WorkWith().Pages()
                                    .Where(p => p.Page != null && p.ShowInNavigation && p.Page.Controls.Where(c => c.ObjectType.StartsWith(typeof(NewsView).FullName)).Count() > 0)
                                    .Get();

                    // attempt to locate the default page
                    foreach (var page in newsPages)
                    {
                        string providerName;

                        // retrieve the news view control from the page
                        var newsView = page.Page.Controls.Where(c => c.ObjectType.StartsWith(typeof(NewsView).FullName)).First();
                        if (newsView == null)
                        {
                            continue;
                        }

                        // determine if there is a modified control definition
                        var controlDefinition = newsView.Properties.Where(p => p.Name == "ControlDefinition").FirstOrDefault();
                        if (controlDefinition == null)
                        {
                            // control uses default provider
                            providerName = NewsManager.GetDefaultProviderName();
                        }
                        else
                        {
                            // search for modified provider name in the control
                            var providerNameProperty = controlDefinition.ChildProperties.Where(p => p.Name == "ProviderName").FirstOrDefault();
                            if (providerNameProperty == null)
                            {
                                // control is modified, but still uses default provider
                                providerName = NewsManager.GetDefaultProviderName();
                            }
                            else
                            {
                                // get selected provider name
                                providerName = providerNameProperty.Value;
                            }
                        }

                        // make sure specified provider matches the current provider we are working with
                        if (providerName != provider.Name)
                        {
                            continue;
                        }

                        // make sure the mode of the control is not Details-only, skip this page if it is
                        var displayModeProperty = newsView.Properties.Where(p => p.Name == "ContentViewDisplayMode").SingleOrDefault();
                        if (displayModeProperty != null && displayModeProperty.Value == Telerik.Sitefinity.Web.UI.ContentUI.Enums.ContentViewDisplayMode.Detail.ToString())
                        {
                            continue;
                        }

                        // save default news page for this provider to the config
                        var newsPage = new ContentPage(newsConfig.Pages);
                        newsPage.DefaultPageUrl = page.GetFullUrl();
                        newsPage.Name           = providerName;
                        newsPage.Include        = true;
                        newsPage.ProviderName   = providerName;
                        newsConfig.Pages.Add(newsPage);

                        // stop search for a matching news page, move to next provider (if any)
                        break;
                    }
                }
            }

            // ensure events config exists
            if (!this.ContentTypes.ContainsKey(EventsModule.ModuleName))
            {
                var contentType = new ContentType(this.ContentTypes);
                contentType.Name  = EventsModule.ModuleName;
                contentType.Pages = new ConfigElementList <ContentPage>(contentType);
                this.ContentTypes.Add(contentType);
            }

            // ensure events pages config exists
            var eventsConfig = this.ContentTypes[EventsModule.ModuleName];

            if (eventsConfig.Pages.Count == 0)
            {
                // add one setting for each provider
                var providers = EventsManager.GetManager().Providers;
                foreach (var provider in providers)
                {
                    // retrieve all pages that contain an EventsView
                    var eventsPages = App.WorkWith().Pages()
                                      .Where(p => p.Page != null && p.ShowInNavigation && p.Page.Controls.Where(c => c.ObjectType.StartsWith(typeof(EventsView).FullName)).Count() > 0)
                                      .Get();

                    // attempt to locate the default page
                    foreach (var page in eventsPages)
                    {
                        string providerName;

                        // retrieve the events view control
                        var eventsView = page.Page.Controls.Where(c => c.ObjectType.StartsWith(typeof(EventsView).FullName)).First();
                        if (eventsView == null)
                        {
                            continue;
                        }

                        // determine if there is a modified control definition
                        var controlDefinition = eventsView.Properties.Where(p => p.Name == "ControlDefinition").FirstOrDefault();
                        if (controlDefinition == null)
                        {
                            // control uses default provider
                            providerName = EventsManager.GetDefaultProviderName();
                        }
                        else
                        {
                            // search for modified provider name
                            var providerNameProperty = controlDefinition.ChildProperties.Where(p => p.Name == "ProviderName").FirstOrDefault();
                            if (providerNameProperty == null)
                            {
                                // control is modified but still uses default provider
                                providerName = EventsManager.GetDefaultProviderName();
                            }
                            else
                            {
                                // get custom provider name
                                providerName = providerNameProperty.Value;
                            }
                        }

                        // make sure specified provider matches the current provider
                        if (providerName != provider.Name)
                        {
                            continue;
                        }

                        // skip page if it is a details-mode page
                        var displayModeProperty = eventsView.Properties.Where(p => p.Name == "ContentViewDisplayMode").SingleOrDefault();
                        if (displayModeProperty != null && displayModeProperty.Value == Telerik.Sitefinity.Web.UI.ContentUI.Enums.ContentViewDisplayMode.Detail.ToString())
                        {
                            continue;
                        }

                        // save page to config
                        var eventsPage = new ContentPage(eventsConfig.Pages);
                        eventsPage.DefaultPageUrl = page.GetFullUrl();
                        eventsPage.Name           = providerName;
                        eventsPage.Include        = true;
                        eventsPage.ProviderName   = providerName;
                        eventsConfig.Pages.Add(eventsPage);

                        // stop search for default page, move to next provider (if any)
                        break;
                    }
                }
            }

            // ensure blog config exists
            if (!this.ContentTypes.ContainsKey(BlogsModule.ModuleName))
            {
                var contentType = new ContentType(this.ContentTypes);
                contentType.Name  = BlogsModule.ModuleName;
                contentType.Pages = new ConfigElementList <ContentPage>(contentType);
                this.ContentTypes.Add(contentType);
            }

            // ensure blogs pages config exist
            var blogsConfig = this.ContentTypes[BlogsModule.ModuleName];

            if (blogsConfig.Pages.Count == 0)
            {
                // add a config setting for each provider
                var providers = BlogsManager.GetManager().Providers;
                foreach (var provider in providers)
                {
                    // retrieve all in the provider
                    var blogs = App.Prepare().SetContentProvider(provider.Name).WorkWith().Blogs().Get();

                    // add a config setting for each blog
                    foreach (var blog in blogs)
                    {
                        // make sure default page is set
                        if (!blog.DefaultPageId.HasValue || blog.DefaultPageId.Value == Guid.Empty)
                        {
                            continue;
                        }

                        // get default page url
                        var defaultPage = App.WorkWith().Page(blog.DefaultPageId.Value).Get();
                        if (defaultPage == null)
                        {
                            continue;
                        }

                        // save default blog page to config
                        var blogPage = new ContentPage(blogsConfig.Pages);
                        blogPage.DefaultPageUrl = defaultPage.GetFullUrl();
                        blogPage.Name           = blog.UrlName;
                        blogPage.Include        = true;
                        blogPage.ProviderName   = provider.Name;
                        blogsConfig.Pages.Add(blogPage);
                    }
                }
            }
        }
예제 #31
0
        private List <NewsResult> GetBlenedResult_org(out int hitCount, string term, int skip, int take)
        {
            var results = BlendedNewsHelper.GetNewsItems(Providers, SearchIndex, out hitCount, Categories, term, skip, take);

            log.InfoFormat("There are {0}, results, prov:{1}, idx:{2}, term:{3}, take:{4}",
                           results.HitCount,
                           Providers?.Join(","),
                           SearchIndex,
                           Categories?.Join(","),
                           term, take);

            List <NewsResult> resultSet = new List <NewsResult>();
            //log.Info("content, title, Id \r\n");
            StringBuilder sb = new StringBuilder();

            foreach (var result in results)
            {
                //newsResult.DisplayDate = result.GetValue("DisplayDate").ToString();
                //
                try
                {
                    var ctnType = result.GetValue("ContentType")?.ToString() ?? string.Empty;

                    var        featured   = result.GetValue("FeaturedRank")?.ToString() ?? string.Empty;
                    NewsResult newsResult = new NewsResult()
                    {
                        ImageId  = result.GetValue("ImageId")?.ToString() ?? string.Empty,
                        Title    = result.GetValue("Title")?.ToString() ?? string.Empty,
                        Summary  = result.GetValue("Summary")?.ToString() ?? string.Empty,
                        Featured = !string.IsNullOrEmpty(featured) && (featured == "1" ? true : false),
                        Content  = result.GetValue("Content")?.ToString() ?? string.Empty,
                        Link     = result.GetValue("Link")?.ToString() ?? string.Empty
                    };

                    var    dynaManager = DynamicModuleManager.GetManager();
                    string txtId       = result.GetValue("Id")?.ToString() ?? String.Empty;
                    log.InfoFormat("try to get from iD:{0} ofType:{1}-title:{2}", txtId, ctnType, newsResult.Title);
                    try
                    {
                        if (!string.IsNullOrEmpty(ctnType) && !string.IsNullOrEmpty(txtId) && txtId.IsGuid())
                        {
                            Guid itemId = new Guid(txtId);
                            if (ctnType.IndexOf("BlogPost") > 0)
                            {
                                var manager = BlogsManager.GetManager();
                                var bp      = manager.GetBlogPosts()
                                              //.Where(c => c.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live)
                                              .FirstOrDefault(b => b.Id == itemId);
                                if (bp != null)
                                {
                                    bp = manager.Lifecycle.GetLive(bp) as BlogPost;
                                    log.InfoFormat("has item:{0}-date:{1}", bp?.GetType()?.FullName, bp?.GetValue("DisplayDate")?.ToString() ?? string.Empty);
                                    newsResult.DisplayDate = bp?.GetValue("DisplayDate")?.ToString() ?? string.Empty;
                                }
                            }
                            else
                            {
                                var item = dynaManager.GetDataItems(TypeResolutionService.ResolveType(ctnType))
                                           .Where(c => c.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live)
                                           .FirstOrDefault(c => c.Id == itemId);

                                log.InfoFormat("has item:{0}-date:{1}", item?.GetType()?.FullName, item?.GetValue("DisplayDate")?.ToString() ?? string.Empty);
                                newsResult.DisplayDate = item?.GetValue("DisplayDate")?.ToString() ?? string.Empty;
                            }

                            /*if (result.Fields.Any(x => x.Name == "DisplayDate") && item?.GetValue("DisplayDate") != null)
                             * {
                             *  newsResult.DisplayDate = item.GetValue("DisplayDate").ToString() ?? string.Empty;
                             * }*/
                        }
                    }
                    catch (Exception ex)
                    {
                        log.InfoFormat("failedToGetDateItemType:{0}-id:{1}, msg:{2}", ctnType, txtId, ex.Message);
                    }

                    string formatString = "yyyyMMddHHmmssfff";
                    // seem like there are already assing below
                    if (!String.IsNullOrEmpty(result.GetValue("PublicationDate")?.ToString()))
                    {
                        DateTime pubd = DateTime.MinValue;
                        //DateTime dt = DateTime.ParseExact(result.GetValue("PublicationDate").ToString(), formatString, null);
                        //newsResult.PublicationDate = dt.ToLocalTime();
                        DateTime.TryParseExact(result.GetValue("PublicationDate").ToString(), formatString, new CultureInfo("en-US"), DateTimeStyles.None, out pubd);
                        newsResult.PublicationDate = pubd;
                        //log.InfoFormat("pubd:{0}", pubd.ToString("MMMM d, yyyy"));
                        //sb.Append("PubDate:").Append(pubd).Append("\r");
                    }

                    if (result.Fields.Any(x => x.Name == "DateField"))
                    {
                        try
                        {
                            /*DateTime dt2 = DateTime.ParseExact(result.GetValue("DateField").ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                             * newsResult.DateField = dt2.ToLocalTime();*/
                            if (!String.IsNullOrEmpty(result.GetValue("DateField")?.ToString()))
                            {
                                DateTime eDateTime = DateTime.MinValue;
                                DateTime.TryParseExact(result.GetValue("DateField").ToString(), "MM/dd/yyyy HH:mm:ss", new CultureInfo("en-US"), DateTimeStyles.None, out eDateTime);
                                newsResult.DateField = eDateTime;
                                //log.InfoFormat("datef:{0}", eDateTime.ToString("MMMM d, yyyy"));
                            }
                        }
                        catch (Exception ex)
                        {
                            log.ErrorFormat("GetBlendedResult-DateField:{0}, inner:{1}, stack:{2}", ex.Message, ex.InnerException?.Message, ex.StackTrace);
                        }
                    }

                    if (string.IsNullOrWhiteSpace(newsResult.Summary) && !string.IsNullOrWhiteSpace(newsResult.Content))
                    {
                        newsResult.Summary = SummaryParser.GetSummary(newsResult.Content, new SummarySettings(SummaryMode.Words, 40, true));
                    }

                    resultSet.Add(newsResult);
                }
                catch (Exception ex)
                {
                    log.InfoFormat("bled-createNewsResult:{0}", ex.Message);
                }



                //newsResult.ImageCaption = result.GetValue("ImageCaption").ToString();

                // testing below

                /*if (!String.IsNullOrEmpty(result.GetValue("PublicationDate")?.ToString()))
                 * {
                 *  //DateTime dt = DateTime.ParseExact(result.GetValue("PublicationDate").ToString(), formatString, null);
                 *  //newsResult.PublicationDate = dt.ToLocalTime();
                 *  DateTime.TryParseExact(result.GetValue("PublicationDate").ToString(), formatString, new CultureInfo("en-US"), DateTimeStyles.None, out eDateTime);
                 *  newsResult.DisplayDate = eDateTime.ToLocalTime().ToShortDateString();
                 * }*/
                ///
            }
            return(resultSet);
        }
예제 #32
0
        private static void EnsureBlogPostThreadExists(string threadKey, IAuthor author, string threadTitle, BlogsManager manager, string language, ICommentService cs)
        {
            ThreadFilter threadFilter = new ThreadFilter();
            threadFilter.ThreadKey.Add(threadKey);
            var thread = cs.GetThreads(threadFilter).SingleOrDefault();

            if (thread == null)
            {
                var groupKey = ControlUtilities.GetUniqueProviderKey(typeof(BlogsManager).FullName, manager.Provider.Name);

                EnsureBlogPostGroupExists(groupKey, author, cs);

                var threadProxy = new ThreadProxy(threadTitle, typeof(BlogPost).FullName, groupKey, author) { Language = language, Key = threadKey };
                thread = cs.CreateThread(threadProxy);
            }
        }
예제 #33
0
        private static void EnsureBlogPostThreadExists(string threadKey, IAuthor author, string threadTitle, BlogsManager manager, string language, ICommentService cs)
        {
            ThreadFilter threadFilter = new ThreadFilter();

            threadFilter.ThreadKey.Add(threadKey);
            var thread = cs.GetThreads(threadFilter).SingleOrDefault();

            if (thread == null)
            {
                var groupKey = ControlUtilities.GetUniqueProviderKey(typeof(BlogsManager).FullName, manager.Provider.Name);

                EnsureBlogPostGroupExists(groupKey, author, cs);

                var threadProxy = new ThreadProxy(threadTitle, typeof(BlogPost).FullName, groupKey, author)
                {
                    Language = language, Key = threadKey
                };
                thread = cs.CreateThread(threadProxy);
            }
        }