/// <summary>
        /// Initializes a new instance of the <see cref="RenderBlogPostViewModel" /> class.
        /// </summary>
        /// <param name="blogPost">The blog post.</param>
        /// <param name="content">The content.</param>
        public RenderBlogPostViewModel(BlogPost blogPost = null, BlogPostContent content = null)
        {
            if (content != null)
            {
                ActivationDate = content.ActivationDate;
                ExpirationDate = content.ExpirationDate;
            }

            if (blogPost != null)
            {
                if (blogPost.Author != null)
                {
                    Author = new RenderBlogPostAuthorViewModel(blogPost.Author);
                }

                if (content == null)
                {
                    ActivationDate = blogPost.ActivationDate;
                    ExpirationDate = blogPost.ExpirationDate;
                }
            }
        }
예제 #2
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;
        }
예제 #3
0
        /// <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 = "******",
                ModifiedByUser = "******",
                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;
        }
 protected virtual void MapExtraProperties(bool isNew, BlogPost entity, BlogPostContent content, PageContent pageContent, BlogPostViewModel model, IPrincipal principal)
 {
     entity.Version = model.Version;
 }
        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 };
            }
        }
 protected virtual BlogPostContent SaveContentWithStatusUpdate(bool isNew, BlogPostContent newContent, BlogPostViewModel request, IPrincipal principal)
 {
     return (BlogPostContent)contentService.SaveContentWithStatusUpdate(newContent, request.DesirableStatus);
 }
        /// <summary>
        /// Saves the blog post.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="childContentOptionValues">The child content option values.</param>
        /// <param name="principal">The principal.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// Saved blog post entity
        /// </returns>
        /// <exception cref="System.ComponentModel.DataAnnotations.ValidationException"></exception>
        /// <exception cref="SecurityException">Forbidden: Access is denied.</exception>
        public BlogPost SaveBlogPost(BlogPostViewModel request, IList<ContentOptionValuesViewModel> childContentOptionValues, IPrincipal principal, out string[] errorMessages)
        {
            errorMessages = new string[0];
            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 };
            }

            var isNew = request.Id.HasDefaultValue();
            var userCanEdit = securityService.IsAuthorized(RootModuleConstants.UserRoles.EditContent);

            ValidateData(isNew, request);

            BlogPost blogPost;
            BlogPostContent content;
            PageContent pageContent;
            GetBlogPostAndContentEntities(request, principal, roles, ref isNew, out content, out pageContent, out blogPost);
            var beforeChange = new UpdatingBlogModel(blogPost);

            // Master page / layout
            Layout layout;
            Page masterPage;
            Region region;
            LoadDefaultLayoutAndRegion(out layout, out masterPage, out region);

            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);
                }
            }

            if (pageContent.Region == null)
            {
                pageContent.Region = region;
            }

            // Load master pages for updating page's master path and page's children master path
            IList<Guid> newMasterIds;
            IList<Guid> oldMasterIds;
            IList<Guid> childrenPageIds;
            IList<MasterPage> existingChildrenMasterPages;
            PrepareForUpdateChildrenMasterPages(isNew, blogPost, request, out newMasterIds, out oldMasterIds, out childrenPageIds, out existingChildrenMasterPages);

            // TODO: TEST AND TRY TO FIX IT: TRANSACTION HERE IS REQUIRED!
            // UnitOfWork.BeginTransaction(); // NOTE: this causes concurrent data exception.

            Redirect redirectCreated = null;
            if (!isNew && userCanEdit && !string.Equals(blogPost.PageUrl, request.BlogUrl) && !string.IsNullOrWhiteSpace(request.BlogUrl))
            {
                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);
            }

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

            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, null, blogPost.Category != null ? (Guid?)blogPost.Category.Id : null);
                }

                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 = SaveContentWithStatusUpdate(isNew, newContent, request, principal);
            pageContent.Content = content;
            optionService.SaveChildContentOptions(content, childContentOptionValues, request.DesirableStatus);

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

            MapExtraProperties(isNew, blogPost, content, pageContent, request, principal);

            // Notify about page properties changing.
            var cancelEventArgs = Events.BlogEvents.Instance.OnBlogChanging(beforeChange, new UpdatingBlogModel(blogPost));
            if (cancelEventArgs.Cancel)
            {
                errorMessages = cancelEventArgs.CancellationErrorMessages.ToArray();
                return null;
            }

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

            masterPageService.UpdateChildrenMasterPages(existingChildrenMasterPages, oldMasterIds, newMasterIds, childrenPageIds);

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

            

            IList<Tag> newTags = null;
            if (userCanEdit)
            {
                newTags = SaveTags(blogPost, request);
            }

            // Commit
            unitOfWork.Commit();

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

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

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

            return blogPost;
        }
예제 #8
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 };
            }
        }
예제 #9
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);
            }
        }
예제 #10
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);
                }
            }
        }
예제 #11
0
        protected override BlogPostContent SaveContentWithStatusUpdate(bool isNew, BlogPostContent newContent, BlogPostViewModel model, IPrincipal principal)
        {
            var modelExt = model as BlogPostViewModelExtender;
            if (isNew && modelExt != null && !modelExt.ContentId.HasDefaultValue())
            {
                if (model.DesirableStatus == ContentStatus.Published)
                {
                    newContent.PublishedOn = modelExt.PublishedOn ?? DateTime.Now;
                    newContent.PublishedByUser = principal.Identity.Name;
                    // TODO: pass published by user newContent.PublishedByUser = !string.IsNullOrEmpty(request.Data.PublishedByUser) ? request.Data.PublishedByUser : securityService.CurrentPrincipalName;
                }

                newContent.Status = model.DesirableStatus;
                newContent.Id = modelExt.ContentId;
                repository.Save(newContent);

                return newContent;
            }

            return base.SaveContentWithStatusUpdate(isNew, newContent, model, principal);
        }