public void WhenContentRequestedContentIdContentResponseHasContentTitle()
        {
            // Assign
            var content = new Models.Content { Title = "TestTitle" };
            this.Dao.GetContent(this.Request.ContentId).Returns(content);

            // Act
            var result = this.Sut.Get(this.Request);

            // Assert
            Assert.AreEqual(content.Title, result.Content.Title);
        }
        public void WhenContentRequestedContentIdContentResponseHasContentBody()
        {
            // Assign
            var content = new Models.Content { Body = "TestBody" };
            this.Dao.GetContent(this.Request.ContentId).Returns(content);

            // Act
            var result = this.Sut.Get(this.Request);

            // Assert
            Assert.AreEqual(content.Body, result.Content.Body);
        }
Esempio n. 3
0
        public ActionResult AddContent(FormCollection form)
        {
            using (var context = new ContentStorage())
            {
                Content content = new Models.Content();

                Int64 parentId = Convert.ToInt64(form["id"]);

                Content parentContent = context.Content.Where(c => c.Id == parentId).FirstOrDefault();

                content.Parent = parentContent;

                TryUpdateModel(content, new string[] { "Name", "PageTitle", "Title", "SeoKeywords", "SeoDescription", "SortOrder" });
                content.ContentType = 4;

                content.Text = HttpUtility.HtmlDecode(form["Text"]);
                content.SeoText = HttpUtility.HtmlDecode(form["SeoText"]);
                context.AddToContent(content);
                context.SaveChanges();

                return RedirectToAction("Index", "Home", new { area = "", id = content.Name });
            }
        }
        public void CopyChildContents(Models.Content destination, Models.Content source)
        {
            if (destination.ChildContents == null)
            {
                destination.ChildContents = new List <ChildContent>();
            }
            if (source.ChildContents == null)
            {
                source.ChildContents = new List <ChildContent>();
            }

            CopyChildContents(destination.ChildContents, source.ChildContents);
            foreach (var sourceChildContent in source.ChildContents)
            {
                var destinationChildContent = destination.ChildContents.First(d => sourceChildContent.AssignmentIdentifier == d.AssignmentIdentifier);
                destinationChildContent.Parent = destination;

                // Remove unneeded options
                if (source.ChildContentsLoaded)
                {
                    destinationChildContent.Options
                    .Where(s => sourceChildContent.Options.All(d => s.Key != d.Key))
                    .Distinct().ToList().ForEach(d => repository.Delete(d));
                }
            }

            // Remove childs, which not exists in source.
            var childsToDelete = destination.ChildContents
                                 .Where(s => source.ChildContents.All(d => s.AssignmentIdentifier != d.AssignmentIdentifier))
                                 .Distinct().ToList();

            childsToDelete.ForEach(d =>
            {
                destination.ChildContents.Remove(d);
                repository.Delete(d);
            });
        }
