Example #1
0
 public static void FromPageContent(PageContent pageContent, PageContentEntity entity)
 {
     entity.EditedOn = pageContent.EditedOn;
     entity.EditedBy = pageContent.EditedBy;
     entity.Text = pageContent.Text;
     entity.VersionNumber = pageContent.VersionNumber;
 }
 public void OnPageContentConfigured(PageContent pageContent)
 {
     if (PageContentConfigured != null)
     {
         PageContentConfigured(new SingleItemEventArgs<PageContent>(pageContent));
     }
 }
        public PageContentProjection Create(PageContent pageContent)
        {
            IContentAccessor contentAccessor = null;
            Type contentType;
            if (pageContent.Content is IProxy)
            {
                contentType = pageContent.Content.GetType().BaseType;
            }
            else
            {
                contentType = pageContent.Content.GetType();
            }

            string key = "CONTENTRENDERER-" + contentType.Name.ToUpperInvariant();

            if (containerProvider.CurrentScope.IsRegisteredWithKey<IContentAccessor>(key))
            {
                contentAccessor = containerProvider.CurrentScope
                    .ResolveKeyed<IContentAccessor>(key, new Parameter[]
                                                             {
                                                                 new PositionalParameter(0, pageContent.Content),
                                                                 new PositionalParameter(1, pageContent.PageContentOptions.Cast<IPageContentOption>().ToList())
                                                             });
            }

            if (contentAccessor == null)
            {
                throw new CmsException(string.Format("No content accessor found for the content type {0}.", pageContent.Content.GetType().FullName));
            }

            PageContentProjection pageContentProjection = new PageContentProjection(pageContent,  contentAccessor);
            return pageContentProjection;
        }
        public virtual PageContent GetContent(WebResponse response)
        {
            using (MemoryStream memoryStream = GetRawData(response))
            {
                String charset = GetCharsetFromHeaders(response);

                if (charset == null) {
                    memoryStream.Seek(0, SeekOrigin.Begin);

                    // Do not wrap in closing statement to prevent closing of this stream.
                    StreamReader srr = new StreamReader(memoryStream, Encoding.ASCII);
                    String body = srr.ReadToEnd();
                    charset = GetCharsetFromBody(body);
                }
                memoryStream.Seek(0, SeekOrigin.Begin);

                charset = CleanCharset(charset);
                Encoding e = GetEncoding(charset);
                string content = "";
                using (StreamReader sr = new StreamReader(memoryStream, e))
                {
                    content = sr.ReadToEnd();
                }

                PageContent pageContent = new PageContent();
                pageContent.Bytes = memoryStream.ToArray();
                pageContent.Charset = charset;
                pageContent.Encoding = e;
                pageContent.Text = content;

                return pageContent;
            }
        }
        public void Edit(PageContent content)
        {
            DbCommand comm = this.GetCommand("SPPageContentsUpdate");
            comm.AddParameter<string>(this.Factory, "PageContentShortName", content.ShortName);
            comm.AddParameter<string>(this.Factory, "PageContentTitle", content.Title);
            comm.AddParameter<string>(this.Factory, "PageContentBody", content.Body);

            comm.SafeExecuteNonQuery();
        }
        public void PageContent_Add_Edit_List_Detail_Delete_Test()
        {
            var controller = TestHelper.Resolve<PageContentsController>();
            controller.ControllerContext = new FakeControllerContext(controller);

            var content = new PageContent()
            {
                Title = "Dummy Test Content"
                ,Body = "<p>Hello world</p>"
            };
            PageContent contentFail = new PageContent();
            #region Add
            var result = controller.Add(content);
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            Assert.IsNotNull(content.ShortName);

            controller = TestHelper.Resolve<PageContentsController>();
            controller.ControllerContext = new FakeControllerContext(controller);
            result = controller.Add(contentFail);
            //Must return to the view
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            #endregion

            #region Edit
            content.Title += " (Edited)";
            controller = TestHelper.Resolve<PageContentsController>();
            controller.ControllerContext = new FakeControllerContext(controller);
            result = controller.Edit(content.ShortName, content);
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));

            controller = TestHelper.Resolve<PageContentsController>();
            controller.ControllerContext = new FakeControllerContext(controller);
            result = controller.Edit(content.ShortName, contentFail);
            //Must return to the view
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            #endregion

            #region List and Detail
            result = controller.Detail(content.ShortName);
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            Assert.IsNotNull(controller.ViewData.Model);
            //List
            result = controller.List();
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            Assert.IsTrue(((IList)controller.ViewData.Model).Count > 0);
            #endregion

            #region Delete
            result = controller.Delete(content.ShortName);
            Assert.IsInstanceOfType(result, typeof(JsonResult));
            #endregion
        }
        protected void FillPageContentWithOptions(Content content, PageContent pageContent)
        {
            var po1 = TestDataProvider.CreateNewPageContentOption(pageContent);
            po1.Key = content.ContentOptions[0].Key;
            var po2 = TestDataProvider.CreateNewPageContentOption(pageContent);
            po2.Key = content.ContentOptions[1].Key;
            var po3 = TestDataProvider.CreateNewPageContentOption(pageContent);
            po3.Key = Guid.NewGuid().ToString();

            pageContent.Options = new List<PageContentOption>();
            pageContent.Options.Add(po1);
            pageContent.Options.Add(po2);
            pageContent.Options.Add(po3);
        }
