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 static void FromPageContent(PageContent pageContent, PageContentEntity entity) { entity.EditedOn = pageContent.EditedOn; entity.EditedBy = pageContent.EditedBy; entity.Text = pageContent.Text; entity.VersionNumber = pageContent.VersionNumber; }
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 OnPageContentConfigured(PageContent pageContent) { if (PageContentConfigured != null) { PageContentConfigured(new SingleItemEventArgs<PageContent>(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); }
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"); }
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; }
/// <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); } }
/// <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); } }
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); } }
public void SetAvailableShortName(PageContent content) { content.ShortName = _dataAccess.GetAvailableShortName(content.ShortName); }
public void Add(PageContent content) { content.ValidateFields(); SetAvailableShortName(content); _dataAccess.Add(content); }
public void should_export_pages_with_content() { // Arrange var settingsRepository = new SettingsRepositoryMock(); var pageRepository = new PageRepositoryMock(); settingsRepository.SiteSettings.PluginLastSaveDate = DateTime.Today; DateTime page1CreatedOn = new DateTime(2013, 01, 01, 12, 00, 00); DateTime page1ModifiedOn = new DateTime(2013, 01, 01, 13, 00, 00); DateTime page2CreatedOn = new DateTime(2013, 01, 02, 12, 00, 00); DateTime page2ModifiedOn = new DateTime(2013, 01, 02, 13, 00, 00); DateTime page3CreatedOn = new DateTime(2013, 01, 03, 12, 00, 00); DateTime page3ModifiedOn = new DateTime(2013, 01, 03, 13, 00, 00); Guid page1ContentId = new Guid("13a8ad19-b203-46f5-be10-11e0ebf6f812"); Guid page2ContentId = new Guid("143b0023-329a-49b9-97a4-5094a0e378a2"); Guid page3ContentId = new Guid("15ee19ef-c093-47de-97d2-83dec406d92d"); string page1Text = @"the text ;''' "" more text """ ; string page2Text = @"the text ;''' #### sdfsdfsdf #### "" blah text """ ; string page3Text = @"the text ;''' #### dddd **dddd** #### "" pppp text """ ; Page page1 = new Page() { CreatedBy = "created-by-user1", CreatedOn = page1CreatedOn, Id = 1, IsLocked = true, ModifiedBy = "modified-by-user2", ModifiedOn = page1ModifiedOn, Tags = "tag1,tag2,tag3", Title = "Page 1 title" }; Page page2 = new Page() { CreatedBy = "created-by-user2", CreatedOn = page2CreatedOn, Id = 2, IsLocked = true, ModifiedBy = "modified-by-user2", ModifiedOn = page2ModifiedOn, Tags = "tagA,tagB,tagC", Title = "Page 2 title" }; Page page3 = new Page() { CreatedBy = "created-by-user3", CreatedOn = page3CreatedOn, Id = 3, IsLocked = false, ModifiedBy = "modified-by-user3", ModifiedOn = page3ModifiedOn, Tags = "tagX,tagY,tagZ", Title = "Page 3 title" }; PageContent pageContent1 = pageRepository.AddNewPage(page1, page1Text, "modified-by-user1", page1ModifiedOn); pageContent1.Id = page1ContentId; PageContent pageContent2 = pageRepository.AddNewPage(page2, page2Text, "modified-by-user2", page2ModifiedOn); pageContent2.Id = page2ContentId; PageContent pageContent3 = pageRepository.AddNewPage(page3, page3Text, "modified-by-user3", page3ModifiedOn); pageContent3.Id = page3ContentId; SqlExportBuilder builder = new SqlExportBuilder(settingsRepository, new UserRepositoryMock(), pageRepository, new PluginFactoryMock()); builder.IncludeConfiguration = false; builder.IncludePages = true; string expectedSql = ReadEmbeddedResource("expected-pages-export.sql"); // Act string actualSql = builder.Export(); // Assert Assert.That(actualSql, Is.EqualTo(expectedSql), actualSql); }
/// <summary> /// 游标分页 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="sql">sql语句</param> /// <param name="objPage">分页实体</param> /// <param name="oper">数据库链接</param> /// <returns></returns> public IDataReader Query(string sql, PageContent objPage, DataBaseOperate oper) { return(CursorPageCutter.Query(sql, objPage, oper)); }
/// <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); } }
/// <summary> /// 添加所要打印的文件(标题、打印目标) /// </summary> /// <param name="strTitle">标题</param> /// <param name="element">打印目标</param> public void Items_Add(string strTitle, FrameworkElement element) { //当前打印页的页码 printPage++; try { #region 打印承载体初始化 PageContent pageContent = new PageContent(); //为页面提供内容 FixedPage fixedPage = new FixedPage(); fixedPage.Width = this._size.Width; fixedPage.Height = this._size.Height; //_FixedPageList.Add(fixedPage); //修饰容器 Viewbox box = new Viewbox(); //修饰容器集合,统一更改视图 listViewBox.Add(box); //将打印页加载 doc.Pages.Add(pageContent); ((IAddChild)pageContent).AddChild(fixedPage); #endregion #region 更换父容器(更换对子元素的连接) if (element.Parent != null) { //需要打印的元素的父元素 DependencyObject parent = element.Parent as DependencyObject; #region 设置打印状态 //设置边距 element.Margin = new Thickness(7, 20, 10, 7); //打印状态不可编辑 element.IsEnabled = false; #endregion //提示控件 LoadingPage loading1 = new LoadingPage(); loading1.waitingText.Text = "执行中。。。。。。请稍等"; box.Child = null; #region 打开窗体,元素替换操作 //如果父元素是border,直接替换 if (parent is Border) { (parent as Border).Child = loading1; } //如果父元素是grid,先移出要打印的元素,替换为等待提示 else if (parent is Grid) { (parent as Grid).Children.Remove(element); (parent as Grid).Children.Add(loading1); } //如果为其它父元素,大可以使用下列方式 else { parent.SetValue(ContentPresenter.ContentProperty, loading1); } #endregion #region 打印目标 //打印表格(c3,高铁,普通) if (element.Tag != null && element.Tag.ToString().Contains("GZLB")) { Border border = new Border(); border.Child = element; box.Child = border; } //打印index折线图 else if (isShuPutDown) { element.RenderTransformOrigin = new Point(0.5, 0.5); TransformGroup transformGroup = new TransformGroup(); transformGroup.Children.Add(new RotateTransform(90)); transformGroup.Children.Add(new ScaleTransform(1, 0.7)); element.RenderTransform = transformGroup; element.Margin = new Thickness(-250, 350, 0, 0); box.Child = element; } //打印其他(index故障列表,datagrid) else { #region 属性设置 element.Margin = new Thickness(7, 20, 10, 7); element.IsEnabled = false; #endregion PrintItem item = new PrintItem(strTitle, element); item.Width = this._size.Width; item.txtPageFoot.Text = printPage.ToString(); box.Child = item; } #endregion //打印窗体关闭时还原 this.Closed += (object sender2, EventArgs e2) => { loading1.waitingText.Text = "正在关闭打印窗体"; if (isShuPutDown) { return; } #region 内存回收 GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); #endregion #region 还原状态设置 element.Margin = new Thickness(0); element.IsEnabled = true; #endregion (element.Parent as Border).Child = null; #region 窗体关闭,还原为初始状态 if (parent is Border) { (parent as Border).Child = element; } else if (parent is Grid) { try { (parent as Grid).Children.Remove(loading1); (parent as Grid).Children.Add(element); } catch (Exception) { throw; } } else if (parent is ScrollViewer) { try { (parent as ScrollViewer).Content = element; } catch (Exception) { throw; } } else { parent.SetValue(ContentPresenter.ContentProperty, element); } #endregion }; } #endregion fixedPage.Children.Add(box); this.txtAllCount.Text = view.PageCount.ToString(); } catch (Exception ex) { MethodLb.CreateLog(this.GetType().FullName, "Items_Add", ex.ToString(), strTitle, element); } finally { } }
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); } }
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 (modelExt.UpdateLanguage) { entity.Language = modelExt.LanguageId.HasValue ? repository.AsProxy <Language>(modelExt.LanguageId.Value) : null; entity.LanguageGroupIdentifier = modelExt.LanguageGroupIdentifier; } // 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); } } }
/// <summary> /// Gets the filtered blog posts query. /// </summary> /// <param name="request">The filter.</param> /// <param name="joinContents">if set to <c>true</c> join contents tables.</param> /// <returns> /// NHibernate query for getting filtered blog posts /// </returns> public NHibernate.IQueryOver <BlogPost, BlogPost> GetFilteredBlogPostsQuery(ViewModels.Filter.BlogsFilter request, bool joinContents = false) { request.SetDefaultSortingOptions("Title"); BlogPost alias = null; var query = unitOfWork.Session .QueryOver(() => alias) .Where(() => !alias.IsDeleted && alias.Status != PageStatus.Preview); if (!request.IncludeArchived) { query = query.Where(() => !alias.IsArchived); } if (!string.IsNullOrWhiteSpace(request.SearchQuery)) { var searchQuery = string.Format("%{0}%", request.SearchQuery); query = query.Where(Restrictions.InsensitiveLike(Projections.Property(() => alias.Title), searchQuery)); } if (request.LanguageId.HasValue) { if (request.LanguageId.Value.HasDefaultValue()) { query = query.Where(Restrictions.IsNull(Projections.Property(() => alias.Language.Id))); } else { query = query.Where(Restrictions.Eq(Projections.Property(() => alias.Language.Id), request.LanguageId.Value)); } } if (request.Tags != null) { foreach (var tagKeyValue in request.Tags) { var id = tagKeyValue.Key.ToGuidOrDefault(); query = query.WithSubquery.WhereExists(QueryOver.Of <PageTag>().Where(tag => tag.Tag.Id == id && tag.Page.Id == alias.Id).Select(tag => 1)); } } if (request.Categories != null) { var categories = request.Categories.Select(c => new Guid(c.Key)).Distinct().ToList(); foreach (var category in categories) { var childCategories = categoryService.GetChildCategoriesIds(category).ToArray(); query = query.WithSubquery.WhereExists(QueryOver.Of <PageCategory>().Where(cat => !cat.IsDeleted && cat.Page.Id == alias.Id).WhereRestrictionOn(cat => cat.Category.Id).IsIn(childCategories).Select(cat => 1)); } } if (request.Status.HasValue) { if (request.Status.Value == PageStatusFilterType.OnlyPublished) { query = query.Where(() => alias.Status == PageStatus.Published); } else if (request.Status.Value == PageStatusFilterType.OnlyUnpublished) { query = query.Where(() => alias.Status != PageStatus.Published); } else if (request.Status.Value == PageStatusFilterType.ContainingUnpublishedContents) { PageContent pageContentAlias = null; Root.Models.Content contentAlias = null; Root.Models.Content contentHistoryAlias = null; var subQuery = QueryOver.Of(() => pageContentAlias) .Inner.JoinAlias(() => pageContentAlias.Content, () => contentAlias, () => !contentAlias.IsDeleted) .Left.JoinAlias(() => contentAlias.History, () => contentHistoryAlias, () => !contentHistoryAlias.IsDeleted) .Where(() => pageContentAlias.Page.Id == alias.Id && !pageContentAlias.IsDeleted) .Where(() => contentHistoryAlias.Status == ContentStatus.Draft || contentAlias.Status == ContentStatus.Draft) .Select(p => 1); query = query.WithSubquery.WhereExists(subQuery); } } if (request.SeoStatus.HasValue) { var subQuery = QueryOver.Of <SitemapNode>() .Where(x => x.Page.Id == alias.Id || x.UrlHash == alias.PageUrlHash) .And(x => !x.IsDeleted) .JoinQueryOver(s => s.Sitemap) .And(x => !x.IsDeleted) .Select(s => 1); var hasSeoDisjunction = Restrictions.Disjunction() .Add(RestrictionsExtensions.IsNullOrWhiteSpace(Projections.Property(() => alias.MetaTitle))) .Add(RestrictionsExtensions.IsNullOrWhiteSpace(Projections.Property(() => alias.MetaKeywords))) .Add(RestrictionsExtensions.IsNullOrWhiteSpace(Projections.Property(() => alias.MetaDescription))) .Add(Subqueries.WhereNotExists(subQuery)); if (request.SeoStatus.Value == SeoStatusFilterType.HasSeo) { query = query.Where(Restrictions.Not(hasSeoDisjunction)); } else { query = query.Where(hasSeoDisjunction); } } if (joinContents) { PageContent pcAlias = null; BlogPostContent bcAlias = null; query = query.JoinAlias(() => alias.PageContents, () => pcAlias); query = query.JoinAlias(() => pcAlias.Content, () => bcAlias); } return(query); }
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) { 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 IHttpActionResult Update([FromBody] PageContent pageContent) { return(Ok(pageService.Update(pageContent))); }
// Print method public void Print(ReportData data) { // Select the printer for printing a report from the print dialog var printDialog = new PrintDialog(); if (printDialog.ShowDialog() == true) { // Obtain capabilities of the selected printer var pcaps = printDialog.PrintQueue.GetPrintCapabilities(); var pticket = printDialog.PrintTicket; // Supported page orientation is portrait and landscape only in this sample double reportWidth = 0, reportHeight = 0; switch (pticket.PageOrientation) { case System.Printing.PageOrientation.Portrait: reportWidth = pticket.PageMediaSize.Width ?? DEFAULT_PAPER_SIZE_A4_S; reportHeight = pticket.PageMediaSize.Height ?? DEFAULT_PAPER_SIZE_A4_L; break; case System.Printing.PageOrientation.Landscape: reportWidth = pticket.PageMediaSize.Height ?? DEFAULT_PAPER_SIZE_A4_L; reportHeight = pticket.PageMediaSize.Width ?? DEFAULT_PAPER_SIZE_A4_S; break; } // Create a new single page that the same size as the size of the selected paper var page = new FixedPage() { Width = reportWidth, Height = reportHeight, // Apply margins of the selected printer to the page Margin = new Thickness( pcaps.PageImageableArea.OriginWidth, pcaps.PageImageableArea.OriginHeight, 0, 0), }; // Create the report image with the ReportControl and align it to the page size var vb = new Viewbox { Width = reportWidth, Height = reportHeight, StretchDirection = StretchDirection.Both, Stretch = Stretch.Uniform, Child = new ReportControl { Width = DEFAULT_PAPER_SIZE_A4_S, Height = DEFAULT_PAPER_SIZE_A4_L, DataContext = data } }; // Create a new fixed document and add the page page.Children.Add(vb); var content = new PageContent(); ((IAddChild)content).AddChild(page); var fixedDoc = new FixedDocument(); fixedDoc.Pages.Add(content); // Print the document on the selected printer printDialog.PrintDocument(fixedDoc.DocumentPaginator, "Report print sample"); } }
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 should_import_all_pages_categories_and_usernames() { // Arrange ApplicationSettings applicationSettings = new ApplicationSettings(); applicationSettings.AttachmentsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ScrewturnImport"); if (Directory.Exists(applicationSettings.AttachmentsFolder)) { Directory.Delete(applicationSettings.AttachmentsFolder, true); } Directory.CreateDirectory(applicationSettings.AttachmentsFolder); applicationSettings.ConnectionString = _connectionString; applicationSettings.DatabaseName = "SqlServer2008"; var context = new LightSpeedContext(); context.ConnectionString = _connectionString; context.DataProvider = DataProvider.SqlServer2008; context.IdentityMethod = IdentityMethod.GuidComb; IUnitOfWork unitOfWork = context.CreateUnitOfWork(); IPageRepository pageRepository = new LightSpeedPageRepository(unitOfWork); IUserRepository userRepository = new LightSpeedUserRepository(unitOfWork); ScrewTurnImporter importer = new ScrewTurnImporter(applicationSettings, pageRepository, userRepository); // Act importer.ImportFromSqlServer(TestConstants.CONNECTION_STRING); // Assert User user = userRepository.GetUserByUsername("user2"); Assert.That(user.Id, Is.Not.EqualTo(Guid.Empty)); List <Page> pages = pageRepository.AllPages().ToList(); Assert.That(pages.Count, Is.EqualTo(3)); Page page1 = pages.FirstOrDefault(x => x.Title == "Screwturn page 1"); PageContent pageContent1 = pageRepository.GetLatestPageContent(page1.Id); Assert.That(page1.Tags, Is.EqualTo("Category1,")); AssertSameDateTimes(page1.CreatedOn, "2013-08-11 18:05"); AssertSameDateTimes(page1.ModifiedOn, "2013-08-11 18:05"); Assert.That(page1.CreatedBy, Is.EqualTo("admin")); Assert.That(page1.ModifiedBy, Is.EqualTo("admin")); Assert.That(pageContent1.Text, Is.EqualTo("This is an amazing Screwturn page.")); Page page2 = pages.FirstOrDefault(x => x.Title == "Screwturn page 2"); PageContent pageContent2 = pageRepository.GetLatestPageContent(page2.Id); Assert.That(page2.Tags, Is.EqualTo("Category1,Category2,")); AssertSameDateTimes(page2.CreatedOn, "2013-08-11 18:06"); AssertSameDateTimes(page2.ModifiedOn, "2013-08-11 18:06"); Assert.That(page2.CreatedBy, Is.EqualTo("user2")); Assert.That(page2.ModifiedBy, Is.EqualTo("user2")); Assert.That(pageContent2.Text, Is.EqualTo("Amazing screwturn page 2")); }
}// end:CreateSecondPageContent() // --------------------- CreateThirdPageContent ----------------------- /// <summary> /// Creates the content for the third fixed page.</summary> /// <param name="pq"> /// The print queue to output to.</param> /// <returns> /// The page content for the third fixed page.</returns> public PageContent CreateThirdPageContent(PrintQueue pq) { PageContent pageContent = new PageContent(); FixedPage fixedPage = new FixedPage(); fixedPage.Background = Brushes.White; Canvas canvas1 = new Canvas(); canvas1.Width = 8.5 * 96; canvas1.Height = 11 * 96; // Top-Left TextBlock label = new TextBlock(); label.Foreground = Brushes.Black; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 14.0; label.Text = String1; Canvas.SetTop(label, 0); Canvas.SetLeft(label, 0); canvas1.Children.Add(label); label = new TextBlock(); label.Foreground = Brushes.Black; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 14.0; label.Text = String2; Canvas.SetTop(label, 20); Canvas.SetLeft(label, 0); canvas1.Children.Add(label); label = new TextBlock(); label.Foreground = Brushes.Black; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 14.0; label.Text = String3; Canvas.SetTop(label, 40); Canvas.SetLeft(label, 0); canvas1.Children.Add(label); label = new TextBlock(); label.Foreground = Brushes.Black; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 14.0; label.Text = String4; Canvas.SetTop(label, 60); Canvas.SetLeft(label, 0); canvas1.Children.Add(label); label = new TextBlock(); label.Foreground = Brushes.Black; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 14.0; label.Text = String5; Canvas.SetTop(label, 80); Canvas.SetLeft(label, 0); canvas1.Children.Add(label); fixedPage.Children.Add(canvas1); double pageWidth = 96 * 8.5; double pageHeight = 96 * 11; fixedPage.Width = pageWidth; fixedPage.Height = pageHeight; PerformTransform(ref fixedPage, pq); ((IAddChild)pageContent).AddChild(fixedPage); return(pageContent); }// end:CreateThirdPageContent()
public PageModel(PageContent page, PageTemplate pageTemplate) { this.Title = page.Title; this.PageTemplate = pageTemplate; }
public string GetItemHtml(ELoadingType loadingType, string returnUrl, NameValueCollection additional) { var htmlBuilder = new StringBuilder(); var parentsCount = _channelInfo.ParentsCount; for (var i = 0; i < parentsCount; i++) { htmlBuilder.Append($@"<img align=""absmiddle"" src=""{_iconEmptyUrl}"" />"); } if (_channelInfo.ChildrenCount > 0) { htmlBuilder.Append( _channelInfo.SiteId == _channelInfo.Id ? $@"<img align=""absmiddle"" style=""cursor:pointer"" onClick=""displayChildren(this);"" isAjax=""false"" isOpen=""true"" id=""{_channelInfo .Id}"" src=""{_iconMinusUrl}"" />" : $@"<img align=""absmiddle"" style=""cursor:pointer"" onClick=""displayChildren(this);"" isAjax=""true"" isOpen=""false"" id=""{_channelInfo .Id}"" src=""{_iconPlusUrl}"" />"); } else { htmlBuilder.Append($@"<img align=""absmiddle"" src=""{_iconEmptyUrl}"" />"); } if (!string.IsNullOrEmpty(_iconFolderUrl)) { htmlBuilder.Append( _channelInfo.Id > 0 ? $@"<a href=""{PageRedirect.GetRedirectUrlToChannel(_channelInfo.SiteId, _channelInfo.Id)}"" target=""_blank"" title=""浏览页面""><img align=""absmiddle"" border=""0"" src=""{_iconFolderUrl}"" style=""max-height: 22px; max-width: 22px"" /></a>" : $@"<img align=""absmiddle"" src=""{_iconFolderUrl}"" style=""max-height: 22px; max-width: 22px"" />"); } htmlBuilder.Append(" "); if (_enabled) { if (loadingType == ELoadingType.ContentTree) { var linkUrl = PageContent.GetRedirectUrl(_channelInfo.SiteId, _channelInfo.Id); htmlBuilder.Append( $"<a href='{linkUrl}' isLink='true' onclick='fontWeightLink(this)' target='content'>{_channelInfo.ChannelName}</a>"); } else if (loadingType == ELoadingType.ChannelSelect) { var linkUrl = ModalChannelSelect.GetRedirectUrl(_channelInfo.SiteId, _channelInfo.Id); if (additional != null) { if (!string.IsNullOrEmpty(additional["linkUrl"])) { linkUrl = additional["linkUrl"] + _channelInfo.Id; } else { foreach (string key in additional.Keys) { linkUrl += $"&{key}={additional[key]}"; } } } htmlBuilder.Append($"<a href='{linkUrl}'>{_channelInfo.ChannelName}</a>"); } else { if (AdminUtility.HasChannelPermissions(_administratorName, _channelInfo.SiteId, _channelInfo.Id, ConfigManager.Permissions.Channel.ChannelEdit)) { var onClickUrl = ModalChannelEdit.GetOpenWindowString(_channelInfo.SiteId, _channelInfo.Id, returnUrl); htmlBuilder.Append( $@"<a href=""javascript:;;"" onClick=""{onClickUrl}"" title=""快速编辑栏目"">{_channelInfo.ChannelName}</a>"); } else { htmlBuilder.Append($@"<a href=""javascript:;;"">{_channelInfo.ChannelName}</a>"); } } } else { htmlBuilder.Append(_channelInfo.ChannelName); } if (_channelInfo.SiteId != 0) { htmlBuilder.Append(" "); htmlBuilder.Append(ChannelManager.GetNodeTreeLastImageHtml(_siteInfo, _channelInfo)); if (_channelInfo.ContentNum < 0) { return(htmlBuilder.ToString()); } htmlBuilder.Append( $@"<span style=""font-size:8pt;font-family:arial"" class=""gray"">({_channelInfo.ContentNum})</span>"); } return(htmlBuilder.ToString()); }
public string ConvertToPdf(string outputFile, Dictionary <int, PrintCanvas> pages) { // NOTE: PdfSharp prints only up to 50 pages in the conversion from xps to pdf. // In some documentation found it seems that this is a debug flag wrapped in #DEBUG // During release build I found that this flag does not work, // and I had to implement document merging to build documents with more than 50 pages if (pages.Count == 0) { pages.Add(0, new PrintCanvas { Width = 100, Height = 100 }); } string formatedOutputFile = this.PreparePdfFileName(outputFile); string formatedFileName = this.ChangeFilenameToXPS(formatedOutputFile); try { List <string> fileNamesList = new List <string>(); FixedDocument fixedDoc = new FixedDocument(); int pageIndex = 0; int batchIndex = 1; formatedFileName = this.UpdateBatchfileName(formatedFileName, batchIndex); fileNamesList.Add(formatedFileName); foreach (KeyValuePair <int, PrintCanvas> pageKeyPair in pages) { Size size = new Size(pageKeyPair.Value.Width, pageKeyPair.Value.Height); PageContent pageContent = new PageContent(); FixedPage page = new FixedPage(); FixedPage.SetLeft(pageKeyPair.Value, 0); FixedPage.SetTop(pageKeyPair.Value, 0); page.Width = size.Width; page.Height = size.Height; page.Children.Add(pageKeyPair.Value); page.Measure(size); page.Arrange(new Rect(0, 0, size.Width, size.Height)); page.UpdateLayout(); fixedDoc.Pages.Add(pageContent); ((System.Windows.Markup.IAddChild)pageContent).AddChild(page); ++pageIndex; if (pageIndex == this.pdfBatchSize) { this.WriteXpsBatchDocument(batchIndex, formatedFileName, fixedDoc); ++batchIndex; formatedFileName = this.UpdateBatchfileName(formatedFileName, batchIndex); fileNamesList.Add(formatedFileName); fixedDoc = new FixedDocument(); pageIndex = 0; } } if (pageIndex > 0 && pageIndex < this.pdfBatchSize) { this.WriteXpsBatchDocument(batchIndex, formatedFileName, fixedDoc); } List <string> pdfFileNames = this.ConvertXpsBatchesToPdf(fileNamesList, this.PreparePdfFileName(formatedOutputFile)); this.MergePdfFiles(pdfFileNames, formatedOutputFile); return(formatedOutputFile); } catch (Exception err) { throw; } }
protected void Page_Load(object sender, EventArgs e) { rssFeedsMode = Settings.RssFeedsMode; if (rssFeedsMode == RssFeedsMode.Disabled) { Response.Clear(); Response.StatusCode = 404; Response.End(); return; } string currentUsername = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(); currentNamespace = DetectNamespace(); if (string.IsNullOrEmpty(currentNamespace)) { currentNamespace = null; } if (SessionFacade.LoginKey == null) { // Look for username/password in the query string if (Request["Username"] != null && Request["Password"] != null) { // Try to authenticate UserInfo u = Users.FindUser(Request["Username"]); if (u != null) { // Very "dirty" way - pages should not access Providers if (u.Provider.TestAccount(u, Request["Password"])) { // Valid account currentUsername = Request["Username"]; currentGroups = Users.FindUser(currentUsername).Groups; } } else { // Check for built-in admin account if (Request["Username"].Equals("admin") && Request["Password"].Equals(Settings.MasterPassword)) { currentUsername = "******"; currentGroups = new string[] { Settings.AdministratorsGroup }; } } } } Response.ClearContent(); Response.ContentType = "text/xml;charset=UTF-8"; Response.ContentEncoding = System.Text.UTF8Encoding.UTF8; if (Request["Page"] != null) { PageInfo page = Pages.FindPage(Request["Page"]); if (page == null) { return; } PageContent content = Content.GetPageContent(page, true); if (Request["Discuss"] == null) { // Check permission for the page bool canReadPage = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage, currentUsername, currentGroups); if (!canReadPage) { Response.StatusCode = 401; return; } // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page)), Settings.MainUrl + page.FullName + Settings.PageExtension, Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx?Page=", page.FullName), Formatter.StripHtml(content.Title) + " - " + Properties.Messages.PageUpdates, DateTime.Now); // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page))); rss.WriteEndElement(); rss.WriteElementString("link", Settings.MainUrl + page.FullName + Settings.PageExtension); // Create the description tag rss.WriteStartElement("description"); if (rssFeedsMode == RssFeedsMode.Summary) { rss.WriteCData(Formatter.StripHtml(content.Title) + ": " + Properties.Messages.ThePageHasBeenUpdatedBy + " " + content.User + (content.Comment.Length > 0 ? ".<br />" + content.Comment : ".")); } else { rss.WriteCData(Content.GetFormattedPageContent(page, false)); } rss.WriteEndElement(); // Write the remaining elements BuildAuthorTag(rss, content.User); rss.WriteElementString("pubDate", content.LastModified.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(page.FullName, content.LastModified)); rss.WriteEndElement(); // Complete the item element CompleteCurrentElement(rss); // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } else { // Check permission for the discussion bool canReadDiscussion = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadDiscussion, currentUsername, currentGroups); if (!canReadDiscussion) { Response.StatusCode = 401; return; } List <Message> messages = new List <Message>(Pages.GetPageMessages(page)); // Un-tree Messages messages = UnTreeMessages(messages); // Sort from newer to older messages.Sort(new MessageDateTimeComparer(true)); // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page)) + " - Discussion Updates", Settings.MainUrl + page.FullName + Settings.PageExtension + "?Discuss=1", Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx?Page=", page.FullName, "&Discuss=1"), Settings.WikiTitle + " - " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page)) + " - Discussion Updates", messages.OrderByDescending(x => x.DateTime).FirstOrDefault().DateTime); for (int i = 0; i < messages.Count; i++) { // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Formatter.StripHtml(FormattingPipeline.PrepareTitle(messages[i].Subject, false, FormattingContext.MessageBody, page))); rss.WriteEndElement(); rss.WriteElementString("link", Settings.MainUrl + page.FullName + Settings.PageExtension + "?Discuss=1"); // Create the description tag rss.WriteStartElement("description"); if (rssFeedsMode == RssFeedsMode.Summary) { rss.WriteCData(Properties.Messages.AMessageHasBeenPostedBy.Replace("##SUBJECT##", messages[i].Subject) + " " + messages[i].Username + "."); } else { rss.WriteCData(FormattingPipeline.FormatWithPhase3(FormattingPipeline.FormatWithPhase1And2(messages[i].Body, false, FormattingContext.MessageBody, page), FormattingContext.MessageBody, page)); } rss.WriteEndElement(); // Write the remaining elements BuildAuthorTag(rss, messages[i].Username); rss.WriteElementString("pubDate", messages[i].DateTime.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(page.FullName + "-" + messages[i].ID.ToString(), messages[i].DateTime)); rss.WriteEndElement(); // Complete the item element CompleteCurrentElement(rss); } // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } } else { if (Request["Discuss"] == null) { // All page updates // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); bool useCat = false; string cat = ""; if (Request["Category"] != null) { useCat = true; cat = Request["Category"]; } RecentChange[] ch = RecentChanges.GetAllChanges(); // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Properties.Messages.PageUpdates, Settings.MainUrl, Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx", (useCat ? ("?Category=" + cat) : "")), Properties.Messages.RecentPageUpdates, ch.OrderByDescending(x => x.DateTime).FirstOrDefault().DateTime); Array.Reverse(ch); for (int i = 0; i < ch.Length; i++) { // Suppress this entry if we've already reported this page (so we don't create duplicate entries in the feed page) bool duplicateFound = false; for (int j = 0; j < i; j++) { if (ch[j].Page == ch[i].Page) { duplicateFound = true; break; } } if (duplicateFound) { continue; } // Skip message-related entries if (!IsPageChange(ch[i].Change)) { continue; } PageInfo p = Pages.FindPage(ch[i].Page); if (p != null) { // Check permissions for every page bool canReadThisPage = AuthChecker.CheckActionForPage(p, Actions.ForPages.ReadPage, currentUsername, currentGroups); if (!canReadThisPage) { continue; } if (useCat) { CategoryInfo[] infos = Pages.GetCategoriesForPage(p); if (infos.Length == 0 && cat != "-") { continue; } else if (infos.Length != 0) { bool found = false; for (int k = 0; k < infos.Length; k++) { if (infos[k].FullName == cat) { found = true; break; } } if (!found) { continue; } } } } // Check namespace if (p != null && NameTools.GetNamespace(p.FullName) != currentNamespace) { continue; } // Skip deleted pages as their category binding is unknown if (p == null && useCat) { continue; } // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Formatter.StripHtml(FormattingPipeline.PrepareTitle(ch[i].Title, false, FormattingContext.PageContent, p))); rss.WriteEndElement(); if (ch[i].Change != Change.PageDeleted && p != null) { rss.WriteElementString("link", Settings.MainUrl + ch[i].Page + Settings.PageExtension); } else { rss.WriteElementString("link", Settings.MainUrl); } BuildAuthorTag(rss, ch[i].User); // Create the description tag StringBuilder sb = new StringBuilder(); if (rssFeedsMode == RssFeedsMode.Summary || p == null) { switch (ch[i].Change) { case Change.PageUpdated: sb.Append(Properties.Messages.ThePageHasBeenUpdatedBy); break; case Change.PageDeleted: sb.Append(Properties.Messages.ThePageHasBeenDeletedBy); break; case Change.PageRenamed: sb.Append(Properties.Messages.ThePageHasBeenRenamedBy); break; case Change.PageRolledBack: sb.Append(Properties.Messages.ThePageHasBeenRolledBackBy); break; } sb.Append(" " + ch[i].User + (ch[i].Description.Length > 0 ? ".<br />" + ch[i].Description : ".")); } else { // p != null sb.Append(Content.GetFormattedPageContent(p, false)); } rss.WriteStartElement("description"); rss.WriteCData(sb.ToString()); rss.WriteEndElement(); // Write the remaining elements rss.WriteElementString("pubDate", ch[i].DateTime.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(ch[i].Page, ch[i].DateTime)); rss.WriteEndElement(); // Complete the item element rss.WriteEndElement(); } // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } else { // All discussion updates // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); bool useCat = false; string cat = ""; if (Request["Category"] != null) { useCat = true; cat = Request["Category"]; } RecentChange[] ch = RecentChanges.GetAllChanges(); // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Properties.Messages.DiscussionUpdates, Settings.MainUrl, Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx", (useCat ? ("?Category=" + cat) : "")), Properties.Messages.RecentDiscussionUpdates, ch.OrderByDescending(x => x.DateTime).FirstOrDefault().DateTime); Array.Reverse(ch); for (int i = 0; i < ch.Length; i++) { // Skip page-related entries if (!IsMessageChange(ch[i].Change)) { continue; } PageInfo p = Pages.FindPage(ch[i].Page); if (p != null) { // Check permissions for every page bool canReadThisPageDiscussion = AuthChecker.CheckActionForPage(p, Actions.ForPages.ReadDiscussion, currentUsername, currentGroups); if (!canReadThisPageDiscussion) { continue; } if (useCat) { CategoryInfo[] infos = Pages.GetCategoriesForPage(p); if (infos.Length == 0 && cat != "-") { continue; } else if (infos.Length != 0) { bool found = false; for (int k = 0; k < infos.Length; k++) { if (infos[k].FullName == cat) { found = true; break; } } if (!found) { continue; } } } // Check namespace if (NameTools.GetNamespace(p.FullName) != currentNamespace) { continue; } // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Properties.Messages.Discussion + ": " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(ch[i].Title, false, FormattingContext.PageContent, p))); rss.WriteEndElement(); string id = Tools.GetMessageIdForAnchor(ch[i].DateTime); if (ch[i].Change != Change.MessageDeleted) { rss.WriteElementString("link", Settings.MainUrl + ch[i].Page + Settings.PageExtension + "?Discuss=1#" + id); } else { rss.WriteElementString("link", Settings.MainUrl + ch[i].Page + Settings.PageExtension + "?Discuss=1"); } string messageContent = FindMessageContent(ch[i].Page, id); // Create the description tag StringBuilder sb = new StringBuilder(); if (rssFeedsMode == RssFeedsMode.Summary || messageContent == null) { switch (ch[i].Change) { case Change.MessagePosted: sb.Append(Properties.Messages.AMessageHasBeenPostedBy.Replace("##SUBJECT##", ch[i].MessageSubject)); break; case Change.MessageEdited: sb.Append(Properties.Messages.AMessageHasBeenEditedBy.Replace("##SUBJECT##", ch[i].MessageSubject)); break; case Change.MessageDeleted: sb.Append(Properties.Messages.AMessageHasBeenDeletedBy.Replace("##SUBJECT##", ch[i].MessageSubject)); break; } sb.Append(" " + ch[i].User + (ch[i].Description.Length > 0 ? ".<br />" + ch[i].Description : ".")); } else { sb.Append(FormattingPipeline.FormatWithPhase3(FormattingPipeline.FormatWithPhase1And2(messageContent, false, FormattingContext.MessageBody, null), FormattingContext.MessageBody, null)); } rss.WriteStartElement("description"); rss.WriteCData(sb.ToString()); rss.WriteEndElement(); // Write the remaining elements BuildAuthorTag(rss, ch[i].User); rss.WriteElementString("pubDate", ch[i].DateTime.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(ch[i].Page, ch[i].DateTime)); rss.WriteEndElement(); // Complete the item element rss.WriteEndElement(); } } // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } } }
protected void Page_Load(object sender, EventArgs e) { discussMode = Request["Discuss"] != null; viewCodeMode = Request["Code"] != null && !discussMode; if (!Settings.EnableViewPageCodeFeature) { viewCodeMode = false; } currentPage = DetectPageInfo(true); VerifyAndPerformRedirects(); // The following actions are verified: // - View content (redirect to AccessDenied) // - Edit or Edit with Approval (for button display) // - Any Administrative activity (Rollback/Admin/Perms) (for button display) // - Download attachments (for button display - download permissions are also checked in GetFile) // - View discussion (for button display in content mode) // - Post discussion (for button display in discuss mode) string currentUsername = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(); bool canView = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadPage, currentUsername, currentGroups); bool canEdit = false; bool canEditWithApproval = false; Pages.CanEditPage(currentPage, currentUsername, currentGroups, out canEdit, out canEditWithApproval); if (canEditWithApproval && canEdit) { canEditWithApproval = false; } bool canDownloadAttachments = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.DownloadAttachments, currentUsername, currentGroups); bool canSetPerms = AuthChecker.CheckActionForGlobals(Actions.ForGlobals.ManagePermissions, currentUsername, currentGroups); bool canAdmin = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ManagePage, currentUsername, currentGroups); bool canViewDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadDiscussion, currentUsername, currentGroups); bool canPostDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.PostDiscussion, currentUsername, currentGroups); bool canManageDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ManageDiscussion, currentUsername, currentGroups); if (!canView) { if (SessionFacade.LoginKey == null) { UrlTools.Redirect("Login.aspx?Redirect=" + Tools.UrlEncode(Tools.GetCurrentUrlFixed())); } else { UrlTools.Redirect(UrlTools.BuildUrl("AccessDenied.aspx")); } } attachmentViewer.Visible = canDownloadAttachments; attachmentViewer.PageInfo = currentPage; currentContent = Content.GetPageContent(currentPage, true); pnlPageInfo.Visible = Settings.EnablePageInfoDiv; SetupTitles(); SetupToolbarLinks(canEdit || canEditWithApproval, canViewDiscussion, canPostDiscussion, canDownloadAttachments, canAdmin, canAdmin, canSetPerms); SetupLabels(); SetupPrintAndRssLinks(); SetupMetaInformation(); VerifyAndPerformPageRedirection(); SetupRedirectionSource(); SetupNavigationPaths(); SetupAdjacentPages(); SessionFacade.Breadcrumbs.AddPage(currentPage); SetupBreadcrumbsTrail(); SetupDoubleClickHandler(); SetupEmailNotification(); SetupPageContent(canPostDiscussion, canManageDiscussion); if (currentPage != null) { Literal canonical = new Literal(); canonical.Text = Tools.GetCanonicalUrlTag(Request.Url.ToString(), currentPage, Pages.FindNamespace(NameTools.GetNamespace(currentPage.FullName))); Page.Header.Controls.Add(canonical); } }
public void Edit(PageContent content) { content.ValidateFields(); _dataAccess.Edit(content); }
/// <summary> /// 把集合写入XML流 /// </summary> /// <param name="list">集合</param> /// <param name="stm">流</param> /// <param name="objPage">分页</param> /// <param name="encoding">编码</param> public static void WriteXml(IList list, Stream stm, PageContent objPage, Encoding encoding) { if (list.Count <= 0) { return; } Type type = list[0].GetType(); ClassInfoHandle entityInfo = null; if (!type.IsValueType) { entityInfo = ClassInfoManager.GetClassHandle(type); } //Dictionary<string,EntityPropertyInfo>.Enumerator enuEntityProInfo=entityInfo.PropertyInfo.GetPropertyEnumerator(); XmlDocument doc = new XmlDocument(); string strxmlBase = ""; strxmlBase += "<?xml version=\"1.0\" encoding=\"" + encoding.BodyName + "\" ?>"; strxmlBase += "<root></root>"; doc.LoadXml(strxmlBase); XmlNode rootNode = doc.GetElementsByTagName("root")[0]; foreach (object obj in list) { XmlElement ele = doc.CreateElement("item"); if (entityInfo != null) { foreach (PropertyInfoHandle info in entityInfo.PropertyInfo) { if (info.PropertyType.IsValueType || info.PropertyType == typeof(string) || info.PropertyType == typeof(Nullable <>)) { XmlElement eleItem = doc.CreateElement(info.PropertyName); object value = info.GetValue(obj); string curValue = ValueToString(value); eleItem.InnerText = curValue; ele.AppendChild(eleItem); } } } else { ele.InnerText = obj.ToString(); } rootNode.AppendChild(ele); } if (objPage != null) //写入分页信息 { XmlAttribute attTotalPage = doc.CreateAttribute("totalPage"); attTotalPage.InnerText = objPage.TotalPage.ToString(); rootNode.Attributes.Append(attTotalPage); XmlAttribute attCurrentPage = doc.CreateAttribute("currentPage"); attCurrentPage.InnerText = objPage.CurrentPage.ToString(); rootNode.Attributes.Append(attCurrentPage); XmlAttribute attPageSize = doc.CreateAttribute("pageSize"); attPageSize.InnerText = objPage.PageSize.ToString(); rootNode.Attributes.Append(attPageSize); } doc.Save(stm); }
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); } } }
protected virtual IQueryOver<PagesView, PagesView> FilterQuery(IQueryOver<PagesView, PagesView> query, PagesFilter request, Junction hasnotSeoDisjunction) { PageProperties alias = null; if (!request.IncludeArchived) { query = query.Where(() => !alias.IsArchived); } if (request.OnlyMasterPages) { query = query.Where(() => alias.IsMasterPage); } else if (!request.IncludeMasterPages) { query = query.Where(() => !alias.IsMasterPage); } if (!string.IsNullOrWhiteSpace(request.SearchQuery)) { var searchQuery = string.Format("%{0}%", request.SearchQuery); query = query.Where(Restrictions.Disjunction() .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.Title), searchQuery)) .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.PageUrl), searchQuery)) .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.MetaTitle), searchQuery)) .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.MetaDescription), searchQuery)) .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.MetaKeywords), searchQuery))); } if (request.CategoryId.HasValue) { query = query.Where(Restrictions.Eq(Projections.Property(() => alias.Category.Id), request.CategoryId.Value)); } if (request.LanguageId.HasValue) { if (request.LanguageId.Value.HasDefaultValue()) { query = query.Where(Restrictions.IsNull(Projections.Property(() => alias.Language.Id))); } else { query = query.Where(Restrictions.Eq(Projections.Property(() => alias.Language.Id), request.LanguageId.Value)); } } if (request.Tags != null) { foreach (var tagKeyValue in request.Tags) { var id = tagKeyValue.Key.ToGuidOrDefault(); query = query.WithSubquery.WhereExists(QueryOver.Of<PageTag>().Where(tag => tag.Tag.Id == id && tag.Page.Id == alias.Id).Select(tag => 1)); } } if (request.Status.HasValue) { if (request.Status.Value == PageStatusFilterType.OnlyPublished) { query = query.Where(() => alias.Status == PageStatus.Published); } else if (request.Status.Value == PageStatusFilterType.OnlyUnpublished) { query = query.Where(() => alias.Status != PageStatus.Published); } else if (request.Status.Value == PageStatusFilterType.ContainingUnpublishedContents) { const ContentStatus draft = ContentStatus.Draft; Root.Models.Content contentAlias = null; var subQuery = QueryOver.Of<PageContent>() .JoinAlias(p => p.Content, () => contentAlias) .Where(pageContent => pageContent.Page.Id == alias.Id) .And(() => contentAlias.Status == draft) .And(() => !contentAlias.IsDeleted) .Select(pageContent => 1); query = query.WithSubquery.WhereExists(subQuery); } } if (request.SeoStatus.HasValue) { if (request.SeoStatus.Value == SeoStatusFilterType.HasNotSeo) { query = query.Where(hasnotSeoDisjunction); } else { query = query.Where(Restrictions.Not(hasnotSeoDisjunction)); } } if (!string.IsNullOrWhiteSpace(request.Layout)) { Guid id; var length = request.Layout.Length - 2; if (request.Layout.StartsWith("m-") && Guid.TryParse(request.Layout.Substring(2, length), out id)) { query = query.Where(() => alias.MasterPage.Id == id); } if (request.Layout.StartsWith("l-") && Guid.TryParse(request.Layout.Substring(2, length), out id)) { query = query.Where(() => alias.Layout.Id == id); } } if (request.ContentId.HasValue) { Root.Models.Content contentAlias = null; ChildContent childContentAlias = null; HtmlContent htmlContentAlias = null; PageContent pageContentAlias = null; var htmlChildContentSubQuery = QueryOver.Of(() => htmlContentAlias) .JoinAlias(h => h.ChildContents, () => childContentAlias) .Where(() => htmlContentAlias.Id == contentAlias.Id) .And(() => childContentAlias.Child.Id == request.ContentId.Value) .Select(pageContent => 1); var pageContentSubQuery = QueryOver.Of(() => pageContentAlias) .JoinAlias(() => pageContentAlias.Content, () => contentAlias) .And(() => pageContentAlias.Page.Id == alias.Id) .And(() => !contentAlias.IsDeleted) .And(() => !pageContentAlias.IsDeleted) .And(Restrictions.Or( Restrictions.Where(() => contentAlias.Id == request.ContentId.Value), Subqueries.WhereExists(htmlChildContentSubQuery) )) .Select(pageContent => 1); query = query.WithSubquery.WhereExists(pageContentSubQuery); } return query; }
public void DeletePageContent(PageContent pageContent) { PageContentEntity entity = UnitOfWork.FindById<PageContentEntity>(pageContent.Id); UnitOfWork.Remove(entity); UnitOfWork.SaveChanges(); }
/// <summary> /// 查询并且返回DataSet(游标分页) /// </summary> /// <param name="sql">要查询的SQL语句</param> /// <param name="lstParam">参数集合</param> /// <param name="objPage">分页对象</param> /// <param name="oper">数据库对象</param> /// <param name="curType">映射的实体类型(如果用回数据库的原列名,则此为null)</param> /// <returns></returns> public DataTable QueryDataTable(string sql, ParamList lstParam, PageContent objPage, DataBaseOperate oper, Type curType) { throw new Exception("SqlServer不支持带参数的游标分页"); }
/// <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); }
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; }
protected void Page_Load(object sender, EventArgs e) { Page.Title = Properties.Messages.PostTitle + " - " + Settings.WikiTitle; if (Request["Page"] == null) { UrlTools.RedirectHome(); } page = Pages.FindPage(Request["Page"]); if (page == null) { UrlTools.RedirectHome(); } editor.CurrentPage = page; if (page.Provider.ReadOnly) { UrlTools.Redirect(UrlTools.BuildUrl(page.FullName, Settings.PageExtension)); } content = Content.GetPageContent(page, true); if (!Page.IsPostBack) { lblTitle.Text += " - " + FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.MessageBody, page); } // Verify permissions and setup captcha bool canPostMessage = AuthChecker.CheckActionForPage(page, Actions.ForPages.PostDiscussion, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()); if (!canPostMessage) { UrlTools.Redirect(UrlTools.BuildUrl(Tools.UrlEncode(page.FullName), Settings.PageExtension)); } captcha.Visible = SessionFacade.LoginKey == null && !Settings.DisableCaptchaControl; if (Page.IsPostBack) { return; } editor.SetContent("", Settings.UseVisualEditorAsDefault); string username = Request.UserHostAddress; if (SessionFacade.LoginKey != null) { username = SessionFacade.CurrentUsername; } bool edit = Request["Edit"] != null; if (!edit) { if (Request["Parent"] != null) { try { int.Parse(Request["Parent"]); } catch { UrlTools.RedirectHome(); } Message[] messages = Pages.GetPageMessages(page); Message parent = Pages.FindMessage(messages, int.Parse(Request["Parent"])); if (parent != null) { txtSubject.Text = (!parent.Subject.ToLowerInvariant().StartsWith("re:") ? "Re: " : "") + parent.Subject; } } } else { try { int.Parse(Request["Edit"]); } catch { UrlTools.RedirectHome(); } Message[] messages = Pages.GetPageMessages(page); Message msg = Pages.FindMessage(messages, int.Parse(Request["Edit"])); if (msg != null) { txtSubject.Text = msg.Subject; editor.SetContent(msg.Body, Settings.UseVisualEditorAsDefault); } else { throw new Exception("Message not found (" + page.FullName + "." + Request["Edit"] + ")."); } } }
/// <summary> /// 游标分页 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="lstParam">参数集合</param> /// <param name="sql">sql语句</param> /// <param name="objPage">分页实体</param> /// <param name="oper">数据库链接</param> /// <returns></returns> public IDataReader Query(string sql, ParamList lstParam, PageContent objPage, DataBaseOperate oper) { throw new Exception("SqlServer不支持带参数的游标分页"); }
/// <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; }
/// <summary> /// 从流中读取XML /// </summary> /// <param name="stm">流</param> /// <returns></returns> public static List <T> ReadXML <T>(Stream stm, PageContent objPage) { stm.Position = 0; Type type = typeof(T); List <T> lst = new List <T>(); XmlDocument doc = new XmlDocument(); doc.Load(stm); if (objPage != null) //读取分页信息 { XmlNodeList rootList = doc.GetElementsByTagName("root"); if (rootList.Count > 0) { XmlAttribute attTotalRecord = rootList[0].Attributes["totalRecord"]; XmlAttribute attCurrentPage = rootList[0].Attributes["currentPage"]; XmlAttribute attPageSize = rootList[0].Attributes["pageSize"]; if (attTotalRecord != null) { objPage.TotalRecords = Convert.ToInt64(attTotalRecord.InnerText); } if (attCurrentPage != null) { objPage.CurrentPage = Convert.ToInt32(attCurrentPage.InnerText); } if (attPageSize != null) { objPage.PageSize = Convert.ToInt32(attPageSize.InnerText); } } } ClassInfoHandle entityInfo = null; if (!type.IsValueType) { entityInfo = ClassInfoManager.GetClassHandle(type); } XmlNodeList nodeList = doc.GetElementsByTagName("item"); foreach (XmlNode node in nodeList) { if (entityInfo != null) { T obj = (T)entityInfo.CreateInstance(); foreach (XmlNode itemNode in node.ChildNodes) { string tagName = itemNode.Name; string value = itemNode.InnerText; PropertyInfoHandle info = entityInfo.PropertyInfo[tagName]; if (info != null) { Type resType = info.PropertyType; object curValue = StringToValue(value, resType); //转换成对象的值 info.SetValue(obj, curValue); //赋值 } } lst.Add(obj); } else { T curValue = (T)StringToValue(node.InnerText, type);//转换成对象的值 lst.Add(curValue); } } return(lst); }
/// <summary> /// Executes the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public bool Execute(PageContentSortViewModel request) { UnitOfWork.BeginTransaction(); var sortedPageContents = new List <PageContent>(); var regionIds = request.PageContents.Select(r => r.RegionId).Distinct().ToArray(); var parentPageContentIds = request.PageContents.Where(r => r.ParentPageContentId.HasValue).Select(r => r.ParentPageContentId.Value); var pageContentIds = request.PageContents.Select(r => r.PageContentId).Concat(parentPageContentIds).Distinct().ToArray(); // Load all page contents from all regions from request var contentsFuture = Repository .AsQueryable <PageContent>() .Where(f => f.Page.Id == request.PageId && (regionIds.Contains(f.Region.Id) || pageContentIds.Contains(f.Id))) .ToFuture(); // Demand access if (cmsConfiguration.Security.AccessControlEnabled) { var page = Repository .AsQueryable <Root.Models.Page>() .Where(p => p.Id == request.PageId) .FetchMany(p => p.AccessRules) .ToFuture() .ToList() .FirstOne(); AccessControlService.DemandAccess(page, Context.Principal, AccessLevel.ReadWrite, RootModuleConstants.UserRoles.EditContent); } else { AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.EditContent); } var pageContents = contentsFuture.ToList(); request.PageContents .GroupBy(group => new System.Tuple <Guid, Guid?>(group.RegionId, group.ParentPageContentId)) .ForEach(group => { var regionId = group.Key.Item1; var parentPageContentId = group.Key.Item2; var region = Repository.AsProxy <Region>(regionId); var index = 0; foreach (var viewModel in group) { var pageContent = pageContents.FirstOrDefault(f => f.Id == viewModel.PageContentId); PageContent parentPageContent = null; if (parentPageContentId.HasValue && !parentPageContentId.Value.HasDefaultValue()) { parentPageContent = pageContents.Where(f => f.Id == parentPageContentId).FirstOne(); } if (pageContent == null) { throw new EntityNotFoundException(typeof(PageContent), Guid.Empty); } if (pageContent.Order != index || pageContent.Region.Id != regionId || pageContent.Parent == null && parentPageContent != null || pageContent.Parent != null && parentPageContent == null || (pageContent.Parent != null && parentPageContent != null && parentPageContent.Id != pageContent.Parent.Id)) { if (pageContent.Version != viewModel.Version) { throw new ConcurrentDataException(pageContent); } pageContent.Order = index; pageContent.Region = region; pageContent.Parent = parentPageContent; sortedPageContents.Add(pageContent); Repository.Save(pageContent); } index++; } }); UnitOfWork.Commit(); // Notify foreach (var pageContent in sortedPageContents) { // Notify. Events.PageEvents.Instance.OnPageContentSorted(pageContent); } return(true); }
/// <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> /// 游标分页 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="lstParam">参数集合</param> /// <param name="sql">sql语句</param> /// <param name="objPage">分页实体</param> /// <param name="oper">数据库链接</param> /// <returns></returns> public IDataReader Query(string sql, ParamList lstParam, PageContent objPage, DataBaseOperate oper) { return(CursorPageCutter.Query(sql, lstParam, objPage, oper, null)); }
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 }; } }
/// <summary> /// 查询并且返回DataSet(游标分页) /// </summary> /// <param name="sql">要查询的SQL语句</param> /// <param name="lstParam">参数集合</param> /// <param name="objPage">分页对象</param> /// <param name="oper">数据库对象</param> /// <param name="curType">映射的实体类型(如果用回数据库的原列名,则此为null)</param> /// <returns></returns> public DataTable QueryDataTable(string sql, ParamList lstParam, PageContent objPage, DataBaseOperate oper, Type curType) { return(CursorPageCutter.QueryDataTable(sql, lstParam, objPage, oper, curType, null)); }
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> /// 生成分页SQL语句 /// </summary> /// <param name="list">参数列表</param> /// <param name="oper">连接对象</param> /// <param name="objCondition">条件对象</param> /// <param name="objPage">分页记录类</param> /// <returns></returns> public virtual string CreatePageSql(ParamList list, DataBaseOperate oper, SelectCondition objCondition, PageContent objPage, bool useCache) { return(CutPageSqlCreater.CreatePageSql(list, oper, objCondition, objPage, useCache)); }
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 }; } }
public Page Create(int number, DictionaryToken dictionary, PageTreeMembers pageTreeMembers, bool isLenientParsing) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } var type = dictionary.GetNameOrDefault(NameToken.Type); if (type != null && !type.Equals(NameToken.Page) && !isLenientParsing) { throw new InvalidOperationException($"Page {number} had its type was specified as {type} rather than 'Page'."); } MediaBox mediaBox = GetMediaBox(number, dictionary, pageTreeMembers, isLenientParsing); CropBox cropBox = GetCropBox(dictionary, pageTreeMembers, mediaBox); UserSpaceUnit userSpaceUnit = GetUserSpaceUnits(dictionary); LoadResources(dictionary, isLenientParsing); PageContent content = default(PageContent); if (!dictionary.TryGet(NameToken.Contents, out var contents)) { // ignored for now, is it possible? check the spec... } else if (contents is ArrayToken array) { var bytes = new List <byte>(); foreach (var item in array.Data) { var obj = item as IndirectReferenceToken; if (obj == null) { throw new PdfDocumentFormatException($"The contents contained something which was not an indirect reference: {item}."); } var contentStream = DirectObjectFinder.Get <StreamToken>(obj, pdfScanner); if (contentStream == null) { throw new InvalidOperationException($"Could not find the contents for object {obj}."); } bytes.AddRange(contentStream.Decode(filterProvider)); } content = GetContent(bytes, cropBox, userSpaceUnit, isLenientParsing); } else { var contentStream = DirectObjectFinder.Get <StreamToken>(contents, pdfScanner); if (contentStream == null) { throw new InvalidOperationException("Failed to parse the content for the page: " + number); } var bytes = contentStream.Decode(filterProvider); content = GetContent(bytes, cropBox, userSpaceUnit, isLenientParsing); } var page = new Page(number, mediaBox, cropBox, content); return(page); }
/// <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; }
/// <summary> /// Executes the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns>Blog post view model</returns> public SaveBlogPostCommandResponse Execute(BlogPostViewModel request) { if (request.DesirableStatus == ContentStatus.Published) { DemandAccess(RootModuleConstants.UserRoles.PublishContent); } var layout = LoadLayout(); var region = LoadRegion(); var isNew = request.Id.HasDefaultValue(); var userCanEdit = false; if (isNew || request.DesirableStatus != ContentStatus.Published) { DemandAccess(RootModuleConstants.UserRoles.EditContent); userCanEdit = true; } else { 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) { blogPost = Repository.First <BlogPost>(request.Id); content = Repository.FirstOrDefault <BlogPostContent>(c => c.PageContents.Any(x => x.Page == blogPost && x.Region == region && !x.IsDeleted)); if (content != null) { pageContent = Repository.FirstOrDefault <PageContent>(c => c.Page == blogPost && c.Region == region && !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 = blogService.CreateBlogPermalink(request.Title); } blogPost.MetaTitle = request.Title; blogPost.Layout = layout; UpdateStatus(blogPost, request.DesirableStatus); } else if (request.DesirableStatus == ContentStatus.Published) { 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.PageUrlLowerTrimmed = blogPost.PageUrl.LowerTrimmedUrl(); blogPost.UseCanonicalUrl = request.UseCanonicalUrl; Repository.Save(blogPost); Repository.Save(content); Repository.Save(pageContent); // Save tags if user has edit right. 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(new SaveBlogPostCommandResponse { Id = blogPost.Id, Version = blogPost.Version, Title = blogPost.Title, PageUrl = blogPost.PageUrl, ModifiedByUser = blogPost.ModifiedByUser, ModifiedOn = blogPost.ModifiedOn.ToFormattedDateString(), CreatedOn = blogPost.CreatedOn.ToFormattedDateString(), PageStatus = blogPost.Status, DesirableStatus = request.DesirableStatus, PageContentId = pageContent.Id }); }
/// <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; }
public PageItem(PageContent pageContent) { PageContent = pageContent; FixedPage = PageContent.GetPageRoot(false); PageBrush = new VisualBrush(FixedPage); }