Esempio n. 5
0
        private void CollectDynamicRegions(string html, Models.Content content, IList <ContentRegion> contentRegions)
        {
            var regionIdentifiers = GetRegionIds(html);

            if (regionIdentifiers.Length > 0)
            {
                var regionIdentifiersLower = regionIdentifiers.Select(s => s.ToLowerInvariant()).ToArray();
                var existingRegions        = repository
                                             .AsQueryable <Region>()
                                             .Where(r => regionIdentifiersLower.Contains(r.RegionIdentifier.ToLowerInvariant()))
                                             .ToArray();

                foreach (var regionId in regionIdentifiers.Where(s => contentRegions.All(region => region.Region.RegionIdentifier != s)))
                {
                    var region = existingRegions.FirstOrDefault(r => r.RegionIdentifier.ToLowerInvariant() == regionId.ToLowerInvariant());

                    if (region == null)
                    {
                        region = contentRegions
                                 .Where(cr => cr.Region.RegionIdentifier.ToLowerInvariant() == regionId.ToLowerInvariant())
                                 .Select(cr => cr.Region).FirstOrDefault();

                        if (region == null)
                        {
                            region = new Region {
                                RegionIdentifier = regionId
                            };
                        }
                    }

                    var contentRegion = new ContentRegion {
                        Region = region, Content = content
                    };
                    contentRegions.Add(contentRegion);
                }
            }
        }
        public System.Tuple <PageContent, Models.Content> GetPageContentForEdit(Guid pageContentId)
        {
            PageContent pageContent = repository.AsQueryable <PageContent>()
                                      .Where(p => p.Id == pageContentId && !p.IsDeleted)
                                      .Fetch(p => p.Content).ThenFetchMany(p => p.History)
                                      .Fetch(p => p.Page)
                                      .Fetch(f => f.Region)
                                      .ToList()
                                      .FirstOrDefault();

            if (pageContent != null)
            {
                Models.Content content = pageContent.Content.FindEditableContentVersion();

                if (content == null)
                {
                    return(null);
                }

                return(new System.Tuple <PageContent, Models.Content>(pageContent, content));
            }

            return(null);
        }
        public Models.Content RestoreContentFromArchive(Models.Content restoreFrom)
        {
            if (restoreFrom == null)
            {
                throw new CmsException("Nothing to restore from.", new ArgumentNullException("restoreFrom"));
            }

            if (restoreFrom.Status != ContentStatus.Archived)
            {
                throw new CmsException("A page content can be restored only from the archived version.");
            }

            // Replace original version with restored entity data
            var originalContent = restoreFrom.Clone();

            originalContent.Id                  = restoreFrom.Original.Id;
            originalContent.Version             = restoreFrom.Original.Version;
            originalContent.Status              = ContentStatus.Published;
            originalContent.Original            = null;
            originalContent.ChildContentsLoaded = true;

            // Save entities
            return(SaveContentWithStatusUpdate(originalContent, ContentStatus.Published));
        }
        public Content.IContent GetContent(string contentPath)
        {
            GenericContent result = null;

            string[]       pathParts = contentPath.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            Models.Content root      = this.repository.GetContents().FirstOrDefault(con => con.Id == SqlIdProvider.Instance.CoreContent.MainCollection);
            foreach (var part in pathParts)
            {
                root = this.repository.GetContents()
                       .Join(this.repository.GetContentCollections()
                             .Where(col => col.ContentOwnerId == root.Id),
                             con => con.Id,
                             col => col.ContentId,
                             (con, col) => con)
                       .FirstOrDefault(con => con.Name == part);

                if (root == null)
                {
                    break;
                }
            }

            if (root != null)
            {
                Models.ContentPublication publication = this.repository.GetContentPublications().FirstOrDefault(pub => pub.ContentId == root.Id);

                IEnumerable <Models.ContentMedata> metadata = null;
                if (publication != null)
                {
                    metadata = this.repository.GetContentMetadatas().Where(met => met.ContentPublicationId == publication.Id);
                }

                result = new GenericContent(root, publication, metadata);
            }
            return(result);
        }
        private void SavePreviewOrDraftContentWithStatusUpdate(Models.Content originalContent, Models.Content updatedContent, ContentStatus requestedStatus)
        {
            /*
             * Edit preview or draft content:
             * -> Save as preview or draft - look for preview or draft version in a history list or create a new history version with requested preview status with reference to an original content.
             * -> Save draft - just update field and save.
             * -> Publish - look if the published content (look for original) exists:
             *              - published content exits:
             *                  | create a history content version of the published (clone it). update original with draft data and remove draft|preview.
             *              - published content not exists:
             *                  | save draft content as published
             */
            if (requestedStatus == ContentStatus.Preview || requestedStatus == ContentStatus.Draft)
            {
                var previewOrDraftContentVersion = originalContent.History.FirstOrDefault(f => f.Status == requestedStatus && !f.IsDeleted);
                if (previewOrDraftContentVersion == null)
                {
                    if (originalContent.Status == requestedStatus ||
                        (originalContent.Status == ContentStatus.Preview && requestedStatus == ContentStatus.Draft))
                    {
                        previewOrDraftContentVersion = originalContent;
                    }
                    else
                    {
                        previewOrDraftContentVersion          = originalContent.Clone();
                        previewOrDraftContentVersion.Original = originalContent;
                        originalContent.History.Add(previewOrDraftContentVersion);
                    }
                }

                updatedContent.CopyDataTo(previewOrDraftContentVersion, false);
                SetContentOptions(previewOrDraftContentVersion, updatedContent);
                SetContentRegions(previewOrDraftContentVersion, updatedContent);
                childContentService.CopyChildContents(previewOrDraftContentVersion, updatedContent);

                previewOrDraftContentVersion.Status = requestedStatus;

                repository.Save(previewOrDraftContentVersion);
            }
            else if (requestedStatus == ContentStatus.Published)
            {
                var publishedVersion = originalContent.History.FirstOrDefault(f => f.Status == requestedStatus && !f.IsDeleted);
                if (publishedVersion != null)
                {
                    var originalToArchive = originalContent.Clone();
                    originalToArchive.Status   = ContentStatus.Archived;
                    originalToArchive.Original = originalContent;
                    originalContent.History.Add(originalToArchive);
                    repository.Save(originalToArchive);
                }

                updatedContent.CopyDataTo(originalContent, false);
                SetContentOptions(originalContent, updatedContent);
                SetContentRegions(originalContent, updatedContent);
                childContentService.CopyChildContents(originalContent, updatedContent);

                originalContent.Status = requestedStatus;
                if (!originalContent.PublishedOn.HasValue)
                {
                    originalContent.PublishedOn = DateTime.Now;
                }
                if (string.IsNullOrWhiteSpace(originalContent.PublishedByUser))
                {
                    originalContent.PublishedByUser = securityService.CurrentPrincipalName;
                }

                repository.Save(originalContent);
            }
        }
        private void SavePublishedContentWithStatusUpdate(Models.Content originalContent, Models.Content updatedContent, ContentStatus requestedStatus)
        {
            /*
             * Edit published content:
             * -> Save as draft, preview - look for draft|preview version in history list or create a new history version with requested status (draft, preview) with reference to an original content.
             * -> Publish - current published version should be cloned to archive version with reference to original (archive state) and original updated with new data (published state).
             *              Look for preview|draft versions - if exists remote it.
             */
            if (requestedStatus == ContentStatus.Preview || requestedStatus == ContentStatus.Draft)
            {
                var contentVersionOfRequestedStatus = originalContent.History.FirstOrDefault(f => f.Status == requestedStatus && !f.IsDeleted);
                if (contentVersionOfRequestedStatus == null)
                {
                    contentVersionOfRequestedStatus = originalContent.Clone();
                }

                updatedContent.CopyDataTo(contentVersionOfRequestedStatus, false);
                SetContentOptions(contentVersionOfRequestedStatus, updatedContent);
                SetContentRegions(contentVersionOfRequestedStatus, updatedContent);
                childContentService.CopyChildContents(contentVersionOfRequestedStatus, updatedContent);

                contentVersionOfRequestedStatus.Original = originalContent;
                contentVersionOfRequestedStatus.Status   = requestedStatus;
                originalContent.History.Add(contentVersionOfRequestedStatus);

                repository.Save(contentVersionOfRequestedStatus);
            }

            if (requestedStatus == ContentStatus.Published)
            {
                // Original is copied with options and saved.
                // Removes options from original.
                // Locks new stuff from view model.
                var originalToArchive = originalContent.Clone();
                originalToArchive.Status   = ContentStatus.Archived;
                originalToArchive.Original = originalContent;
                originalContent.History.Add(originalToArchive);
                repository.Save(originalToArchive);

                // Load draft content's child contents options, if saving from draft to public
                var draftVersion = originalContent.History.FirstOrDefault(f => f.Status == ContentStatus.Draft && !f.IsDeleted);
                if (draftVersion != null)
                {
                    updatedContent
                    .ChildContents
                    .ForEach(cc => cc.Options = draftVersion
                                                .ChildContents
                                                .Where(cc1 => cc1.AssignmentIdentifier == cc.AssignmentIdentifier)
                                                .SelectMany(cc1 => cc1.Options)
                                                .ToList());
                }

                updatedContent.CopyDataTo(originalContent, false);
                SetContentOptions(originalContent, updatedContent);
                SetContentRegions(originalContent, updatedContent);
                childContentService.CopyChildContents(originalContent, updatedContent);

                originalContent.Status = requestedStatus;
                if (!originalContent.PublishedOn.HasValue)
                {
                    originalContent.PublishedOn = DateTime.Now;
                }
                if (string.IsNullOrWhiteSpace(originalContent.PublishedByUser))
                {
                    originalContent.PublishedByUser = securityService.CurrentPrincipalName;
                }
                repository.Save(originalContent);

                IList <Models.Content> contentsToRemove = originalContent.History.Where(f => f.Status == ContentStatus.Preview || f.Status == ContentStatus.Draft).ToList();
                foreach (var redundantContent in contentsToRemove)
                {
                    repository.Delete(redundantContent);
                    originalContent.History.Remove(redundantContent);
                }
            }
        }
        public void ValidateChildContentsCircularReferences(Models.Content destination, Models.Content source)
        {
            var destinationChildren = new List <ChildContent>();

            if (destination.ChildContents != null)
            {
                destinationChildren.AddRange(destination.ChildContents);
            }

            var sourceChildren = new List <ChildContent>();

            if (source.ChildContents != null)
            {
                sourceChildren.AddRange(source.ChildContents);
            }
            CopyChildContents(destinationChildren, sourceChildren);

            // Remove childs, which not exists in source.
            destinationChildren
            .Where(s => sourceChildren.All(d => s.AssignmentIdentifier != d.AssignmentIdentifier))
            .ToList()
            .ForEach(d => destinationChildren.Remove(d));

            if (destinationChildren.Any())
            {
                // Cannot add itself as child
                if (destinationChildren.Any(dc => dc.Child.Id == destination.Id))
                {
                    var message = string.Format(RootGlobalization.ChildContent_CirculatReferenceDetected, destination.Name);
                    throw new ValidationException(() => message, message);
                }

                var references  = new List <Guid>();
                var childrenIds = PopulateReferencesList(
                    references,
                    destinationChildren.Select(s => new System.Tuple <Guid, Guid, string>(destination.Id, s.Child.Id, s.Child.Name)));

                ValidateChildContentsCircularReferences(childrenIds, references);
            }
        }
        public PageContentProjection CreatePageContentProjection(
            bool canManageContent,
            PageContent pageContent,
            List <PageContent> allPageContents,
            IChildContent childContent  = null,
            Guid?previewPageContentId   = null,
            Guid?languageId             = null,
            bool retrieveCorrectVersion = true)
        {
            // Run logic of projection creation, because it's not created yet
            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 regions (dynamic regions) contents projections
            var childRegionContentProjections = CreateListOfChildRegionContentProjectionsRecursively(canManageContent, previewPageContentId, pageContent, allPageContents, contentToProject, languageId);

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

            Func <IPageContent, IContent, IContentAccessor, IEnumerable <ChildContentProjection>, IEnumerable <PageContentProjection>, PageContentProjection> createProjectionDelegate;

            if (childContent != null)
            {
                createProjectionDelegate = (pc, c, a, ccpl, pcpl) =>
                {
                    if (childContent.ChildContent is IProxy)
                    {
                        childContent.ChildContent = (IContent)unitOfWork.Session.GetSessionImplementation().PersistenceContext.Unproxy(childContent.ChildContent);
                    }
                    return(new ChildContentProjection(pc, childContent, a, ccpl, pcpl));
                };
            }
            else
            {
                createProjectionDelegate = (pc, c, a, ccpl, pcpl) => new PageContentProjection(pc, c, a, ccpl, pcpl);
            }

            var optionValues      = childContent != null ? childContent.Options : pageContent.Options;
            var options           = optionService.GetMergedOptionValues(contentToProject.ContentOptions, optionValues, languageId);
            var contentProjection = pageContentProjectionFactory.Create(pageContent, contentToProject, options, childContentsProjections, childRegionContentProjections, createProjectionDelegate);

            return(contentProjection);
        }