Example #8
0
        public static PageContent ToPageContent(PageContentEntity entity)
        {
            if (entity == null)
                return null;

            PageContent pageContent = new PageContent();
            pageContent.Id = entity.Id;
            pageContent.EditedOn = entity.EditedOn;
            pageContent.EditedBy = entity.EditedBy;
            pageContent.Text = entity.Text;
            pageContent.VersionNumber = entity.VersionNumber;
            pageContent.Page = ToPage(entity.Page);

            return pageContent;
        }
        protected void btnSaveInfo_Click(object sender, EventArgs e)
        {
            BLL.ContactDetails objdata = new ContactDetails();
            objdata.LoadByPrimaryKey(1);
            objdata.Telephone = txtTelephone.Text;
            objdata.Email = txtMail.Text;
            objdata.Location = txtLocation.Text;
            objdata.Facebook = txtFacebook.Text;
            objdata.Save();

            ClientScript.RegisterStartupScript(this.GetType(), "getCKEditor", "$(#hfPageContect).val() = $('#txtPageContent').ckeditorGet();");
            BLL.PageContent objPC = new PageContent();
            objPC.LoadByPrimaryKey(1);
            objPC.PlaceHolder1 = hfPageContect.Value;
            objPC.Save();
            Response.Redirect("ManageContactInformation.aspx");
        }
Example #10
0
		public static PageContent ToPageContent(PageContentEntity entity)
		{
			if (entity == null)
				return null;

			PageContent pageContent = new PageContent();
			pageContent.Id = entity.Id;
			pageContent.EditedOn = entity.EditedOn;
			pageContent.EditedBy = entity.EditedBy;
			pageContent.Text = entity.Text;
			pageContent.VersionNumber = entity.VersionNumber;
			pageContent.Page = ToPage(entity.Page);
            pageContent.ProjectStart = entity.ProjectStart;
            pageContent.ProjectEnd = entity.ProjectEnd;
            pageContent.ProjectEstimatedTime = entity.ProjectEstimatedTime;
            pageContent.ProjectStatus = entity.ProjectStatus;
            pageContent.ProjectLanguage = entity.ProjectLanguage;
            pageContent.orgID = entity.orgID;

			return pageContent;
		}
