/// <summary> /// Deletes the page and all of it's related regions. /// </summary> /// <returns></returns> public virtual bool DeleteAll() { // Since we can have multiple rows for all id's, get everything. List <Region> regions = Region.GetAllByPageId(Page.Id); List <Property> properties = Property.GetAllByParentId(Page.Id); List <Page> pages = Page.Get("page_id=@0", Page.Id); using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { regions.ForEach(r => r.Delete(tx)); properties.ForEach(p => p.Delete(tx)); pages.ForEach(p => p.Delete(tx)); Permalink.Delete(tx); // Change global last modified Web.ClientCache.SetSiteLastModified(tx); tx.Commit(); try { // Delete page preview // WebPages.WebThumb.RemovePagePreview(Page.Id) ; } catch {} } return(true); }
/// <summary> /// Saves the edit model. /// </summary> public bool SaveAll() { using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { try { if (Permalink.IsNew) { Permalink.Name = Permalink.Generate(Category.Name); } Permalink.Save(tx); Category.Save(tx); foreach (var ext in Extensions) { // Call OnSave ext.Body.OnManagerSave(Category); ext.ParentId = Category.Id; ext.Save(tx); } tx.Commit(); } catch { tx.Rollback(); throw; } } Refresh(); return(true); }
/// <summary> /// Deletes the specified content and its related file. /// </summary> public bool DeleteAll() { var content = Content.Get("content_id = @0", Content.Id); var permalinks = Permalink.Get("permalink_id = @0", Content.PermalinkId); using (IDbTransaction tx = Database.OpenTransaction()) { try { // Call OnDelete for all extensions foreach (var ext in Extensions) { ext.Body.OnManagerDelete(Content); } File.Delete(HttpContext.Current.Server.MapPath("~/App_Data/Content/" + Content.Id)); foreach (var c in content) { c.Delete(tx); } foreach (var p in permalinks) { p.Delete(tx); } tx.Commit(); return(true); } catch { tx.Rollback(); } } return(false); }
/// <summary> /// Deletes the page and all of it's related regions. /// </summary> /// <returns></returns> public virtual bool DeleteAll() { // Since we can have multiple rows for all id's, get everything. List <Region> regions = Region.GetAllByPageId(Page.Id); List <Property> properties = Property.GetAllByParentId(Page.Id); List <Page> pages = Page.Get("page_id=@0", Page.Id); using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { // Call OnDelete for all extensions Extensions.ForEach(e => e.Body.OnManagerDelete(Page)); // Call OnDelete for all regions Regions.ForEach(r => r.Body.OnManagerDelete(Page)); // Delete all entities regions.ForEach(r => r.Delete(tx)); properties.ForEach(p => p.Delete(tx)); pages.ForEach(p => p.Delete(tx)); Permalink.Delete(tx); // Change global last modified Web.ClientCache.SetSiteLastModified(tx); tx.Commit(); } return(true); }
/// <summary> /// Gets the related information /// </summary> private void GetRelated() { // Get Permalink Permalink = Permalink.GetSingle(Category.PermalinkId); if (Permalink == null) { Permalink = new Permalink() { Id = Guid.NewGuid(), Type = Models.Permalink.PermalinkType.CATEGORY, NamespaceId = new Guid("AE46C4C4-20F7-4582-888D-DFC148FE9067") }; Category.PermalinkId = Permalink.Id; } // Get categories List <Category> cats = Piranha.Models.Category.Get("category_id != @0", Category.Id, new Params() { OrderBy = "category_name ASC" }); cats.Insert(0, new Category()); Categories = new SelectList(cats, "Id", "Name"); // Get extensions Extensions = Category.GetExtensions(true); }
////TODO: Throw some kind of exception on failure. /// <summary> /// Save a post from Windows Live Writer to the database. /// </summary> /// <param name="blogid">The blog identifier string.</param> /// <param name="p">The post content and metadata</param> /// <param name="publish">Whether this is published or not. Currently /// this flag is not supported by the views.</param> /// <returns>The post id number.</returns> public string SavePost(string blogid, Post p, bool publish) { SeqPost sp = new SeqPost(); sp.BlogId = blogid; sp.Title = p.title; sp.Description = p.description; sp.ExtendedText = p.mt_text_more; sp.Excerpt = p.mt_excerpt; /* SQLServer can not deal with year < 1753, but dateCreated can be year 1 when WLW2011 post date is not set. For practical purposes we use 1970 as the minimum date. */ if (p.dateCreated.Year < 1970) sp.CreateDate = DateTime.Now.ToUniversalTime(); else sp.CreateDate = p.dateCreated; sp.ModifiedDate = DateTime.Now.ToUniversalTime(); sp.Published = publish; sp.Permalink = Permalink.Generate(sp.Title); UpdateCategories(p.categories.Length>0 ? p.categories[0] : "",sp); UpdateTags(p.mt_keywords, sp); db.SeqPosts.AddObject(sp); db.SaveChanges(); return sp.PostId.ToString(); }
/// <summary> /// Saves the model. /// </summary> /// <returns>Whether the operation succeeded or not</returns> public bool SaveAll() { // Ensure correct naming convention for properties for (var n = 0; n < Template.Properties.Count; n++) { Template.Properties[n] = Template.Properties[n].Replace(" ", "_").Trim(); } using (var tx = Database.OpenTransaction()) { // Permalink if (Permalink.IsNew && String.IsNullOrEmpty(Permalink.Name)) { Permalink.Name = Permalink.Generate(Template.Name); } Permalink.Save(tx); Template.Save(tx); // Clear all implementing posts from the cache var posts = Post.Get("post_template_id = @0", tx, Template.Id); foreach (var post in posts) { post.InvalidateRecord(post); } tx.Commit(); return(true); } }
public ActionResult Post(PostEditModel m) { ViewBag.Title = Piranha.Resources.Template.EditPostTitleNew; if (ModelState.IsValid) { try { if (m.SaveAll()) { ModelState.Clear(); ViewBag.Title = Piranha.Resources.Template.EditPostTitleExisting; SuccessMessage(Piranha.Resources.Template.MessagePostSaved); } else { ErrorMessage(Piranha.Resources.Template.MessagePostNotSaved); } } catch (DuplicatePermalinkException) { // Manually set the duplicate error. ModelState.AddModelError("Permalink", @Piranha.Resources.Global.PermalinkDuplicate); // If this is the default permalink, remove the model state so it will be shown. if (Permalink.Generate(m.Template.Name) == m.Permalink.Name) { ModelState.Remove("Permalink.Name"); } } catch (Exception e) { ErrorMessage(e.ToString()); } } return(View("PostEdit", m)); }
public PermalinkTest() { mPermalink = new Permalink(); mPermalink.SourceId = new Random().Next(); mPermalink.TargetId = new Random().Next(); mPermalink.SourceType = Guid.NewGuid().ToString(); mPermalink.TargetType = Guid.NewGuid().ToString(); }
/// <summary> /// Handles the current request. /// </summary> /// <param name="context">The current context</param> /// <param name="draft">Whether to get the draft or not</param> /// <param name="args">Optional url arguments passed to the handler</param> protected void HandleRequest(HttpContext context, bool draft, params string[] args) { if (args != null && args.Length > 0) { Content content = null; int? width = null; int? height = null; try { // Get content by id content = Content.GetSingle(new Guid(args[0]), draft); if (content != null) { if (args.Length > 1) { try { width = Convert.ToInt32(args[1]); } catch {} } if (args.Length > 2) { try { height = Convert.ToInt32(args[2]); } catch {} } } } catch { // Get content by permalink var perm = Permalink.GetByName(Config.MediaNamespaceId, GetPermalink(args[0], ref width, ref height)); if (perm != null) { content = Content.GetByPermalinkId(perm.Id); } } // Since we don't handle viewing image drafts right now, don't execute the overhead // if (content.IsDraft && !Extend.ExtensionManager.Current.MediaProvider.ExistsDraft(content.Id)) // content.IsDraft = false ; if (content != null) { if (height.HasValue) { content.GetMedia(context, width, height); } content.GetMedia(context, width); } else { context.Response.StatusCode = 404; } } else { context.Response.StatusCode = 500; } }
/// <summary> /// Handles requests to the given page. /// </summary> /// <param name="context">The current http context</param> /// <param name="permalink">The permalink</param> /// <param name="page">The page</param> /// <param name="args">Optional route arguments</param> public void HandlePage(HttpContext context, Permalink permalink, Page page, params string[] args) { if (!String.IsNullOrEmpty(page.Controller)) { context.RewritePath("~/" + page.Controller + "/" + args.Implode("/") + "?permalink=" + permalink.Name + (page.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false); } else { context.RewritePath("~/page/" + args.Implode("/") + "?permalink=" + permalink.Name + (page.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false); } }
public Permalink GetPermalink(ISession session) { Permalink permalink = (Id != 0) ? (Permalink)session.Load(typeof(Permalink), Id) : new Permalink(); permalink.SourceId = SourceId; permalink.TargetId = TargetId; permalink.SourceType = SourceType; permalink.TargetType = TargetType; return(permalink); }
/// <summary> /// Gets the model for the template specified by the given id. /// </summary> /// <param name="id">The template id</param> /// <returns>The model</returns> public static PostEditModel GetById(Guid id) { PostEditModel m = new PostEditModel(); m.Template = PostTemplate.GetSingle(id); if (m.Template.Properties == null) m.Template.Properties = new List<string>(); if (m.Template.PermalinkId != Guid.Empty) m.Permalink = Permalink.GetSingle(m.Template.PermalinkId); else m.Template.PermalinkId = m.Permalink.Id; return m; }
private async Task <PermalinkViewModel> BuildViewModel(Permalink permalink) { var subject = await _subjectRepository.Get(permalink.Query.SubjectId); var isValid = subject != null && await _subjectRepository.IsSubjectForLatestPublishedRelease(subject.Id); var viewModel = _mapper.Map <PermalinkViewModel>(permalink); viewModel.Invalidated = !isValid; return(viewModel); }
public async Task <Either <ActionResult, PermalinkViewModel> > CreateAsync(Guid releaseId, CreatePermalinkRequest request) { return(await _tableBuilderService.Query(releaseId, request.Query).OnSuccess(async result => { var permalink = new Permalink(request.Configuration, result, request.Query); await _blobStorageService.UploadText(containerName: PublicPermalinkContainerName, path: permalink.Id.ToString(), content: JsonConvert.SerializeObject(permalink), contentType: MediaTypeNames.Application.Json); return await BuildViewModel(permalink); })); }
/// <summary> /// Handles requests to the given post. /// </summary> /// <param name="context">The current http context</param> /// <param name="permalink">The permalink</param> /// <param name="post">The post</param> /// <param name="args">Optional route arguments</param> public void HandlePost(HttpContext context, Permalink permalink, Post post, params string[] args) { if (!String.IsNullOrEmpty(post.Controller)) { context.RewritePath("~/" + post.Controller + args.Implode("/") + "?permalink=" + permalink.Name + (post.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false); } else { context.RewritePath("~/post/" + args.Implode("/") + "?permalink=" + permalink.Name + (post.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false); } }
/// <summary> /// Handles requests to the given page. /// </summary> /// <param name="context">The current http context</param> /// <param name="permalink">The permalink</param> /// <param name="page">The page</param> /// <param name="args">Optional route arguments</param> public void HandlePage(HttpContext context, Permalink permalink, Page page, params string[] args) { if (!String.IsNullOrEmpty(page.Controller)) { context.RewritePath("~/templates/" + page.Controller + "/" + args.Implode("/") + "?permalink=" + permalink.Name + (page.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false); } else { context.RewritePath("~/page/" + args.Implode("/") + "?permalink=" + permalink.Name + (page.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false); } }
/// <summary> /// Default constructor. Creates a new model. /// </summary> public EditModel() { Category = new Category() { Id = Guid.NewGuid() } ; Permalink = new Permalink() { ParentId = Category.Id, Type = Models.Permalink.PermalinkType.CATEGORY } ; List<Category> cats = Piranha.Models.Category.Get(new Params() { OrderBy = "category_name ASC" }) ; cats.Insert(0, new Category()) ; Categories = new SelectList(cats, "Id", "Name") ; }
public async Task <Either <ActionResult, PermalinkViewModel> > Create(Guid releaseId, PermalinkCreateViewModel request) { return(await _tableBuilderService.Query(releaseId, request.Query).OnSuccess(async result => { var permalinkTableResult = new PermalinkTableBuilderResult(result); var permalink = new Permalink(request.Configuration, permalinkTableResult, request.Query); await _blobStorageService.UploadAsJson(containerName: Permalinks, path: permalink.Id.ToString(), content: permalink, settings: BuildJsonSerializerSettings()); return await BuildViewModel(permalink); })); }
/// <summary> /// Deletes the post. /// </summary> /// <returns></returns> public virtual bool DeleteAll() { using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { List <Relation> rel = Relation.Get("relation_data_id = @0", Post.Id); List <Post> posts = Post.Get("post_id = @0", Post.Id); rel.ForEach(r => r.Delete(tx)); posts.ForEach(p => p.Delete(tx)); Permalink.Delete(tx); tx.Commit(); } return(true); }
private async Task <PermalinkViewModel> BuildViewModel(Permalink permalink) { var subject = await _subjectService.Get(permalink.Query.SubjectId); var isValid = subject != null && await _subjectService.IsSubjectForLatestPublishedRelease(subject.Id); var publication = await _subjectService.FindPublicationForSubject(permalink.Query.SubjectId); var viewModel = _mapper.Map <PermalinkViewModel>(permalink); viewModel.Query.PublicationId = publication?.Id; viewModel.Invalidated = !isValid; return(viewModel); }
/// <summary> /// Return the site structure as an ul/li list with the current page selected. /// </summary> /// <param name="StartLevel">The start level of the menu</param> /// <param name="StopLevel">The stop level of the menu</param> /// <param name="Levels">The number of levels. Use this if you don't know the start level</param> /// <returns>A html string</returns> public IHtmlString Menu(int StartLevel = 1, int StopLevel = Int32.MaxValue, int Levels = 0, string RootNode = "", string CssClass = "menu", bool RenderParent = false) { StringBuilder str = new StringBuilder(); List <Sitemap> sm = null; Page Current = CurrentPage; if (Current != null || StartLevel == 1) { if (Current == null) { Current = new Page(); } if (RootNode != "") { Permalink pr = Models.Permalink.GetSingle("permalink_name = @0 AND permalink_namespace_id = @1", RootNode, WebPiranha.CurrentSite.NamespaceId); if (pr != null) { Page p = Page.GetByPermalinkId(pr.Id); Sitemap page = Sitemap.GetStructure(true).GetRootNode(p.Id); if (page != null) { sm = new List <Sitemap>(); if (RenderParent) { sm.Add(Mapper.Map <Sitemap, Sitemap>(page)); } sm.AddRange(page.Pages); } } } else { sm = GetStartLevel(Sitemap.GetStructure(true), Current.Id, StartLevel, RenderParent); } if (sm != null) { if (StopLevel == Int32.MaxValue && Levels > 0 && sm.Count > 0) { StopLevel = sm[0].Level + Math.Max(0, Levels - 1); } RenderUL(Current, sm, str, StopLevel, CssClass); } } return(new HtmlString(str.ToString())); }
/// <summary> /// Saves the model. /// </summary> /// <returns>Whether the operation succeeded or not</returns> public bool SaveAll() { using (var tx = Database.OpenTransaction()) { // Permalink if (Permalink.IsNew && String.IsNullOrEmpty(Permalink.Name)) { Permalink.Name = Permalink.Generate(Template.Name); } Permalink.Save(tx); Template.Save(tx); tx.Commit(); return(true); } }
public async Task Get_SubjectIsNotFromLatestPublishedRelease() { var subject = new Subject { Id = Guid.NewGuid() }; var permalink = new Permalink( new TableBuilderConfiguration(), new PermalinkTableBuilderResult { SubjectMeta = new PermalinkResultSubjectMeta() }, new ObservationQueryContext { SubjectId = subject.Id }); var blobStorageService = new Mock <IBlobStorageService>(MockBehavior.Strict); var subjectRepository = new Mock <ISubjectRepository>(MockBehavior.Strict); blobStorageService.SetupDownloadBlobText( container: Permalinks, path: permalink.Id.ToString(), blobText: JsonConvert.SerializeObject(permalink)); subjectRepository .Setup(s => s.Get(subject.Id)) .ReturnsAsync(subject); subjectRepository .Setup(s => s.IsSubjectForLatestPublishedRelease(subject.Id)) .ReturnsAsync(false); var service = BuildService(blobStorageService: blobStorageService.Object, subjectRepository: subjectRepository.Object); var result = (await service.Get(permalink.Id)).AssertRight(); MockUtils.VerifyAllMocks( blobStorageService, subjectRepository); Assert.Equal(permalink.Id, result.Id); // Expect invalidated Permalink Assert.True(result.Invalidated); }
/// <summary> /// Saves the edit model. /// </summary> public bool SaveAll() { using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { try { if (Permalink.IsNew) { Permalink.Name = Permalink.Generate(Category.Name); } Permalink.Save(tx); Category.Save(tx); tx.Commit(); } catch { tx.Rollback(); throw; } } Refresh(); return(true); }
/// <summary> /// Gets the model for the post /// </summary> /// <param name="id"></param> /// <returns></returns> public static EditModel GetById(Guid id, bool draft = true) { EditModel m = new EditModel(); m.Post = Piranha.Models.Post.GetSingle(id, draft); m.Template = PostTemplate.GetSingle(m.Post.TemplateId); m.Permalink = Permalink.GetSingle(m.Post.PermalinkId); Category.GetByPostId(m.Post.Id, draft).ForEach(c => m.PostCategories.Add(c.Id)); m.Categories = new MultiSelectList(Category.GetFields("category_id, category_name", new Params() { OrderBy = "category_name" }), "Id", "Name", m.PostCategories); m.GetRelated(); return(m); }
public ActionResult Create(PageCreateOrEditViewModel vmObj) { return(CreateUsingViewModel(vmObj, (parent) => { var permalinkName = ValidatePermalinkName(vmObj.PermalinkName, ""); if (string.IsNullOrEmpty(permalinkName)) { return null; } else { var permalink = new Permalink() { Name = permalinkName, Type = null, ChangeEvent = CreateChangeEvent() }; db.Permalinks.Add(permalink); //Convert the ViewModel to DB Object (Model) var dbObj = new Page() { Id = vmObj.Id, Name = vmObj.Name, Title = vmObj.Title, Description = vmObj.Description, Keywords = vmObj.Keywords, Tags = vmObj.Tags, //Content = vmObj.Content.ToList(), Parent = vmObj.Parent, //Pages = vmObj.Pages.ToList(), PermalinkId = vmObj.PermalinkId, Permalink = permalink, TemplateName = vmObj.TemplateName, IncludeInMenu = vmObj.IncludeInMenu, IsDraft = vmObj.IsDraft, IsPublished = vmObj.IsPublished, ActiveFrom = vmObj.ActiveFrom, ActiveTo = vmObj.ActiveTo, IsRssFeed = vmObj.IsRssFeed, ChangeEventId = vmObj.ChangeEventId, ChangeEvent = vmObj.ChangeEvent }; return dbObj; } }, null, "CreateOrEdit")); }
/// <summary> /// Represents a single episode parsed from a stream. /// </summary> /// <param name="baseItem"></param> internal EpisodeModel(SyndicationItem baseItem, int epIndex, string showTitle) { Title = baseItem.Title.Text.CleanFileName(); Description = baseItem.Summary.Text.CleanMarkup(); PubDate = baseItem.PublishDate; foreach (var link in baseItem.Links) { var uri = link.GetAbsoluteUri(); // Check if we have an actual audio file. If not... store it. if (link.RelationshipType == "enclosure") { Permalink = link.Uri.ToString(); Extension = Path.GetExtension(Permalink).Substring(0, 4); if (string.IsNullOrWhiteSpace(Extension)) { Extension = ParseOutExtension(Permalink.ToLowerInvariant()); } FileName = $"{showTitle} {epIndex} - {Title}{Extension}"; } else { DisplayLink = uri.AbsoluteUri; } } foreach (var extension in baseItem.ElementExtensions) { var ele = extension.GetObject <XElement>(); switch (extension.OuterName) { case "keywords": KeywordString = ele.Value; break; case "explicit": IsExplicit = ele.Value.ToLowerInvariant() == "yes"; break; case "image": ImageLink = ele.Value; break; } } }
public ActionResult Edit(bool draft, EditModel pm) { if (ModelState.IsValid) { try { if (pm.SaveAll(draft)) { ModelState.Clear(); if (!draft) { SuccessMessage(Piranha.Resources.Page.MessagePublished); } else { SuccessMessage(Piranha.Resources.Page.MessageSaved); } } else { ErrorMessage(Piranha.Resources.Page.MessageNotSaved); } } catch (DuplicatePermalinkException e) { // Manually set the duplicate error. ModelState.AddModelError("Permalink", @Piranha.Resources.Global.PermalinkDuplicate); // If this is the default permalink, remove the model state so it will be shown. if (Permalink.Generate(pm.Page.Title) == pm.Permalink.Name) { ModelState.Remove("Permalink.Name"); } } catch (Exception e) { ErrorMessage(e.ToString()); } } pm.Refresh(); if (pm.Page.IsNew) { ViewBag.Title = Piranha.Resources.Page.EditTitleNew + pm.Template.Name.ToLower(); } else { ViewBag.Title = Piranha.Resources.Page.EditTitleExisting; } return(View("Edit", pm)); }
/// <summary> /// Default constructor. Creates a new model. /// </summary> public PostEditModel() { Permalink = new Permalink() { Id = Guid.NewGuid(), Type = Permalink.PermalinkType.ARCHIVE, NamespaceId = Config.ArchiveNamespaceId } ; Template = new PostTemplate() { PermalinkId = Permalink.Id, Preview = new HtmlString( "<table class=\"template\">\n" + " <tr>\n" + " <td></td>\n" + " </tr>\n" + "</table>" ) } ; HandlerPrefix = Application.Current.Handlers.Where(h => h.Id == "ARCHIVE").SingleOrDefault().UrlPrefix ; }
/// <summary> /// Default constructor. Creates a new model. /// </summary> public PostEditModel() { Permalink = new Permalink() { Id = Guid.NewGuid(), Type = Permalink.PermalinkType.ARCHIVE, NamespaceId = Config.ArchiveNamespaceId }; Template = new PostTemplate() { PermalinkId = Permalink.Id, Preview = new HtmlString( "<table class=\"template\">\n" + " <tr>\n" + " <td></td>\n" + " </tr>\n" + "</table>" ) }; HandlerPrefix = Application.Current.Handlers.Where(h => h.Id == "ARCHIVE").SingleOrDefault().UrlPrefix; }
/// <summary> /// Deletes the model and all related data. /// </summary> public bool DeleteAll() { using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { try { // Delete all relations to the current category List <Relation> pc = Relation.GetByTypeAndRelatedId(Relation.RelationType.POSTCATEGORY, Category.Id); pc.ForEach((r) => r.Delete(tx)); // Delete category Category.Delete(tx); // Delete permalink Permalink.Delete(tx); tx.Commit(); } catch { tx.Rollback(); return(false); } } return(true); }
/// <summary> /// Deletes the post. /// </summary> /// <returns></returns> public virtual bool DeleteAll() { using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) { List <Relation> rel = Relation.Get("relation_data_id = @0", Post.Id); List <Post> posts = Post.Get("post_id = @0", Post.Id); // Call OnDelete for all extensions Extensions.ForEach(e => e.Body.OnManagerDelete(Post)); // Delete all entities rel.ForEach(r => r.Delete(tx)); posts.ForEach(p => p.Delete(tx)); Permalink.Delete(tx); tx.Commit(); } return(true); }
private void GetRelated() { // Clear related Regions.Clear(); Properties.Clear(); AttachedContent.Clear(); // Get group parents DisableGroups = SysGroup.GetParents(Page.GroupId); DisableGroups.Reverse(); // Get template & permalink Template = PageTemplate.GetSingle("pagetemplate_id = @0", Page.TemplateId); Permalink = Permalink.GetSingle(Page.PermalinkId); if (Permalink == null) { // Get the site tree using (var db = new DataContext()) { var sitetree = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single(); Permalink = new Permalink() { Id = Guid.NewGuid(), Type = Permalink.PermalinkType.PAGE, NamespaceId = sitetree.NamespaceId }; Page.PermalinkId = Permalink.Id; } } // Get placement ref title if (!IsSite) { if (Page.ParentId != Guid.Empty || Page.Seqno > 1) { Page refpage = null; if (Page.Seqno > 1) { if (Page.ParentId != Guid.Empty) refpage = Page.GetSingle("page_parent_id = @0 AND page_seqno = @1", Page.ParentId, Page.Seqno - 1); else refpage = Page.GetSingle("page_parent_id IS NULL AND page_seqno = @0 AND page_sitetree_id = @1", Page.Seqno - 1, Page.SiteTreeId); //ÖS 2015-03-18 added siteid to the query } else { refpage = Page.GetSingle(Page.ParentId, true); } PlaceRef = refpage.Title; } } if (Template != null) { // Only load regions & properties if this is an original if (Page.OriginalId == Guid.Empty) { // Get regions var regions = RegionTemplate.Get("regiontemplate_template_id = @0", Template.Id, new Params() { OrderBy = "regiontemplate_seqno" }); foreach (var rt in regions) { var reg = Region.GetSingle("region_regiontemplate_id = @0 AND region_page_id = @1 and region_draft = @2", rt.Id, Page.Id, Page.IsDraft); if (reg != null) Regions.Add(reg); else Regions.Add(new Region() { InternalId = rt.InternalId, Name = rt.Name, Type = rt.Type, PageId = Page.Id, RegiontemplateId = rt.Id, IsDraft = Page.IsDraft, IsPageDraft = Page.IsDraft }); } // Get Properties foreach (string name in Template.Properties) { Property prp = Property.GetSingle("property_name = @0 AND property_parent_id = @1 AND property_draft = @2", name, Page.Id, Page.IsDraft); if (prp != null) Properties.Add(prp); else Properties.Add(new Property() { Name = name, ParentId = Page.Id, IsDraft = Page.IsDraft }); } } } else throw new ArgumentException("Could not find page template for page {" + Page.Id.ToString() + "}"); // Only load attachments if this is an original if (Page.OriginalId == Guid.Empty) { // Get attached content if (Page.Attachments.Count > 0) { // Content meta data is actually memcached, so this won't result in multiple queries Page.Attachments.ForEach(a => { Models.Content c = Models.Content.GetSingle(a, true); if (c != null) AttachedContent.Add(c); }); } } // Get page position Parents = BuildParentPages(Sitemap.GetStructure(Page.SiteTreeInternalId, false), Page); Parents.Insert(0, new PagePlacement() { Level = 1, IsSelected = Page.ParentId == Guid.Empty }); Siblings = BuildSiblingPages(Page.Id, Page.ParentId, Page.Seqno, Page.ParentId, Page.SiteTreeInternalId); // Only load extensions if this is an original if (Page.OriginalId == Guid.Empty) { // Get extensions Extensions = Page.GetExtensions(true); } // Initialize regions foreach (var reg in Regions) reg.Body.InitManager(this); // Get whether comments should be enabled EnableComments = Areas.Manager.Models.CommentSettingsModel.Get().EnablePages; if (!Page.IsNew && EnableComments) { using (var db = new DataContext()) { Comments = db.Comments. Include("CreatedBy"). Where(c => c.ParentId == Page.Id && c.ParentIsDraft == false). OrderByDescending(c => c.Created).ToList(); } } // Get the site if this is a site page if (Permalink.Type == Models.Permalink.PermalinkType.SITE) { using (var db = new DataContext()) { SiteTree = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single(); } } // Check if the page can be published if (Page.OriginalId != Guid.Empty) { CanPublish = Page.GetScalar("SELECT count(*) FROM page WHERE page_id=@0 AND page_draft=0", Page.OriginalId) > 0; } }
/// <summary> /// Gets the related information /// </summary> private void GetRelated() { // Get Permalink Permalink = Permalink.GetSingle(Category.PermalinkId) ; if (Permalink == null) { Permalink = new Permalink() { Id = Guid.NewGuid(), Type = Models.Permalink.PermalinkType.CATEGORY, NamespaceId = new Guid("AE46C4C4-20F7-4582-888D-DFC148FE9067") } ; Category.PermalinkId = Permalink.Id ; } // Get categories List<Category> cats = Piranha.Models.Category.Get("category_id != @0", Category.Id, new Params() { OrderBy = "category_name ASC" }) ; cats.Insert(0, new Category()) ; Categories = new SelectList(cats, "Id", "Name") ; }
/// <summary> /// Saves the current edit model. /// </summary> /// <returns>Whether the entity was updated or not</returns> public bool Save() { using (var db = new DataContext()) { InternalId = (!String.IsNullOrEmpty(InternalId) ? InternalId.Replace(" ", "") : Name.Replace(" ", "")).ToUpper() ; var site = db.SiteTrees.Where(s => s.Id == Id).SingleOrDefault() ; if (site == null) { // Create new dedicated namespace var name = new Namespace() { Id = Guid.NewGuid(), Name = "Site namespace", InternalId = InternalId, Description = "Namespace for the site " + InternalId, } ; db.Namespaces.Add(name) ; // Create site site = new SiteTree() ; site.Id = Id ; site.NamespaceId = NamespaceId = name.Id ; db.SiteTrees.Add(site) ; } // If we've changed namespace, update all related permalinks. if (site.NamespaceId != NamespaceId) ChangeNamespace(db, Id, NamespaceId) ; // Update the site tree site.NamespaceId = NamespaceId ; site.InternalId = InternalId ; site.Name = Name ; site.HostNames = HostNames ; site.Description = Description ; // Update the site template var template = db.PageTemplates.Include(pt => pt.RegionTemplates).Where(pt => pt.Id == Id && pt.IsSiteTemplate).SingleOrDefault() ; if (template == null) { template = new PageTemplate() ; db.PageTemplates.Add(template) ; template.Id = Id ; template.Name = Id.ToString() ; template.IsSiteTemplate = true ; } template.Preview = Template.Preview ; template.Properties = Template.Properties ; // Update the regions var currentRegions = new List<Guid>() ; foreach (var reg in Regions) { var region = template.RegionTemplates.Where(r => r.Id == reg.Id).SingleOrDefault() ; if (region == null) { region = new RegionTemplate() ; db.RegionTemplates.Add(region) ; template.RegionTemplates.Add(region) ; region.Id = Guid.NewGuid() ; region.TemplateId = template.Id ; region.Type = reg.Type ; } region.Name = reg.Name ; region.InternalId = reg.InternalId ; region.Seqno = reg.Seqno ; region.Description = reg.Description ; currentRegions.Add(region.Id) ; } // Delete removed regions foreach (var reg in template.RegionTemplates.Where(r => !currentRegions.Contains(r.Id)).ToList()) { db.RegionTemplates.Remove(reg) ; } // Check that we have a site page, if not, create it var page = db.Pages.Where(p => p.SiteTreeId == site.Id && p.TemplateId == site.Id).SingleOrDefault() ; if (page == null) { // Create page page = new Page() { Id = Guid.NewGuid(), SiteTreeId = site.Id, TemplateId = site.Id, ParentId = site.Id, Title = site.Id.ToString(), PermalinkId = Guid.NewGuid() } ; // Create published version var published = page.Clone() ; published.IsDraft = false ; // Create permalink var permalink = new Permalink() { Id = page.PermalinkId, NamespaceId = site.NamespaceId, Name = site.Id.ToString(), Type = "SITE" } ; // Attach to context page.Attach(db, EntityState.Added) ; published.Attach(db, EntityState.Added) ; permalink.Attach(db, EntityState.Added) ; } var ret = db.SaveChanges() > 0 ; Id = site.Id ; // Refresh host name configuration if (ret) WebPages.WebPiranha.RegisterDefaultHostNames() ; return ret ; } }
private void GetRelated() { // Clear related PageRegions.Clear() ; Properties.Clear() ; AttachedContent.Clear() ; // Get placement ref title if (Page.ParentId != Guid.Empty || Page.Seqno > 1) { Page refpage = null ; if (Page.Seqno > 1) { if (Page.ParentId != Guid.Empty) refpage = Page.GetSingle("page_parent_id = @0 AND page_seqno = @1", Page.ParentId, Page.Seqno - 1) ; else refpage = Page.GetSingle("page_parent_id IS NULL AND page_seqno = @0", Page.Seqno - 1) ; } else { refpage = Page.GetSingle(Page.ParentId, true) ; } PlaceRef = refpage.Title ; } // Get template & permalink Template = PageTemplate.GetSingle("pagetemplate_id = @0", Page.TemplateId) ; Permalink = Permalink.GetSingle(Page.PermalinkId) ; if (Permalink == null) { Permalink = new Permalink() { Id = Guid.NewGuid(), Type = Permalink.PermalinkType.PAGE, NamespaceId = new Guid("8FF4A4B4-9B6C-4176-AAA2-DB031D75AC03") } ; Page.PermalinkId = Permalink.Id ; } if (Template != null) { // Get page regions foreach (string name in Template.PageRegions) { Region reg = Region.GetSingle("region_name = @0 AND region_page_id = @1 AND region_draft = @2", name, Page.Id, Page.IsDraft) ; if (reg != null) PageRegions.Add(reg) ; else PageRegions.Add(new Region() { Name = name, PageId = Page.Id, IsDraft = Page.IsDraft, IsPageDraft = Page.IsDraft }) ; } // Get Properties foreach (string name in Template.Properties) { Property prp = Property.GetSingle("property_name = @0 AND property_parent_id = @1 AND property_draft = @2", name, Page.Id, Page.IsDraft) ; if (prp != null) Properties.Add(prp) ; else Properties.Add(new Property() { Name = name, ParentId = Page.Id, IsDraft = Page.IsDraft }) ; } } else throw new ArgumentException("Could not find page template for page {" + Page.Id.ToString() + "}") ; // Get attached content if (Page.Attachments.Count > 0) { // Content meta data is actually memcached, so this won't result in multiple queries Page.Attachments.ForEach(a => { Models.Content c = Models.Content.GetSingle(a) ; if (c != null) AttachedContent.Add(c) ; }) ; } // Get page position Parents = BuildParentPages(Sitemap.GetStructure(false), Page) ; Parents.Insert(0, new PagePlacement() { Level = 1, IsSelected = Page.ParentId == Guid.Empty }) ; Siblings = BuildSiblingPages(Page.Id, Page.ParentId, Page.Seqno, Page.ParentId) ; }