Esempio n. 13
0
        private void GetRelated()
        {
            // Clear related
            Regions.Clear();
            Properties.Clear();
            AttachedContent.Clear();

            // Get group parents
            DisableGroups = SysGroup.GetParents(Page.GroupId);
            DisableGroups.Reverse();

            // Get template & permalink
            Template  = PageTemplate.GetSingle("pagetemplate_id = @0", Page.TemplateId);
            Permalink = Permalink.GetSingle(Page.PermalinkId);
            if (Permalink == null)
            {
                // Get the site tree
                using (var db = new DataContext()) {
                    var sitetree = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single();

                    Permalink = new Permalink()
                    {
                        Id = Guid.NewGuid(), Type = Permalink.PermalinkType.PAGE, NamespaceId = sitetree.NamespaceId
                    };
                    Page.PermalinkId = Permalink.Id;
                }
            }

            // Get placement ref title
            if (!IsSite)
            {
                if (Page.ParentId != Guid.Empty || Page.Seqno > 1)
                {
                    Page refpage = null;
                    if (Page.Seqno > 1)
                    {
                        if (Page.ParentId != Guid.Empty)
                        {
                            refpage = Page.GetSingle("page_parent_id = @0 AND page_seqno = @1", Page.ParentId, Page.Seqno - 1);
                        }
                        else
                        {
                            refpage = Page.GetSingle("page_parent_id IS NULL AND page_seqno = @0", Page.Seqno - 1);
                        }
                    }
                    else
                    {
                        refpage = Page.GetSingle(Page.ParentId, true);
                    }
                    PlaceRef = refpage.Title;
                }
            }

            if (Template != null)
            {
                // Only load regions & properties if this is an original
                if (Page.OriginalId == Guid.Empty)
                {
                    // Get regions
                    var regions = RegionTemplate.Get("regiontemplate_template_id = @0", Template.Id, new Params()
                    {
                        OrderBy = "regiontemplate_seqno"
                    });
                    foreach (var rt in regions)
                    {
                        var reg = Region.GetSingle("region_regiontemplate_id = @0 AND region_page_id = @1 and region_draft = @2",
                                                   rt.Id, Page.Id, Page.IsDraft);
                        if (reg != null)
                        {
                            Regions.Add(reg);
                        }
                        else
                        {
                            Regions.Add(new Region()
                            {
                                InternalId       = rt.InternalId,
                                Name             = rt.Name,
                                Type             = rt.Type,
                                PageId           = Page.Id,
                                RegiontemplateId = rt.Id,
                                IsDraft          = Page.IsDraft,
                                IsPageDraft      = Page.IsDraft
                            });
                        }
                    }

                    // Get Properties
                    foreach (string name in Template.Properties)
                    {
                        Property prp = Property.GetSingle("property_name = @0 AND property_parent_id = @1 AND property_draft = @2",
                                                          name, Page.Id, Page.IsDraft);
                        if (prp != null)
                        {
                            Properties.Add(prp);
                        }
                        else
                        {
                            Properties.Add(new Property()
                            {
                                Name = name, ParentId = Page.Id, IsDraft = Page.IsDraft
                            });
                        }
                    }
                }
            }
            else
            {
                throw new ArgumentException("Could not find page template for page {" + Page.Id.ToString() + "}");
            }

            // Only load attachments if this is an original
            if (Page.OriginalId == Guid.Empty)
            {
                // Get attached content
                if (Page.Attachments.Count > 0)
                {
                    // Content meta data is actually memcached, so this won't result in multiple queries
                    Page.Attachments.ForEach(a => {
                        Models.Content c = Models.Content.GetSingle(a, true);
                        if (c != null)
                        {
                            AttachedContent.Add(c);
                        }
                    });
                }
            }

            // Get page position
            Parents = BuildParentPages(Sitemap.GetStructure(Page.SiteTreeInternalId, false), Page);
            Parents.Insert(0, new PagePlacement()
            {
                Level = 1, IsSelected = Page.ParentId == Guid.Empty
            });
            Siblings = BuildSiblingPages(Page.Id, Page.ParentId, Page.Seqno, Page.ParentId, Page.SiteTreeInternalId);

            // Only load extensions if this is an original
            if (Page.OriginalId == Guid.Empty)
            {
                // Get extensions
                Extensions = Page.GetExtensions(true);
            }

            // Initialize regions
            foreach (var reg in Regions)
            {
                reg.Body.InitManager(this);
            }

            // Get whether comments should be enabled
            EnableComments = Areas.Manager.Models.CommentSettingsModel.Get().EnablePages;
            if (!Page.IsNew && EnableComments)
            {
                using (var db = new DataContext()) {
                    Comments = db.Comments.
                               Where(c => c.ParentId == Page.Id && c.ParentIsDraft == false).
                               OrderByDescending(c => c.Created).ToList();
                }
            }

            // Get the site if this is a site page
            if (Permalink.Type == Models.Permalink.PermalinkType.SITE)
            {
                using (var db = new DataContext()) {
                    SiteTree = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single();
                }
            }

            // Check if the page can be published
            if (Page.OriginalId != Guid.Empty)
            {
                CanPublish = Page.GetScalar("SELECT count(*) FROM page WHERE page_id=@0 AND page_draft=0", Page.OriginalId) > 0;
            }
        }