Example #11
0
        /// <summary>
        /// Adds the page to the database.
        /// </summary>
        /// <param name="summary">The summary details for the page.</param>
        /// <returns>A <see cref="PageSummary"/> for the newly added page.</returns>
        /// <exception cref="DatabaseException">An NHibernate (database) error occurred while saving.</exception>
        /// <exception cref="SearchException">An error occurred adding the page to the search index.</exception>
        public PageSummary AddPage(PageSummary summary)
        {
            try
            {
                string currentUser = RoadkillContext.Current.CurrentUsername;

                Page page = new Page();
                page.Title = summary.Title;
                page.Tags = summary.Tags.CleanTags();
                page.CreatedBy = AppendIpForAppHarbor(currentUser);
                page.CreatedOn = DateTime.Now;
                page.ModifiedOn = DateTime.Now;
                page.ModifiedBy = AppendIpForAppHarbor(currentUser);
                NHibernateRepository.Current.SaveOrUpdate<Page>(page);

                PageContent pageContent = new PageContent();
                pageContent.VersionNumber = 1;
                pageContent.Text = summary.Content;
                pageContent.EditedBy = AppendIpForAppHarbor(currentUser);
                pageContent.EditedOn = DateTime.Now;
                pageContent.Page = page;
                NHibernateRepository.Current.SaveOrUpdate<PageContent>(pageContent);

                // Update the lucene index
                try
                {
                    SearchManager.Current.Add(page.ToSummary());
                }
                catch (SearchException)
                {
                    // TODO: log
                }

                return page.ToSummary();
            }
            catch (HibernateException e)
            {
                throw new DatabaseException(e, "An error occurred while adding page '{0}' to the database", summary.Title);
            }
        }
 public void Add(PageContent content)
 {
     content.ValidateFields();
     SetAvailableShortName(content);
     _dataAccess.Add(content);
 }
        protected virtual void GetBlogPostAndContentEntities(BlogPostViewModel request, IPrincipal principal, string[] roles, 
            ref bool isNew, out BlogPostContent content, out PageContent pageContent , out BlogPost blogPost)
        {
            content = null;
            pageContent = null;

            // Loading blog post and it's content, or creating new, if such not exists
            if (!isNew)
            {
                var blogPostFuture = repository
                    .AsQueryable<BlogPost>(b => b.Id == request.Id)
                    .ToFuture();

                content = repository
                    .AsQueryable<BlogPostContent>(c => c.PageContents.Any(x => x.Page.Id == request.Id && !x.IsDeleted))
                    .ToFuture()
                    .FirstOrDefault();

                blogPost = blogPostFuture.FirstOne();

                if (configuration.Security.AccessControlEnabled)
                {
                    accessControlService.DemandAccess(blogPost, principal, AccessLevel.ReadWrite, roles);
                }

                if (content != null)
                {
                    // Check if user has confirmed the deletion of content
                    if (!request.IsUserConfirmed && blogPost.IsMasterPage)
                    {
                        var hasAnyChildren = contentService.CheckIfContentHasDeletingChildren(blogPost.Id, content.Id, request.Content);
                        if (hasAnyChildren)
                        {
                            var message = PagesGlobalization.SaveContent_ContentHasChildrenContents_RegionDeleteConfirmationMessage;
                            var logMessage = string.Format("User is trying to delete content regions which has children contents. Confirmation is required. ContentId: {0}, PageId: {1}",
                                    content.Id, blogPost.Id);
                            throw new ConfirmationRequestException(() => message, logMessage);
                        }
                    }

                    var bpRef = blogPost;
                    var contentRef = content;
                    pageContent = repository.FirstOrDefault<PageContent>(c => c.Page == bpRef && !c.IsDeleted && c.Content == contentRef);
                }
            }
            else
            {
                blogPost = new BlogPost();
            }

            if (pageContent == null)
            {
                pageContent = new PageContent { Page = blogPost };
            }
        }
        private IEnumerable<ChildContentProjection> CreateListOfChildProjectionsRecursively(
            bool canManageContent, 
            Guid? previewPageContentId, 
            PageContent pageContent,
            IEnumerable<ChildContent> children)
        {
            List<ChildContentProjection> childProjections;
            if (children != null && children.Any(c => !c.Child.IsDeleted))
            {
                childProjections = new List<ChildContentProjection>();
                foreach (var child in children.Where(c => !c.Child.IsDeleted).Distinct())
                {
                    var childProjection = (ChildContentProjection)CreatePageContentProjection(canManageContent, pageContent, child, previewPageContentId);
                    if (childProjection != null)
                    {
                        childProjections.Add(childProjection);
                    }
                }
            }
            else
            {
                childProjections = null;
            }

            return childProjections;
        }
        public PageContentProjection CreatePageContentProjection(
            bool canManageContent,
            PageContent pageContent,
            IChildContent childContent = null,
            Guid? previewPageContentId = null, 
            bool retrieveCorrectVersion = true)
        {
            Models.Content contentToProject = null;
            var content = childContent == null ? pageContent.Content : (Models.Content)childContent.ChildContent;

            if (!retrieveCorrectVersion)
            {
                contentToProject = content;
            }
            else
            {
                if (childContent == null && previewPageContentId != null && previewPageContentId.Value == pageContent.Id)
                {
                    // Looks for the preview content version first.
                    if (content.Status == ContentStatus.Preview)
                    {
                        contentToProject = content;
                    }
                    else
                    {
                        contentToProject = content.History.FirstOrDefault(f => f.Status == ContentStatus.Preview);
                    }
                }

                if (contentToProject == null && (canManageContent || previewPageContentId != null))
                {
                    // Look for the draft content version if we are in the edit or preview mode.
                    if (content.Status == ContentStatus.Draft)
                    {
                        contentToProject = content;
                    }
                    else
                    {
                        contentToProject = content.History.FirstOrDefault(f => f.Status == ContentStatus.Draft);
                    }
                }

                if (contentToProject == null && content.Status == ContentStatus.Published)
                {
                    IHtmlContent htmlContent = content as IHtmlContent;
                    if (!canManageContent && htmlContent != null
                        && (DateTime.Now < htmlContent.ActivationDate || (htmlContent.ExpirationDate.HasValue && htmlContent.ExpirationDate.Value < DateTime.Now)))
                    {
                        // Invisible for user because of activation dates.
                        return null;
                    }

                    // Otherwise take published version.
                    contentToProject = content;
                }
            }

            if (contentToProject == null)
            {
                throw new CmsException(string.Format("A content version was not found to project on the page. PageContent={0}; CanManageContent={1}, PreviewPageContentId={2};", pageContent, canManageContent, previewPageContentId));
            }

            // Create a collection of child contents (child widgets) projections
            var childContentsProjections = CreateListOfChildProjectionsRecursively(canManageContent, previewPageContentId, pageContent, contentToProject.ChildContents);

            Func<IPageContent, IContent, IContentAccessor, IEnumerable<ChildContentProjection>, PageContentProjection> createProjectionDelegate;
            if (childContent != null)
            {
                createProjectionDelegate = (pc, c, a, ccpl) => new ChildContentProjection(pc, childContent, a, ccpl);
            }
            else
            {
                createProjectionDelegate = (pc, c, a, ccpl) => new PageContentProjection(pc, c, a, ccpl);
            }

            var optionValues = childContent != null ? childContent.Options : pageContent.Options;
            var options = optionService.GetMergedOptionValues(contentToProject.ContentOptions, optionValues);
            return pageContentProjectionFactory.Create(pageContent, contentToProject, options, childContentsProjections, createProjectionDelegate);
        }
		/// <summary>
		/// This updates an existing set of text and is used for page rename updates.
		/// To add a new version of a page, use AddNewPageContentVersion
		/// </summary>
		/// <param name="content"></param>
		public void UpdatePageContent(PageContent content)
		{
			PageContentEntity entity = UnitOfWork.FindById<PageContentEntity>(content.Id);
			if (entity != null)
			{
				ToEntity.FromPageContent(content, entity);
				UnitOfWork.SaveChanges();
				content = FromEntity.ToPageContent(entity);
			}
		}
Example #17
0
        protected virtual void GetBlogPostAndContentEntities(BlogPostViewModel request, IPrincipal principal, string[] roles, 
            ref bool isNew, out BlogPostContent content, out PageContent pageContent , out BlogPost blogPost)
        {
            content = null;
            pageContent = null;

            // Loading blog post and it's content, or creating new, if such not exists
            if (!isNew)
            {
                var blogPostFuture = repository
                    .AsQueryable<BlogPost>(b => b.Id == request.Id)
                    .ToFuture();

                content = repository
                    .AsQueryable<BlogPostContent>(c => c.PageContents.Any(x => x.Page.Id == request.Id && !x.IsDeleted))
                    .ToFuture()
                    .FirstOrDefault();

                blogPost = blogPostFuture.FirstOne();

                if (configuration.Security.AccessControlEnabled)
                {
                    accessControlService.DemandAccess(blogPost, principal, AccessLevel.ReadWrite, roles);
                }

                if (content != null)
                {
                    // Check if user has confirmed the deletion of content
                    if (!request.IsUserConfirmed && blogPost.IsMasterPage)
                    {
                        contentService.CheckIfContentHasDeletingChildrenWithException(blogPost.Id, content.Id, request.Content);
                    }

                    var bpRef = blogPost;
                    var contentRef = content;
                    pageContent = repository.FirstOrDefault<PageContent>(c => c.Page == bpRef && !c.IsDeleted && c.Content == contentRef);
                }
            }
            else
            {
                blogPost = new BlogPost();
            }

            if (pageContent == null)
            {
                pageContent = new PageContent { Page = blogPost };
            }
        }
 public void SetAvailableShortName(PageContent content)
 {
     content.ShortName = _dataAccess.GetAvailableShortName(content.ShortName);
 }
        /// <summary>
        /// Creates the test view model.
        /// </summary>
        /// <returns>Test view model</returns>
        private RenderPageViewModel CreateTestViewModel(bool extendModel = false)
        {
            var entity = new BlogPost
            {
                Title = "Fake Page Title",
                PageUrl = "/Fake/Page/Url/s",
                Id = new Guid("DB4C3C70-F5F3-44A1-9472-6155A9A77D89"),
                CreatedOn = new DateTime(2010, 11, 15),
                ModifiedOn = new DateTime(2012, 12, 3),
                CreatedByUser = "Fake Page Creator",
                ModifiedByUser = "Fake Page Modifier",
                MetaTitle = "Fake Page Meta Title",
                MetaKeywords = "Fake Page Meta Keywords",
                MetaDescription = "Fake Page MetaDescription",
                ActivationDate = new DateTime(2012, 5, 12),
                ExpirationDate = new DateTime(2013, 4, 18)
            };

            if (extendModel)
            {
                entity.Categories = new List<PageCategory>() { new PageCategory() { Category = new Category { Name = "Fake Category Name" }, Page = entity } };
                entity.Author = new Author { Name = "Fake Author Name" };
                entity.Image = new MediaImage { PublicUrl = "/Fake/Main/Image/Url/" };
                entity.SecondaryImage = new MediaImage { PublicUrl = "/Fake/Secondary/Image/Url/" };
                entity.FeaturedImage = new MediaImage { PublicUrl = "/Fake/Featured/Image/Url/" };
                entity.ActivationDate = new DateTime();

                var content = new BlogPostContent { ActivationDate = new DateTime(2012, 5, 12), ExpirationDate = new DateTime(2013, 4, 18) };
                var pageContent = new PageContent { Content = content, Page = entity };
                entity.PageContents = new List<PageContent> { pageContent };
            }

            var model = new RenderPageViewModel(entity)
                            {
                                Options = new List<IOptionValue>
                                              {
                                                  new OptionValueViewModel
                                                      {
                                                          OptionKey = OptionNames.Text,
                                                          OptionValue = "Fake Option Value",
                                                          Type = OptionType.Text
                                                      },

                                                  new OptionValueViewModel
                                                      {
                                                          OptionKey = OptionNames.Float,
                                                          OptionValue = 10.123456M,
                                                          Type = OptionType.Float
                                                      },

                                                  new OptionValueViewModel
                                                      {
                                                          OptionKey = OptionNames.Date,
                                                          OptionValue = new DateTime(2009, 4, 27),
                                                          Type = OptionType.DateTime
                                                      }
                                              }
                            };

            if (extendModel)
            {
                model.Contents = new List<PageContentProjection>();
                model.Contents.Add(
                    new PageContentProjection(
                        entity.PageContents[0],
                        entity.PageContents[0].Content,
                        new BlogPostContentAccessor((BlogPostContent)entity.PageContents[0].Content, new List<IOptionValue>())));
                model.ExtendWithPageData(entity);
                model.ExtendWithBlogData(entity);
            }

            return model;
        }
Example #20
0
        /// <summary>
        /// Updates the provided page.
        /// </summary>
        /// <param name="summary">The summary.</param>
        /// <exception cref="DatabaseException">An NHibernate (database) error occurred while updating.</exception>
        /// <exception cref="SearchException">An error occurred adding the page to the search index.</exception>
        public void UpdatePage(PageSummary summary)
        {
            try
            {
                string currentUser = RoadkillContext.Current.CurrentUsername;
                HistoryManager manager = new HistoryManager();

                Page page = Pages.FirstOrDefault(p => p.Id == summary.Id);
                page.Title = summary.Title;
                page.Tags = summary.Tags.CleanTags();
                page.ModifiedOn = DateTime.Now;
                page.ModifiedBy = AppendIpForAppHarbor(currentUser);

                // A second check to ensure a fake IsLocked POST doesn't work.
                if (RoadkillContext.Current.IsAdmin)
                    page.IsLocked = summary.IsLocked;

                NHibernateRepository.Current.SaveOrUpdate<Page>(page);

                PageContent pageContent = new PageContent();
                pageContent.VersionNumber = manager.MaxVersion(summary.Id) + 1;
                pageContent.Text = summary.Content;
                pageContent.EditedBy = AppendIpForAppHarbor(currentUser);
                pageContent.EditedOn = DateTime.Now;
                pageContent.Page = page;
                NHibernateRepository.Current.SaveOrUpdate<PageContent>(pageContent);

                // Update the lucene index
                SearchManager.Current.Update(page.ToSummary());
            }
            catch (HibernateException ex)
            {
                throw new DatabaseException(ex, "An error occurred updating the page with title '{0}' in the database", summary.Title);
            }
        }