Esempio n. 14
0
        private void SavePublishedContentWithStatusUpdate(Models.Content originalContent, Models.Content updatedContent, ContentStatus requestedStatus)
        {
            /*
             * Edit published content:
             * -> Save as draft, preview - look for draft|preview version in history list or create a new history version with requested status (draft, preview) with reference to an original content.
             * -> Publish - current published version should be cloned to archive version with reference to original (archive state) and original updated with new data (published state).
             *              Look for preview|draft versions - if exists remote it.
             */
            if (requestedStatus == ContentStatus.Preview || requestedStatus == ContentStatus.Draft)
            {
                var contentVersionOfRequestedStatus = originalContent.History.FirstOrDefault(f => f.Status == requestedStatus && !f.IsDeleted);
                if (contentVersionOfRequestedStatus == null)
                {
                    contentVersionOfRequestedStatus = originalContent.Clone();
                }

                RemoveContentOptionsIfExists(contentVersionOfRequestedStatus);

                updatedContent.CopyDataTo(contentVersionOfRequestedStatus);
                contentVersionOfRequestedStatus.Original = originalContent;
                contentVersionOfRequestedStatus.Status   = requestedStatus;
                originalContent.History.Add(contentVersionOfRequestedStatus);
                repository.Save(contentVersionOfRequestedStatus);
            }

            if (requestedStatus == ContentStatus.Published)
            {
                var originalToArchive = originalContent.Clone();
                originalToArchive.Status   = ContentStatus.Archived;
                originalToArchive.Original = originalContent;
                originalContent.History.Add(originalToArchive);
                repository.Save(originalToArchive);

                RemoveContentOptionsIfExists(originalContent);
                updatedContent.CopyDataTo(originalContent);
                originalContent.Status          = requestedStatus;
                originalContent.PublishedOn     = DateTime.Now;
                originalContent.PublishedByUser = securityService.CurrentPrincipalName;
                repository.Save(originalContent);

                IList <Models.Content> contentsToRemove = originalContent.History.Where(f => f.Status == ContentStatus.Preview || f.Status == ContentStatus.Draft).ToList();
                foreach (var redundantContent in contentsToRemove)
                {
                    repository.Delete(redundantContent);
                    originalContent.History.Remove(redundantContent);
                }
            }
        }