Example #21
0
        protected override void MapExtraProperties(bool isNew, BlogPost entity, BlogPostContent content, PageContent pageContent, BlogPostViewModel model, IPrincipal principal)
        {
            var currentVersion = entity.Version;
            base.MapExtraProperties(isNew, entity, content, pageContent, model, principal);

            var modelExt = model as BlogPostViewModelExtender;
            if (modelExt != null)
            {
                // Restore version if not set from the extended model
                if (model.Version <= 0)
                {
                    entity.Version = currentVersion;
                }

                entity.SecondaryImage = modelExt.SecondaryImageId.HasValue ? repository.AsProxy<MediaImage>(modelExt.SecondaryImageId.Value) : null;
                entity.FeaturedImage = modelExt.FeaturedImageId.HasValue ? repository.AsProxy<MediaImage>(modelExt.FeaturedImageId.Value) : null;
                entity.IsArchived = modelExt.IsArchived;
                entity.UseNoFollow = modelExt.UseNoFollow;
                entity.UseNoIndex = modelExt.UseNoIndex;
                entity.MetaKeywords = modelExt.MetaKeywords;
                entity.MetaDescription = modelExt.MetaDescription;

                // If creating new and content / page content / region ids are set, enforce them to be set explicitly
                if (isNew && !model.ContentId.HasDefaultValue() && modelExt.PageContentId.HasValue && modelExt.RegionId.HasValue)
                {
                    pageContent.Id = modelExt.PageContentId.Value;
                    pageContent.Region = repository.AsProxy<Region>(modelExt.RegionId.Value);
                }

                // Set blog post Id, if it's set
                if (isNew && !model.Id.HasDefaultValue())
                {
                    entity.Id = model.Id;
                }

                // PublishedOn
                if (isNew && entity.Status == PageStatus.Published && modelExt.PublishedOn.HasValue)
                {
                    entity.PublishedOn = modelExt.PublishedOn.Value;
                }

                // Set layout / master page
                if (modelExt.MasterPageId.HasValue)
                {
                    entity.Layout = null;
                    if (isNew)
                    {
                        entity.MasterPage = repository
                            .AsQueryable<Page>(p => p.Id == modelExt.MasterPageId.Value)
                            .FetchMany(p => p.AccessRules)
                            .ToList()
                            .FirstOne();

                        if (modelExt.AccessRules == null)
                        {
                            AddDefaultAccessRules(entity, principal, entity.MasterPage);
                        }
                        masterPageService.SetPageMasterPages(entity, entity.MasterPage.Id);
                    }
                    else
                    {
                        entity.MasterPage = repository.AsProxy<Page>(modelExt.MasterPageId.Value);
                    }
                }
                else if (modelExt.LayoutId.HasValue)
                {
                    entity.Layout = repository.AsProxy<Layout>(modelExt.LayoutId.Value);
                    entity.MasterPage = null;
                    if (isNew && modelExt.AccessRules == null)
                    {
                        AddDefaultAccessRules(entity, principal, null);
                    }
                }

                // Add access rules from the request
                if (modelExt.AccessRules != null)
                {
                    if (entity.AccessRules == null)
                    {
                        entity.AccessRules = new List<AccessRule>();
                    }
                    else
                    {
                        entity.AccessRules.RemoveDuplicateEntities();
                    }
                    var accessRules = modelExt.AccessRules
                        .Select(r => (IAccessRule)new AccessRule
                        {
                            AccessLevel = (AccessLevel)(int)r.AccessLevel,
                            Identity = r.Identity,
                            IsForRole = r.IsForRole
                        }).ToList();

                    accessControlService.UpdateAccessControl(entity, accessRules);
                }
            }
        }