Esempio n. 15
0
 public Task <bool> PostContentAsync(Models.Content content)
 {
     return(Task.FromResult(false));
 }
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                HttpPostedFileBase picture = (HttpPostedFileBase)Request.Files["Picture"];
                // TODO: Add insert logic here
                Models.Content content = new Models.Content(){
                    Title = collection["Title"],
                    Content1 = collection["Content"],
                    Status = EntityStatuses.Actived.ToString(),
                    CreatedDate = DateTime.Now,
                    UpdatedDate = DateTime.Now,
                    UniqueKey = collection["Title"].ToUrlKey(),
                    CategoryId = int.Parse(collection["CategoryId"]),
                    IsFeatured = collection["IsFeatured"].Contains("true"),
                    Description = collection["Description"],
                };

                
                ContentService.Create(content, picture);

                return RedirectToAction("Index");
            }
            catch
            {
                throw;
                return View();
            }
        }
Esempio n. 17
0
        private void GetRelated()
        {
            // Clear related
            Properties.Clear();

            if (Template != null)
            {
                // Get Properties
                foreach (string name in Template.Properties)
                {
                    Property prp = Property.GetSingle("property_name = @0 AND property_parent_id = @1 AND property_draft = @2",
                                                      name, Post.Id, Post.IsDraft);
                    if (prp != null)
                    {
                        Properties.Add(prp);
                    }
                    else
                    {
                        Properties.Add(new Property()
                        {
                            Name = name, ParentId = Post.Id, IsDraft = Post.IsDraft
                        });
                    }
                }
            }

            // Get selected categories
            if (PostCategories.Count > 0)
            {
                Categories = new MultiSelectList(Category.GetFields("category_id, category_name",
                                                                    new Params()
                {
                    OrderBy = "category_name"
                }), "Id", "Name", PostCategories);
            }

            // Get attached content
            if (Post.Attachments.Count > 0)
            {
                // Content meta data is actually memcached, so this won't result in multiple queries
                Post.Attachments.ForEach(a => {
                    Models.Content c = Models.Content.GetSingle(a, true);
                    if (c != null)
                    {
                        AttachedContent.Add(c);
                    }
                });
            }

            // Get extensions
            Extensions = Post.GetExtensions(true);

            // Get whether comments should be enabled
            EnableComments = Areas.Manager.Models.CommentSettingsModel.Get().EnablePosts;
            if (!Post.IsNew && EnableComments)
            {
                using (var db = new DataContext()) {
                    Comments = db.Comments.
                               Include("CreatedBy").
                               Where(c => c.ParentId == Post.Id && c.ParentIsDraft == false).
                               OrderByDescending(c => c.Created).ToList();
                }
            }
        }