Example #22
0
        protected override void GetBlogPostAndContentEntities(BlogPostViewModel model, IPrincipal principal, string[] roles, 
            ref bool isNew, out BlogPostContent content, out PageContent pageContent , out BlogPost blogPost)
        {
            var modelExt = model as BlogPostViewModelExtender;
            if (!isNew && modelExt != null)
            {
                content = null;
                pageContent = null;

                blogPost = repository
                    .AsQueryable<BlogPost>(bp => bp.Id == model.Id)
                    .FetchMany(bp => bp.AccessRules)
                    .FetchMany(bp => bp.PageTags)
                    .ThenFetch(pt => pt.Tag)
                    .ToList()
                    .FirstOrDefault();

                if (blogPost != null)
                {
                    if (configuration.Security.AccessControlEnabled)
                    {
                        accessControlService.DemandAccess(blogPost, principal, AccessLevel.ReadWrite, roles);
                    }

                    if (modelExt.PageContentId.HasValue)
                    {
                        content = repository
                            .AsQueryable<BlogPostContent>(c => c.PageContents.Any(x => x.Page.Id == model.Id
                                && !x.IsDeleted && x.Id == modelExt.PageContentId.Value
                                && !x.IsDeleted && c.Id == model.ContentId))
                            .ToFuture()
                            .FirstOrDefault();

                        if (content == null)
                        {
                            const string message = "Cannot find a blog post content by specified blog post content and Id and page content Id.";
                            var logMessage = string.Format("{0} BlogId: {1}, BlogPostContentId: {2}, PageContentId: {3}", 
                                message, model.Id, model.ContentId, modelExt.PageContentId);
                            throw new ValidationException(() => message, logMessage);
                        }

                        pageContent = repository.First<PageContent>(pc => pc.Id == modelExt.PageContentId.Value);
                    }
                    else
                    {
                        content = repository
                            .AsQueryable<BlogPostContent>(c => c.PageContents.Any(x => x.Page.Id == model.Id && !x.IsDeleted) && !c.IsDeleted)
                            .ToFuture()
                            .FirstOrDefault();

                        if (content != null)
                        {
                            var contentRef = content;
                            pageContent = repository.FirstOrDefault<PageContent>(c => c.Page.Id == model.Id && !c.IsDeleted && c.Content == contentRef);
                        }
                    }
                }

                isNew = blogPost == null;
                if (isNew)
                {
                    blogPost = new BlogPost();
                    pageContent = new PageContent { Page = blogPost };
                }
            }
            else
            {
                base.GetBlogPostAndContentEntities(model, principal, roles, ref isNew, out content, out pageContent, out blogPost);
            }
        }
        private IList<PageContentProjection> CreateListOfChildRegionContentProjectionsRecursively(
            bool canManageContent,
            Guid? previewPageContentId, 
            PageContent pageContent,
            List<PageContent> allPageContents,
            Models.Content contentToProject,
            Guid? languageId)
        {
            var childRegionContentProjections = new List<PageContentProjection>();
            var childRegionPageContents = allPageContents.Where(apc => apc.Parent != null 
                && apc.Parent.Id == pageContent.Id
                && contentToProject.ContentRegions != null
                && contentToProject.ContentRegions.Any(cr => cr.Region == apc.Region));
            foreach (var childPageContent in childRegionPageContents)
            {
                var childRegionContentProjection = CreatePageContentProjection(canManageContent, childPageContent, allPageContents, null, previewPageContentId, languageId);
                childRegionContentProjections.Add(childRegionContentProjection);
            }

            return childRegionContentProjections;
        }
		public void DeletePageContent(PageContent pageContent)
		{
			PageContentEntity entity = UnitOfWork.FindById<PageContentEntity>(pageContent.Id);
			UnitOfWork.Remove(entity);
			UnitOfWork.SaveChanges();
		}
 protected virtual void MapExtraProperties(bool isNew, BlogPost entity, BlogPostContent content, PageContent pageContent, BlogPostViewModel model, IPrincipal principal)
 {
     entity.Version = model.Version;
 }
        /// <summary>
        /// Extracts and saves all textual content for a page.
        /// </summary>
        /// <param name="page">The page the content belongs to.</param>
        private void AddContent(Page page)
        {
            using (SqlConnection connection = new SqlConnection(_connectionString))
            {
                using (SqlCommand command = connection.CreateCommand())
                {
                    connection.Open();
                    command.CommandText = "SELECT * FROM PageContent WHERE Page = @Page";

                    SqlParameter parameter = new SqlParameter();
                    parameter.ParameterName = "@Page";
                    parameter.SqlDbType = System.Data.SqlDbType.VarChar;
                    parameter.Value = page.Title;
                    command.Parameters.Add(parameter);

                    List<PageContent> categories = new List<PageContent>();
                    bool hasContent = false;
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            PageContent content = new PageContent();
                            content.EditedBy = reader["User"].ToString();
                            content.EditedOn = (DateTime)reader["LastModified"];
                            content.Text = reader["Content"].ToString();
                            content.Text = CleanContent(content.Text);
                            content.VersionNumber = (int.Parse(reader["Revision"].ToString())) + 1;
                            content.Page = page;

                            NHibernateRepository.Current.SaveOrUpdate<PageContent>(content);
                            hasContent = true;
                        }
                    }

                    // For broken content, make sure the page has something
                    if (!hasContent)
                    {
                        PageContent content = new PageContent();
                        content.EditedBy = "unknown";
                        content.EditedOn = DateTime.Now;
                        content.Text = "";
                        content.VersionNumber = 1;
                        content.Page = page;

                        NHibernateRepository.Current.SaveOrUpdate<PageContent>(content);
                    }
                }
            }
        }
        /// <summary>
        /// Gets the view model for rendering widget preview.
        /// </summary>
        /// <param name="contentId">The content id.</param>
        /// <param name="user">The user.</param>
        /// <returns>
        /// View model for rendering widget preview
        /// </returns>
        public RenderPageViewModel GetContentPreviewViewModel(Guid contentId, IPrincipal user, bool allowJavaScript)
        {
            // Creating fake region.
            var regionGuid = new Guid(regionId);
            var region = new Region { Id = regionGuid, RegionIdentifier = regionIdentifier };
            var regionViewModel = new PageRegionViewModel { RegionId = regionGuid, RegionIdentifier = regionIdentifier };

            // Creating fake page content and loading it's children.
            var pageContent = new PageContent
            {
                Options = new List<PageContentOption>(),
                Region = region
            };

            pageContent.Content = repository
                .AsQueryable<ContentEntity>(c => c.Id == contentId)
                .FetchMany(f => f.ContentOptions)
                .FetchMany(f => f.ChildContents)
                .ThenFetch(f => f.Child)
                .FetchMany(f => f.ChildContents)
                .ThenFetchMany(f => f.Options)
                .ToList()
                .FirstOrDefault();

            if (pageContent.Content != null)
            {
                DemandAccess(user, RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent);
            }

            childContentService.RetrieveChildrenContentsRecursively(true, new[] { pageContent.Content });

            var contentProjection = contentProjectionService.CreatePageContentProjection(true, pageContent, new List<PageContent> { pageContent }, retrieveCorrectVersion: false);

            var pageViewModel = new RenderPageViewModel
                                    {
                                        Contents = new List<PageContentProjection> { contentProjection },
                                        Stylesheets = new List<IStylesheetAccessor> { contentProjection },
                                        Regions = new List<PageRegionViewModel> { regionViewModel },
                                        AreRegionsEditable = true,
                                        IsPreviewing = true
                                    };
            if (allowJavaScript)
            {
                pageViewModel.JavaScripts = new List<IJavaScriptAccessor> { contentProjection };
            }

            return pageViewModel;
        }
 public void Edit(PageContent content)
 {
     content.ValidateFields();
     _dataAccess.Edit(content);
 }
Example #29
0
        /// <summary>
        /// Saves the blog post.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="principal">The principal.</param>
        /// <returns>
        /// Saved blog post entity
        /// </returns>
        public BlogPost SaveBlogPost(BlogPostViewModel request, IPrincipal principal)
        {
            string[] roles;
            if (request.DesirableStatus == ContentStatus.Published)
            {
                accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.PublishContent);
                roles = new[] { RootModuleConstants.UserRoles.PublishContent };
            }
            else
            {
                accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.EditContent);
                roles = new[] { RootModuleConstants.UserRoles.EditContent };
            }

            Layout layout;
            Page masterPage;
            LoadLayout(out layout, out masterPage);

            if (masterPage != null)
            {
                var level = accessControlService.GetAccessLevel(masterPage, principal);
                if (level < AccessLevel.Read)
                {
                    var message = BlogGlobalization.SaveBlogPost_FailedToSave_InaccessibleMasterPage;
                    const string logMessage = "Failed to save blog post. Selected master page for page layout is inaccessible.";
                    throw new ValidationException(() => message, logMessage);
                }
            }

            var region = LoadRegion(layout, masterPage);
            var isNew = request.Id.HasDefaultValue();
            var userCanEdit = securityService.IsAuthorized(RootModuleConstants.UserRoles.EditContent);

            // UnitOfWork.BeginTransaction(); // NOTE: this causes concurrent data exception.

            BlogPost blogPost;
            BlogPostContent content = null;
            PageContent pageContent = null;
            Pages.Models.Redirect redirectCreated = null;

            // Loading blog post and it's content, or creating new, if such not exists
            if (!isNew)
            {
                var blogPostFuture = repository
                    .AsQueryable<BlogPost>(b => b.Id == request.Id)
                    .ToFuture();

                content = repository
                    .AsQueryable<BlogPostContent>(c => c.PageContents.Any(x => x.Page.Id == request.Id && !x.IsDeleted))
                    .ToFuture()
                    .FirstOrDefault();

                blogPost = blogPostFuture.FirstOne();

                if (cmsConfiguration.Security.AccessControlEnabled)
                {
                    accessControlService.DemandAccess(blogPost, principal, AccessLevel.ReadWrite, roles);
                }

                if (content != null)
                {
                    // Check if user has confirmed the deletion of content
                    if (!request.IsUserConfirmed && blogPost.IsMasterPage)
                    {
                        var hasAnyChildren = contentService.CheckIfContentHasDeletingChildren(blogPost.Id, content.Id, request.Content);
                        if (hasAnyChildren)
                        {
                            var message = PagesGlobalization.SaveContent_ContentHasChildrenContents_RegionDeleteConfirmationMessage;
                            var logMessage = string.Format("User is trying to delete content regions which has children contents. Confirmation is required. ContentId: {0}, PageId: {1}",
                                    content.Id, blogPost.Id);
                            throw new ConfirmationRequestException(() => message, logMessage);
                        }
                    }

                    pageContent = repository.FirstOrDefault<PageContent>(c => c.Page == blogPost && !c.IsDeleted && c.Content == content);
                }

                if (userCanEdit && !string.Equals(blogPost.PageUrl, request.BlogUrl) && request.BlogUrl != null)
                {
                    request.BlogUrl = urlService.FixUrl(request.BlogUrl);
                    pageService.ValidatePageUrl(request.BlogUrl, request.Id);
                    if (request.RedirectFromOldUrl)
                    {
                        var redirect = redirectService.CreateRedirectEntity(blogPost.PageUrl, request.BlogUrl);
                        if (redirect != null)
                        {
                            repository.Save(redirect);
                            redirectCreated = redirect;
                        }
                    }

                    blogPost.PageUrl = urlService.FixUrl(request.BlogUrl);
                }
            }
            else
            {
                blogPost = new BlogPost();
            }

            if (pageContent == null)
            {
                pageContent = new PageContent { Region = region, Page = blogPost };
            }

            // Push to change modified data each time.
            blogPost.ModifiedOn = DateTime.Now;
            blogPost.Version = request.Version;

            if (userCanEdit)
            {
                blogPost.Title = request.Title;
                blogPost.Description = request.IntroText;
                blogPost.Author = request.AuthorId.HasValue ? repository.AsProxy<Author>(request.AuthorId.Value) : null;
                blogPost.Category = request.CategoryId.HasValue ? repository.AsProxy<Category>(request.CategoryId.Value) : null;
                blogPost.Image = (request.Image != null && request.Image.ImageId.HasValue) ? repository.AsProxy<MediaImage>(request.Image.ImageId.Value) : null;
                if (isNew || request.DesirableStatus == ContentStatus.Published)
                {
                    blogPost.ActivationDate = request.LiveFromDate;
                    blogPost.ExpirationDate = TimeHelper.FormatEndDate(request.LiveToDate);
                }
            }

            if (isNew)
            {
                if (!string.IsNullOrWhiteSpace(request.BlogUrl))
                {
                    blogPost.PageUrl = urlService.FixUrl(request.BlogUrl);
                    pageService.ValidatePageUrl(blogPost.PageUrl);
                }
                else
                {
                    blogPost.PageUrl = CreateBlogPermalink(request.Title);
                }

                blogPost.MetaTitle = request.MetaTitle ?? request.Title;
                if (masterPage != null)
                {
                    blogPost.MasterPage = masterPage;
                    masterPageService.SetPageMasterPages(blogPost, masterPage.Id);
                }
                else
                {
                    blogPost.Layout = layout;
                }
                UpdateStatus(blogPost, request.DesirableStatus);
                AddDefaultAccessRules(blogPost, principal, masterPage);
            }
            else if (request.DesirableStatus == ContentStatus.Published
                || blogPost.Status == PageStatus.Preview)
            {
                // Update only if publishing or current status is preview.
                // Else do not change, because it may change from published to draft status 
                UpdateStatus(blogPost, request.DesirableStatus);
            }

            // Create content.
            var newContent = new BlogPostContent
            {
                Id = content != null ? content.Id : Guid.Empty,
                Name = request.Title,
                Html = request.Content ?? string.Empty,
                EditInSourceMode = request.EditInSourceMode,
                ActivationDate = request.LiveFromDate,
                ExpirationDate = TimeHelper.FormatEndDate(request.LiveToDate)
            };

            // Preserve content if user is not authorized to change it.
            if (!userCanEdit)
            {
                if (content == null)
                {
                    throw new SecurityException("Forbidden: Access is denied."); // User has no rights to create new content.
                }

                var contentToPublish = (BlogPostContent)(content.History != null
                    ? content.History.FirstOrDefault(c => c.Status == ContentStatus.Draft) ?? content
                    : content);

                newContent.Name = contentToPublish.Name;
                newContent.Html = contentToPublish.Html;
            }

            content = (BlogPostContent)contentService.SaveContentWithStatusUpdate(newContent, request.DesirableStatus);
            pageContent.Content = content;

            blogPost.PageUrlHash = blogPost.PageUrl.UrlHash();
            blogPost.UseCanonicalUrl = request.UseCanonicalUrl;

            repository.Save(blogPost);
            repository.Save(content);
            repository.Save(pageContent);

            pageContent.Content = content;
            blogPost.PageContents = new [] {pageContent};

            IList<Tag> newTags = null;
            if (userCanEdit)
            {
                tagService.SavePageTags(blogPost, request.Tags, out newTags);
            }

            // Commit
            unitOfWork.Commit();

            // Notify about new or updated blog post.
            if (isNew)
            {
                Events.BlogEvents.Instance.OnBlogCreated(blogPost);
            }
            else
            {
                Events.BlogEvents.Instance.OnBlogUpdated(blogPost);

            }

            // Notify about new created tags.
            Events.RootEvents.Instance.OnTagCreated(newTags);

            // Notify about redirect creation.
            if (redirectCreated != null)
            {
                Events.PageEvents.Instance.OnRedirectCreated(redirectCreated);
            }

            return blogPost;
        }
        /// <summary>
        /// Clones the content of the page.
        /// </summary>
        /// <param name="pageContent">Content of the page.</param>
        /// <param name="newPage">The new page.</param>
        private void ClonePageContent(PageContent pageContent, PageProperties newPage)
        {
            var newPageContent = new PageContent();
            newPageContent.Page = newPage;
            newPageContent.Order = pageContent.Order;
            newPageContent.Region = pageContent.Region;

            if (pageContent.Content is HtmlContentWidget || pageContent.Content is ServerControlWidget)
            {
                // Do not need to clone widgets.
                newPageContent.Content = pageContent.Content;
            }
            else
            {
                newPageContent.Content = pageContent.Content.Clone();

                var draft = pageContent.Content.History.FirstOrDefault(c => c.Status == ContentStatus.Draft && !c.IsDeleted);
                if (pageContent.Content.Status == ContentStatus.Published && draft != null)
                {
                    if (newPageContent.Content.History == null)
                    {
                        newPageContent.Content.History = new List<Root.Models.Content>();
                    }

                    var draftClone = draft.Clone();
                    draftClone.Original = newPageContent.Content;
                    newPageContent.Content.History.Add(draftClone);
                    repository.Save(draftClone);
                }
            }

            // Clone page content options.
            foreach (var option in pageContent.Options.Distinct())
            {
                if (newPageContent.Options == null)
                {
                    newPageContent.Options = new List<PageContentOption>();
                }

                var newOption = new PageContentOption
                {
                    Key = option.Key,
                    Value = option.Value,
                    Type = option.Type,
                    PageContent = newPageContent,
                    CustomOption = option.CustomOption
                };
                newPageContent.Options.Add(newOption);
                repository.Save(newOption);
            }

            repository.Save(newPageContent);
        }