Esempio n. 18
0
        private void GetRelated()
        {
            // Clear related
            Regions.Clear();
            Properties.Clear();
            AttachedContent.Clear();

            // Get group parents
            DisableGroups = SysGroup.GetParents(Page.GroupId);
            DisableGroups.Reverse();

            // Get placement ref title
            if (Page.ParentId != Guid.Empty || Page.Seqno > 1)
            {
                Page refpage = null;
                if (Page.Seqno > 1)
                {
                    if (Page.ParentId != Guid.Empty)
                    {
                        refpage = Page.GetSingle("page_parent_id = @0 AND page_seqno = @1", Page.ParentId, Page.Seqno - 1);
                    }
                    else
                    {
                        refpage = Page.GetSingle("page_parent_id IS NULL AND page_seqno = @0", Page.Seqno - 1);
                    }
                }
                else
                {
                    refpage = Page.GetSingle(Page.ParentId, true);
                }
                PlaceRef = refpage.Title;
            }

            // Get template & permalink
            Template  = PageTemplate.GetSingle("pagetemplate_id = @0", Page.TemplateId);
            Permalink = Permalink.GetSingle(Page.PermalinkId);
            if (Permalink == null)
            {
                Permalink = new Permalink()
                {
                    Id = Guid.NewGuid(), Type = Permalink.PermalinkType.PAGE, NamespaceId = new Guid("8FF4A4B4-9B6C-4176-AAA2-DB031D75AC03")
                };
                Page.PermalinkId = Permalink.Id;
            }

            if (Template != null)
            {
                // Get regions
                var regions = RegionTemplate.Get("regiontemplate_template_id = @0", Template.Id, new Params()
                {
                    OrderBy = "regiontemplate_seqno"
                });
                foreach (var rt in regions)
                {
                    var reg = Region.GetSingle("region_regiontemplate_id = @0 AND region_page_id = @1 and region_draft = @2",
                                               rt.Id, Page.Id, Page.IsDraft);
                    if (reg != null)
                    {
                        Regions.Add(reg);
                    }
                    else
                    {
                        Regions.Add(new Region()
                        {
                            InternalId       = rt.InternalId,
                            Name             = rt.Name,
                            Type             = rt.Type,
                            PageId           = Page.Id,
                            RegiontemplateId = rt.Id,
                            IsDraft          = Page.IsDraft,
                            IsPageDraft      = Page.IsDraft
                        });
                    }
                }

                // Get Properties
                foreach (string name in Template.Properties)
                {
                    Property prp = Property.GetSingle("property_name = @0 AND property_parent_id = @1 AND property_draft = @2",
                                                      name, Page.Id, Page.IsDraft);
                    if (prp != null)
                    {
                        Properties.Add(prp);
                    }
                    else
                    {
                        Properties.Add(new Property()
                        {
                            Name = name, ParentId = Page.Id, IsDraft = Page.IsDraft
                        });
                    }
                }
            }
            else
            {
                throw new ArgumentException("Could not find page template for page {" + Page.Id.ToString() + "}");
            }

            // Get attached content
            if (Page.Attachments.Count > 0)
            {
                // Content meta data is actually memcached, so this won't result in multiple queries
                Page.Attachments.ForEach(a => {
                    Models.Content c = Models.Content.GetSingle(a);
                    if (c != null)
                    {
                        AttachedContent.Add(c);
                    }
                });
            }

            // Get page position
            Parents = BuildParentPages(Sitemap.GetStructure(false), Page);
            Parents.Insert(0, new PagePlacement()
            {
                Level = 1, IsSelected = Page.ParentId == Guid.Empty
            });
            Siblings = BuildSiblingPages(Page.Id, Page.ParentId, Page.Seqno, Page.ParentId);
        }
 public IActionResult Index()
 {
     Models.Content content = new Models.Content("Lorem ipsum dolor sit amet, nec stet rebum offendit ne, ius te nullam postulant. Mel meliore deserunt ne, mei id nullam impetus, porro iracundia temporibus pro in. Sed an eruditi recusabo euripidis, ad nusquam percipitur eam.");
     return(View("index", content));
 }
Esempio n. 20
0
        public async Task <ApiResult <long> > Submit(Model.Post.Submit.Input input)
        {
            var userId = _current.UserId;

            var output = new ApiResult <long>();

            if (string.IsNullOrEmpty(input.Name))
            {
                output.Msgs.Add(new MsgResult("name", "common.name_empty"));
            }

            if (input.CategoryId.HasValue == false)
            {
                output.Msgs.Add(new MsgResult("category", "common.category_empty"));
            }

            if (output.Msgs.Any() == false)
            {
                try
                {
                    if (input.Id.HasValue)
                    {
                        var item = await _repository.GetQuery(input.Id.Value).FirstOrDefaultAsync();

                        if (item != null)
                        {
                            _unitOfWork._dbContext.ContentByCategory.RemoveRange(_unitOfWork._dbContext.ContentByCategory.Where(m => m.ItemId == item.Id));
                            await _unitOfWork._dbContext.ContentByCategory.AddAsync(new Models.ContentByCategory {
                                CategoryId = input.CategoryId.Value, ItemId = item.Id
                            });

                            _unitOfWork.Edit(item, nameof(item.Name), input.Name);
                            _unitOfWork.Edit(item, nameof(item.Summary), input.Summary);
                            _unitOfWork.Edit(item, nameof(item.IsHidden), input.IsHidden);
                            _unitOfWork.Edit(item, nameof(item.DateCreated), input.DateCreated);
                            _unitOfWork.Edit(item, nameof(item.Description), input.Description);
                            _unitOfWork.Edit(item, nameof(item.Link), input.Link);
                            await _unitOfWork.SaveChanges();

                            output.Code = Const.ApiCodeEnum.Success;
                            output.Data = item.Id;
                        }
                        else
                        {
                            output.Msgs.Add(new MsgResult("general", "common.not_exists"));
                        }
                    }
                    else
                    {
                        var item = new Models.Content
                        {
                            UserId            = userId,
                            Name              = input.Name,
                            Summary           = input.Summary,
                            IsHidden          = input.IsHidden,
                            Description       = input.Description,
                            Link              = input.Link,
                            DateCreated       = input.DateCreated ?? _current.Now,
                            ContentByCategory = new List <Models.ContentByCategory> {
                                new Models.ContentByCategory {
                                    CategoryId = input.CategoryId.Value
                                }
                            },
                        };
                        await _unitOfWork._dbContext.Content.AddAsync(item);

                        await _unitOfWork.SaveChanges();

                        input.Id = item.Id;

                        output.Code = Const.ApiCodeEnum.Success;
                        output.Data = item.Id;
                    }

                    if (output.Code == Const.ApiCodeEnum.Success)
                    {
                        await _fileManage.Update(new File.Model.Manage.UpdateModel.Input
                        {
                            CategoryId = (long)Const.FileCategory.Content,
                            ItemId     = input.Id.ToString(),
                            IsTemp     = false,
                            FileList   = input.FileList.Select((m, index) => new File.Model.Manage.UploadModel.File {
                                Id = m.Id, IsVR = m.IsVR, OrderNumber = index
                            }).ToList(),
                        });
                    }

                    await _fileManage.Update(new File.Model.Manage.UpdateModel.Input
                    {
                        CategoryId = (long)Const.FileCategory.Content,
                        ItemId     = input.Id.ToString(),
                        IsTemp     = false,
                        ItemField  = "description",
                        FileList   = input.DescriptionFileList.Select((m, index) => new File.Model.Manage.UploadModel.File {
                            Id = m.Id, OrderNumber = index
                        }).ToList(),
                    });
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, ex.Message);
                }
            }

            return(output);
        }
        public Models.Content SaveContentWithStatusUpdate(Models.Content updatedContent, ContentStatus requestedStatus)
        {
            if (updatedContent == null)
            {
                throw new CmsException("Nothing to save.", new ArgumentNullException("updatedContent"));
            }

            if (requestedStatus == ContentStatus.Archived)
            {
                throw new CmsException(string.Format("Can't switch a content to the Archived state directly."));
            }

            // Fill content with dynamic contents info
            UpdateDynamicContainer(updatedContent);

            if (updatedContent.Id == default(Guid))
            {
                /* Just create a new content with requested status.*/
                if (requestedStatus == ContentStatus.Published)
                {
                    if (!updatedContent.PublishedOn.HasValue)
                    {
                        updatedContent.PublishedOn = DateTime.Now;
                    }
                    if (string.IsNullOrWhiteSpace(updatedContent.PublishedByUser))
                    {
                        updatedContent.PublishedByUser = securityService.CurrentPrincipalName;
                    }
                }

                updatedContent.Status = requestedStatus;
                repository.Save(updatedContent);

                return(updatedContent);
            }

            var originalContent =
                repository.AsQueryable <Models.Content>()
                .Where(f => f.Id == updatedContent.Id && !f.IsDeleted)
                .Fetch(f => f.Original).ThenFetchMany(f => f.History)
                .Fetch(f => f.Original).ThenFetchMany(f => f.ContentOptions)
                .FetchMany(f => f.History)
                .FetchMany(f => f.ContentOptions)
                .FetchMany(f => f.ChildContents)
                .FetchMany(f => f.ContentRegions)
                .ThenFetch(f => f.Region)
                .ToList()
                .FirstOrDefault();

            if (originalContent == null)
            {
                throw new EntityNotFoundException(typeof(Models.Content), updatedContent.Id);
            }

            if (originalContent.Original != null)
            {
                originalContent = originalContent.Original;
            }

            originalContent = repository.UnProxy(originalContent);

            if (originalContent.History != null)
            {
                originalContent.History = originalContent.History.Distinct().ToList();
            }
            else
            {
                originalContent.History = new List <Models.Content>();
            }

            if (originalContent.ContentOptions != null)
            {
                originalContent.ContentOptions = originalContent.ContentOptions.Distinct().ToList();
            }

            if (originalContent.ContentRegions != null)
            {
                originalContent.ContentRegions = originalContent.ContentRegions.Distinct().ToList();
            }

            if (originalContent.ChildContents != null)
            {
                originalContent.ChildContents = originalContent.ChildContents.Distinct().ToList();
            }

            childContentService.ValidateChildContentsCircularReferences(originalContent, updatedContent);

            /* Update existing content. */
            switch (originalContent.Status)
            {
            case ContentStatus.Published:
                SavePublishedContentWithStatusUpdate(originalContent, updatedContent, requestedStatus);
                break;

            case ContentStatus.Preview:
            case ContentStatus.Draft:
                SavePreviewOrDraftContentWithStatusUpdate(originalContent, updatedContent, requestedStatus);
                break;

            case ContentStatus.Archived:
                throw new CmsException(string.Format("Can't edit a content in the {0} state.", originalContent.Status));

            default:
                throw new CmsException(string.Format("Unknown content status {0}.", updatedContent.Status), new NotSupportedException());
            }

            return(originalContent);
        }
 public Models.Content CreateContent()
 {
     var result = new Models.Content();
     this.context.Entry(result).State = System.Data.Entity.EntityState.Added;
     return result;
 }