/// <summary> /// Copies the page. /// </summary> /// <param name="pageId">The page identifier.</param> /// <param name="currentPersonAliasId">The current person alias identifier.</param> public Guid? CopyPage( int pageId, int? currentPersonAliasId = null ) { var rockContext = new RockContext(); var pageService = new PageService( rockContext ); Guid? newPageGuid = null; var page = pageService.Get( pageId ); if ( page != null ) { Dictionary<Guid, Guid> pageGuidDictionary = new Dictionary<Guid, Guid>(); Dictionary<Guid, Guid> blockGuidDictionary = new Dictionary<Guid, Guid>(); var newPage = GeneratePageCopy( page, pageGuidDictionary, blockGuidDictionary, currentPersonAliasId ); pageService.Add( newPage ); rockContext.SaveChanges(); if ( newPage.ParentPageId.HasValue ) { PageCache.Flush( newPage.ParentPageId.Value ); } newPageGuid= newPage.Guid; GenerateBlockAttributeValues( pageGuidDictionary, blockGuidDictionary, rockContext, currentPersonAliasId ); GeneratePageBlockAuths( pageGuidDictionary, blockGuidDictionary, rockContext, currentPersonAliasId ); CloneHtmlContent( blockGuidDictionary, rockContext, currentPersonAliasId ); } return newPageGuid; }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); List<int> expandedPageIds = new List<int>(); PageService pageService = new PageService( new RockContext() ); if ( Page.IsPostBack ) { foreach ( string expandedId in hfExpandedIds.Value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) ) { int id = 0; if ( expandedId.StartsWith( "p" ) && expandedId.Length > 1 ) { if ( int.TryParse( expandedId.Substring( 1 ), out id ) ) { expandedPageIds.Add( id ); } } } } else { string pageSearch = this.PageParameter( "pageSearch" ); if ( !string.IsNullOrWhiteSpace( pageSearch ) ) { foreach ( Page page in pageService.Queryable().Where( a => a.InternalName.IndexOf( pageSearch ) >= 0 ) ) { Page selectedPage = page; while ( selectedPage != null ) { selectedPage = selectedPage.ParentPage; if ( selectedPage != null ) { expandedPageIds.Add( selectedPage.Id ); } } } } } var sb = new StringBuilder(); sb.AppendLine( "<ul id=\"treeview\">" ); var allPages = pageService.Queryable( "Pages, Blocks, Blocks.BlockType" ).ToList(); foreach ( var page in allPages.Where( a => a.ParentPageId == null ).OrderBy( a => a.Order ).ThenBy( a => a.InternalName ) ) { sb.Append( PageNode( page, expandedPageIds ) ); } sb.AppendLine( "</ul>" ); lPages.Text = sb.ToString(); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( System.Web.UI.Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; if ( !string.IsNullOrWhiteSpace( value ) ) { var service = new PageService(); var page = service.Get( new Guid( value ) ); if ( page != null ) { formattedValue = page.InternalName; } } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); PageService pageService = new PageService(); var sb = new StringBuilder(); sb.AppendLine( "<ul id=\"treeview\">" ); var allPages = pageService.Queryable( "Pages, Blocks, Blocks.BlockType" ).ToList(); foreach ( var page in allPages.Where( a => a.ParentPageId == null ).OrderBy( a => a.Order ).ThenBy( a => a.InternalName ) ) { sb.Append( PageNode( page ) ); } sb.AppendLine( "</ul>" ); lPages.Text = sb.ToString(); }
private void BindGrid() { string type = PageParameter( "SearchType" ); string term = PageParameter( "SearchTerm" ); if ( !string.IsNullOrWhiteSpace( type ) && !string.IsNullOrWhiteSpace( term ) ) { term = term.Trim(); type = type.Trim().ToLower(); var terms = term.Split( ' ' ); var pageService = new PageService( new RockContext() ); var pages = new List<Page>(); switch ( type ) { case ( "name" ): { pages = pageService.Queryable().ToList().Where( p => Regex.IsMatch( p.PageTitle, String.Join("\\w* ", terms.Select(t => Regex.Escape(t))), RegexOptions.IgnoreCase ) ).ToList(); break; } } if ( pages.Count == 1 ) { NavigateToPage( pages[0].Guid, null ); Context.ApplicationInstance.CompleteRequest(); } else { gPages.DataKeyNames = new string[] { "Guid" }; gPages.EntityTypeId = EntityTypeCache.GetId<Page>(); gPages.DataSource = pages.Select( p => new { p.Guid, p.PageTitle, Structure = ParentStructure( p ), Site = p.Layout.Site.Name } ).ToList(); gPages.DataBind(); } } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); PageService pageService = new PageService( new RockContext() ); List<int> expandedPageIds = new List<int>(); string pageSearch = this.PageParameter( "pageSearch" ); if ( !string.IsNullOrWhiteSpace( pageSearch ) ) { foreach ( Page page in pageService.Queryable().Where( a => a.InternalName.IndexOf( pageSearch ) >= 0 ) ) { Page selectedPage = page; while ( selectedPage != null ) { selectedPage = selectedPage.ParentPage; if (selectedPage != null) { expandedPageIds.Add( selectedPage.Id ); } } } } var sb = new StringBuilder(); sb.AppendLine( "<ul id=\"treeview\">" ); var allPages = pageService.Queryable( "Pages, Blocks, Blocks.BlockType" ).ToList(); foreach ( var page in allPages.Where( a => a.ParentPageId == null ).OrderBy( a => a.Order ).ThenBy( a => a.InternalName ) ) { sb.Append( PageNode( page, expandedPageIds ) ); } sb.AppendLine( "</ul>" ); lPages.Text = sb.ToString(); }
/// <summary> /// Handles the Click event of the btnSelect control. /// </summary> protected override void SetValueOnSelect() { var page = new PageService( new RockContext() ).Get( int.Parse( ItemId ) ); this.SetValue( page ); }
/// <summary> /// Loads the drop downs. /// </summary> private void LoadDropDowns() { PageService pageService = new PageService(); List<Rock.Model.Page> allPages = pageService.Queryable().ToList(); ddlDefaultPage.DataSource = allPages.OrderBy( a => a.PageSortHash ); ddlDefaultPage.DataBind(); ddlTheme.Items.Clear(); DirectoryInfo di = new DirectoryInfo( this.Page.Request.MapPath( this.CurrentTheme ) ); foreach ( var themeDir in di.Parent.EnumerateDirectories().OrderBy( a => a.Name ) ) { ddlTheme.Items.Add( new ListItem( themeDir.Name, themeDir.Name ) ); } }
/// <summary> /// Builds a dictionary containing the content of the provided <see cref="System.ServiceModel.Syndication.SyndicationItem"/> /// </summary> /// <param name="i">The <see cref="System.ServiceModel.Syndicawtion.SyndicationItem"/> to be converted to a dictionary.</param> /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page.</param> /// <returns>A <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the provided syndication item.</returns> private static Dictionary <string, object> BuildSyndicationItem(SyndicationItem i, string detailPage) { Dictionary <string, object> itemDictionary = new Dictionary <string, object>(); if (i != null) { itemDictionary.Add("AttributeExtensions", i.AttributeExtensions.ToDictionary(a => a.Key.ToString(), a => a.Value)); string detailPageUrl = string.Empty; if (!String.IsNullOrWhiteSpace(detailPage)) { Rock.Model.Page page = new Rock.Model.PageService().Get(new Guid(detailPage)); Dictionary <string, string> queryString = new Dictionary <string, string>(); queryString.Add("feedItemId", System.Web.HttpUtility.UrlEncode(i.Id)); detailPageUrl = new PageReference(page.Id, 0, queryString).BuildUrl(); } List <Dictionary <string, object> > authors = new List <Dictionary <string, object> >(); foreach (var a in i.Authors) { authors.Add(BuildSyndicationPerson(a)); } itemDictionary.Add("Authors", authors); itemDictionary.Add("BaseUri", i.BaseUri == null ? null : i.BaseUri.ToString()); List <Dictionary <string, object> > categories = new List <Dictionary <string, object> >(); foreach (var c in i.Categories) { categories.Add(BuildSyndicationCategory(c)); } itemDictionary.Add("Categories", categories); itemDictionary.Add("Content", i.Content == null ? null : System.Web.HttpUtility.HtmlDecode(((TextSyndicationContent)i.Content).Text)); List <Dictionary <string, object> > contributors = new List <Dictionary <string, object> >(); foreach (var c in i.Contributors) { contributors.Add(BuildSyndicationPerson(c)); } itemDictionary.Add("Contributors", contributors); itemDictionary.Add("Copyright", i.Copyright == null ? null : i.Copyright.Text); itemDictionary.Add("DetailPageUrl", detailPageUrl); itemDictionary.Add("ElementExtensions", i.ElementExtensions); itemDictionary.Add("Id", i.Id); itemDictionary.Add("LastUpdatedTime", i.LastUpdatedTime.ToLocalTime().DateTime); List <Dictionary <string, object> > link = new List <Dictionary <string, object> >(); foreach (var l in i.Links) { link.Add(BuildSyndicationLink(l)); } itemDictionary.Add("Links", link); itemDictionary.Add("PublishDate", i.PublishDate.ToLocalTime().DateTime); itemDictionary.Add("Summary", i.Summary == null ? null : i.Summary.Text); itemDictionary.Add("Title", i.Title == null ? null : i.Title.Text); } return(itemDictionary); }
/// <summary> /// Sets the value. /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="value">The value.</param> public override void SetEditValue( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues, string value ) { if ( value != null ) { PagePicker ppPage = control as PagePicker; if ( ppPage != null ) { string[] valuePair = value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ); Page page = null; PageRoute pageRoute = null; //// Value is in format "Page.Guid,PageRoute.Guid" //// If only the Page.Guid is specified this is just a reference to a page without a special route //// In case the PageRoute record can't be found from PageRoute.Guid (maybe the pageroute was deleted), fall back to the Page without a PageRoute if ( valuePair.Length == 2 ) { Guid pageRouteGuid; Guid.TryParse( valuePair[1], out pageRouteGuid ); pageRoute = new PageRouteService().Get( pageRouteGuid ); } if ( pageRoute != null ) { ppPage.SetValue( pageRoute ); } else { if ( valuePair.Length > 0 ) { Guid pageGuid; Guid.TryParse( valuePair[0], out pageGuid ); page = new PageService().Get( pageGuid ); } ppPage.SetValue( page ); } } } }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click( object sender, EventArgs e ) { if ( _updatePage ) { var pageCache = PageCache.Read( RockPage.PageId ); if ( pageCache != null && ( pageCache.PageTitle != tbName.Text || pageCache.Description != tbDesc.Text ) ) { var rockContext = new RockContext(); var service = new PageService( rockContext ); var page = service.Get( pageCache.Id ); page.InternalName = tbName.Text; page.PageTitle = tbName.Text; page.BrowserTitle = tbName.Text; page.Description = tbDesc.Text; rockContext.SaveChanges(); Rock.Web.Cache.PageCache.Flush( page.Id ); pageCache = PageCache.Read( RockPage.PageId ); var breadCrumb = RockPage.BreadCrumbs.Where( c => c.Url == RockPage.PageReference.BuildUrl() ).FirstOrDefault(); if ( breadCrumb != null ) { breadCrumb.Name = pageCache.BreadCrumbText; } } } SetAttributeValue( "Query", ceQuery.Text ); SetAttributeValue( "Timeout", nbTimeout.Text ); SetAttributeValue( "StoredProcedure", cbStoredProcedure.Checked.ToString() ); SetAttributeValue( "QueryParams", tbParams.Text ); SetAttributeValue( "UrlMask", tbUrlMask.Text ); SetAttributeValue( "Columns", tbColumns.Text ); SetAttributeValue( "ShowColumns", ddlHideShow.SelectedValue ); SetAttributeValue( "FormattedOutput", ceFormattedOutput.Text ); SetAttributeValue( "PageTitleLava", cePageTitleLava.Text ); SetAttributeValue( "PersonReport", cbPersonReport.Checked.ToString() ); SetAttributeValue( "ShowCommunicate", ( cbPersonReport.Checked && cbShowCommunicate.Checked ).ToString() ); SetAttributeValue( "ShowMergePerson", ( cbPersonReport.Checked && cbShowMergePerson.Checked ).ToString() ); SetAttributeValue( "ShowBulkUpdate", ( cbPersonReport.Checked && cbShowBulkUpdate.Checked ).ToString() ); SetAttributeValue( "ShowExcelExport", cbShowExcelExport.Checked.ToString() ); SetAttributeValue( "ShowMergeTemplate", cbShowMergeTemplate.Checked.ToString() ); SetAttributeValue( "ShowGridFilter", cbShowGridFilter.Checked.ToString() ); SetAttributeValue( "MergeFields", tbMergeFields.Text ); SaveAttributeValues(); mdEdit.Hide(); pnlEditModel.Visible = false; upnlContent.Update(); BuildControls( true ); }
/// <summary> /// Handles the OnSave event of the masterPage control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void masterPage_OnSave( object sender, EventArgs e ) { Page.Validate( BlockValidationGroup ); if ( Page.IsValid && _pageId.HasValue ) { var rockContext = new RockContext(); var pageService = new PageService( rockContext ); var routeService = new PageRouteService( rockContext ); var contextService = new PageContextService( rockContext ); var page = pageService.Get( _pageId.Value ); // validate/check for removed routes var editorRoutes = tbPageRoute.Text.SplitDelimitedValues().Distinct(); var databasePageRoutes = page.PageRoutes.ToList(); var deletedRouteIds = new List<int>(); var addedRoutes = new List<string>(); if ( editorRoutes.Any() ) { // validate for any duplicate routes var duplicateRoutes = routeService.Queryable() .Where( r => editorRoutes.Contains( r.Route ) && r.PageId != _pageId ) .Select( r => r.Route ) .Distinct() .ToList(); if ( duplicateRoutes.Any() ) { // Duplicate routes nbPageRouteWarning.Title = "Duplicate Route(s)"; nbPageRouteWarning.Text = string.Format( "<p>The page route <strong>{0}</strong>, already exists for another page. Please choose a different route name.</p>", duplicateRoutes.AsDelimited( "</strong> and <strong>" ) ); nbPageRouteWarning.Dismissable = true; nbPageRouteWarning.Visible = true; CurrentTab = "Advanced Settings"; rptProperties.DataSource = _tabs; rptProperties.DataBind(); ShowSelectedPane(); return; } } // validate if removed routes can be deleted foreach ( var pageRoute in databasePageRoutes ) { if ( !editorRoutes.Contains( pageRoute.Route ) ) { // make sure the route can be deleted string errorMessage; if ( !routeService.CanDelete( pageRoute, out errorMessage ) ) { nbPageRouteWarning.Text = string.Format( "The page route <strong>{0}</strong>, cannot be removed. {1}", pageRoute.Route, errorMessage ); nbPageRouteWarning.NotificationBoxType = NotificationBoxType.Warning; nbPageRouteWarning.Dismissable = true; nbPageRouteWarning.Visible = true; CurrentTab = "Advanced Settings"; rptProperties.DataSource = _tabs; rptProperties.DataBind(); ShowSelectedPane(); return; } } } // take care of deleted routes foreach ( var pageRoute in databasePageRoutes ) { if ( !editorRoutes.Contains( pageRoute.Route ) ) { // if they removed the Route, remove it from the database page.PageRoutes.Remove( pageRoute ); routeService.Delete( pageRoute ); deletedRouteIds.Add( pageRoute.Id ); } } // take care of added routes foreach ( string route in editorRoutes ) { // if they added the Route, add it to the database if ( !databasePageRoutes.Any( a => a.Route == route ) ) { var pageRoute = new PageRoute(); pageRoute.Route = route.TrimStart( new char[] { '/' } ); pageRoute.Guid = Guid.NewGuid(); page.PageRoutes.Add( pageRoute ); addedRoutes.Add( route ); } } int parentPageId = ppParentPage.SelectedValueAsInt() ?? 0; if ( page.ParentPageId != parentPageId ) { if ( page.ParentPageId.HasValue ) { PageCache.Flush( page.ParentPageId.Value ); } if ( parentPageId != 0 ) { PageCache.Flush( parentPageId ); } } page.InternalName = tbPageName.Text; page.PageTitle = tbPageTitle.Text; page.BrowserTitle = tbBrowserTitle.Text; if ( parentPageId != 0 ) { page.ParentPageId = parentPageId; } else { page.ParentPageId = null; } page.LayoutId = ddlLayout.SelectedValueAsInt().Value; int? orphanedIconFileId = null; page.IconCssClass = tbIconCssClass.Text; page.PageDisplayTitle = cbPageTitle.Checked; page.PageDisplayBreadCrumb = cbPageBreadCrumb.Checked; page.PageDisplayIcon = cbPageIcon.Checked; page.PageDisplayDescription = cbPageDescription.Checked; page.DisplayInNavWhen = ddlMenuWhen.SelectedValue.ConvertToEnumOrNull<DisplayInNavWhen>() ?? DisplayInNavWhen.WhenAllowed; page.MenuDisplayDescription = cbMenuDescription.Checked; page.MenuDisplayIcon = cbMenuIcon.Checked; page.MenuDisplayChildPages = cbMenuChildPages.Checked; page.BreadCrumbDisplayName = cbBreadCrumbName.Checked; page.BreadCrumbDisplayIcon = cbBreadCrumbIcon.Checked; page.RequiresEncryption = cbRequiresEncryption.Checked; page.EnableViewState = cbEnableViewState.Checked; page.IncludeAdminFooter = cbIncludeAdminFooter.Checked; page.OutputCacheDuration = tbCacheDuration.Text.AsIntegerOrNull() ?? 0; page.Description = tbDescription.Text; page.HeaderContent = ceHeaderContent.Text; // update PageContexts foreach ( var pageContext in page.PageContexts.ToList() ) { contextService.Delete( pageContext ); } page.PageContexts.Clear(); foreach ( var control in phContext.Controls ) { if ( control is RockTextBox ) { var tbContext = control as RockTextBox; if ( !string.IsNullOrWhiteSpace( tbContext.Text ) ) { var pageContext = new PageContext(); pageContext.Entity = tbContext.ID.Substring( 8 ).Replace( '_', '.' ); pageContext.IdParameter = tbContext.Text; page.PageContexts.Add( pageContext ); } } } // save page and it's routes if ( page.IsValid ) { rockContext.SaveChanges(); // remove any routes that were deleted foreach (var deletedRouteId in deletedRouteIds ) { var existingRoute = RouteTable.Routes.OfType<Route>().FirstOrDefault( a => a.RouteId() == deletedRouteId ); if ( existingRoute != null ) { RouteTable.Routes.Remove( existingRoute ); } } // ensure that there aren't any other extra routes for this page in the RouteTable foreach (var routeTableRoute in RouteTable.Routes.OfType<Route>().Where(a => a.PageId() == page.Id)) { if ( !editorRoutes.Any( a => a == routeTableRoute.Url ) ) { RouteTable.Routes.Remove( routeTableRoute ); } } // Add any routes that were added foreach ( var pageRoute in new PageRouteService( rockContext ).GetByPageId( page.Id ) ) { if ( addedRoutes.Contains( pageRoute.Route ) ) { RouteTable.Routes.AddPageRoute( pageRoute ); } } if ( orphanedIconFileId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedIconFileId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } Rock.Web.Cache.PageCache.Flush( page.Id ); string script = "if (typeof window.parent.Rock.controls.modal.close === 'function') window.parent.Rock.controls.modal.close('PAGE_UPDATED');"; ScriptManager.RegisterStartupScript( this.Page, this.GetType(), "close-modal", script, true ); } } }
/// <summary> /// Gets a <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the contents of the syndicated feed. /// </summary> /// <param name="feedUrl">A <see cref="System.String"/> representing the URL of the feed.</param> /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page. </param> /// <param name="cacheDuration">A <see cref="System.Int32"/> representing the length of time that the content of the RSS feed will be saved to cache.</param> /// <param name="message">A <see cref="System.Collections.Generic.Dictionary{string,object}"/> that will contain any error or alert messages that are returned.</param> /// <param name="isError">A <see cref="System.Boolean"/> that is <c>true</c> if an error has occurred, otherwise <c>false</c>.</param> /// <returns></returns> public static Dictionary <string, object> GetFeed(string feedUrl, string detailPage, int cacheDuration, ref Dictionary <string, string> message, ref bool isError) { Dictionary <string, object> feedDictionary = new Dictionary <string, object>(); if (message == null) { message = new Dictionary <string, string>(); } if (String.IsNullOrEmpty(feedUrl)) { message.Add("Feed URL not provided.", "The RSS Feed URL has not been provided. Please update the \"RSS Feed URL\" attribute in the block settings."); return(feedDictionary); } if (!System.Text.RegularExpressions.Regex.IsMatch(feedUrl, @"^(http://|https://|)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?")) { message.Add("Feed URL not valid.", "The Feed URL is not formatted properly. Please verify the \"RSS Feed URL\" attribute in block settings."); isError = false; return(feedDictionary); } ObjectCache feedCache = MemoryCache.Default; if (feedCache[GetFeedCacheKey(feedUrl)] != null) { feedDictionary = (Dictionary <string, object>)feedCache[GetFeedCacheKey(feedUrl)]; } else { XDocument feed = null; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(feedUrl); using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { if (resp.StatusCode == HttpStatusCode.OK) { XmlReader feedReader = XmlReader.Create(resp.GetResponseStream()); feed = XDocument.Load(feedReader); feedReader.Close(); } else { message.Add("Error loading feed.", string.Format("An error has occurred while loading the feed. Status Code: {0} - {1}", (int)resp.StatusCode, resp.StatusDescription)); isError = true; } } if (feed != null) { string detailPageBaseUrl = string.Empty; int detailPageID = 0; if (!String.IsNullOrEmpty(detailPage)) { detailPageID = new Rock.Model.PageService(new Rock.Data.RockContext()).Get(new Guid(detailPage)).Id; detailPageBaseUrl = new PageReference(detailPageID).BuildUrl(); } if (detailPageID > 0) { detailPageBaseUrl = new PageReference(detailPageID).BuildUrl(); } Dictionary <string, XNamespace> namespaces = feed.Root.Attributes() .Where(a => a.IsNamespaceDeclaration) .GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName, a => XNamespace.Get(a.Value)) .ToDictionary(g => g.Key, g => g.First()); feedDictionary = BuildElementDictionary(feed.Elements().First(), namespaces); if (feedDictionary.Count == 1 && feedDictionary.First().Value.GetType() == typeof(Dictionary <string, object>)) { feedDictionary = (Dictionary <string, object>)feedDictionary.First().Value; } if (feedDictionary.ContainsKey("lastBuildDate")) { feedDictionary["lastBuildDate"] = DateTimeOffset.Parse(feedDictionary["lastBuildDate"].ToString()).LocalDateTime; } if (feedDictionary.ContainsKey("updated")) { feedDictionary["updated"] = DateTimeOffset.Parse(feedDictionary["updated"].ToString()).LocalDateTime; } if (feedDictionary.ContainsKey("item") || feedDictionary.ContainsKey("entry")) { List <Dictionary <string, object> > articles = (List <Dictionary <string, object> >)feedDictionary.Where(x => x.Key == "item" || x.Key == "entry").FirstOrDefault().Value; foreach (var article in articles) { string idEntry = String.Empty; string idEntryHashed = string.Empty; if (article.ContainsKey("id")) { idEntry = article["id"].ToString(); } if (article.ContainsKey("guid")) { if (article["guid"].GetType() == typeof(Dictionary <string, object>)) { idEntry = ((Dictionary <string, object>)article["guid"])["value"].ToString(); } else { idEntry = article["guid"].ToString(); } } if (!String.IsNullOrWhiteSpace(idEntry)) { System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.SHA1.Create(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (byte b in hashAlgorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(idEntry))) { sb.Append(b.ToString("X2")); } idEntryHashed = sb.ToString(); Dictionary <string, string> queryString = new Dictionary <string, string>(); queryString.Add("feedItemId", idEntryHashed); if (detailPageID > 0) { article.Add("detailPageUrl", new PageReference(detailPageID, 0, queryString).BuildUrl()); } article.Add("articleHash", idEntryHashed); } if (article.ContainsKey("pubDate")) { article["pubDate"] = DateTimeOffset.Parse(article["pubDate"].ToString()).LocalDateTime; } if (article.ContainsKey("updated")) { article["updated"] = DateTimeOffset.Parse(article["updated"].ToString()).LocalDateTime; } } } if (!String.IsNullOrEmpty(detailPageBaseUrl)) { feedDictionary.Add("DetailPageBaseUrl", detailPageBaseUrl); } } if (feedDictionary != null) { feedCache.Set(GetFeedCacheKey(feedUrl), feedDictionary, DateTimeOffset.Now.AddMinutes(cacheDuration)); } } return(feedDictionary); }
/// <summary> /// Handles the Click event of the btnDeleteConfirm control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnDeleteConfirm_Click( object sender, EventArgs e ) { bool canDelete = false; var rockContext = new RockContext(); SiteService siteService = new SiteService( rockContext ); Site site = siteService.Get( int.Parse( hfSiteId.Value ) ); LayoutService layoutService = new LayoutService( rockContext ); PageService pageService = new PageService( rockContext ); PageViewService pageViewService = new PageViewService( rockContext ); if ( site != null ) { var sitePages = new List<int> { site.DefaultPageId ?? -1, site.LoginPageId ?? -1, site.RegistrationPageId ?? -1, site.PageNotFoundPageId ?? -1 }; foreach ( var pageView in pageViewService .Queryable() .Where( t => t.Page != null && t.Page.Layout != null && t.Page.Layout.SiteId == site.Id ) ) { pageView.Page = null; pageView.PageId = null; } var pageQry = pageService.Queryable( "Layout" ) .Where( t => t.Layout.SiteId == site.Id || sitePages.Contains( t.Id ) ); pageService.DeleteRange( pageQry ); var layoutQry = layoutService.Queryable() .Where( l => l.SiteId == site.Id ); layoutService.DeleteRange( layoutQry ); rockContext.SaveChanges( true ); string errorMessage; canDelete = siteService.CanDelete( site, out errorMessage, includeSecondLvl: true ); if ( !canDelete ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Alert ); return; } siteService.Delete( site ); rockContext.SaveChanges(); SiteCache.Flush( site.Id ); } NavigateToParentPage(); }
/// <summary> /// Recursively saves Pages and associated Blocks, PageRoutes and PageContexts. /// </summary> /// <param name="page">The current Page to save</param> /// <param name="newBlockTypes">List of BlockTypes not currently installed</param> /// <param name="personId">Id of the Person performing the "Import" operation</param> /// <param name="parentPageId">Id of the the current Page's parent</param> /// <param name="siteId">Id of the site the current Page is being imported into</param> private void SavePages( Page page, IEnumerable<BlockType> newBlockTypes, int personId, int parentPageId, int siteId ) { // find layout var layoutService = new LayoutService(); var layout = layoutService.GetBySiteId(siteId).Where( l => l.Name == page.Layout.Name && l.FileName == page.Layout.FileName ).FirstOrDefault(); if ( layout == null ) { layout = new Layout(); layout.FileName = page.Layout.FileName; layout.Name = page.Layout.Name; layout.SiteId = siteId; layoutService.Add( layout, null ); layoutService.Save( layout, null ); } int layoutId = layout.Id; // Force shallow copies on entities so save operations are more atomic and don't get hosed // by nested object references. var pg = page.Clone(deepCopy: false); var blockTypes = newBlockTypes.ToList(); pg.ParentPageId = parentPageId; pg.LayoutId = layoutId; var pageService = new PageService(); pageService.Add( pg, personId ); pageService.Save( pg, personId ); var blockService = new BlockService(); foreach ( var block in page.Blocks ?? new List<Block>() ) { var blockType = blockTypes.FirstOrDefault( bt => block.BlockType.Path == bt.Path ); var b = block.Clone( deepCopy: false ); b.PageId = pg.Id; if ( blockType != null ) { b.BlockTypeId = blockType.Id; } blockService.Add( b, personId ); blockService.Save( b, personId ); } var pageRouteService = new PageRouteService(); foreach ( var pageRoute in page.PageRoutes ?? new List<PageRoute>() ) { var pr = pageRoute.Clone(deepCopy: false); pr.PageId = pg.Id; pageRouteService.Add( pr, personId ); pageRouteService.Save( pr, personId ); } var pageContextService = new PageContextService(); foreach ( var pageContext in page.PageContexts ?? new List<PageContext>() ) { var pc = pageContext.Clone(deepCopy: false); pc.PageId = pg.Id; pageContextService.Add( pc, personId ); pageContextService.Save( pc, personId ); } foreach ( var p in page.Pages ?? new List<Page>() ) { SavePages( p, blockTypes, personId, pg.Id, siteId ); } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); List<int> expandedPageIds = new List<int>(); RockContext rockContext = new RockContext(); PageService pageService = new PageService( rockContext ); var allPages = pageService.Queryable( "PageContexts, PageRoutes" ); foreach ( var page in allPages ) { PageCache.Read( page ); } foreach ( var block in new BlockService(rockContext).Queryable() ) { BlockCache.Read( block ); } foreach ( var blockType in new BlockTypeService( rockContext ).Queryable() ) { BlockTypeCache.Read( blockType ); } if ( Page.IsPostBack ) { foreach ( string expandedId in hfExpandedIds.Value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) ) { int id = 0; if ( expandedId.StartsWith( "p" ) && expandedId.Length > 1 ) { if ( int.TryParse( expandedId.Substring( 1 ), out id ) ) { expandedPageIds.Add( id ); } } } } else { string pageSearch = this.PageParameter( "pageSearch" ); if ( !string.IsNullOrWhiteSpace( pageSearch ) ) { foreach ( Page page in pageService.Queryable().Where( a => a.InternalName.IndexOf( pageSearch ) >= 0 ) ) { Page selectedPage = page; while ( selectedPage != null ) { selectedPage = selectedPage.ParentPage; if ( selectedPage != null ) { expandedPageIds.Add( selectedPage.Id ); } } } } } var sb = new StringBuilder(); sb.AppendLine( "<ul id=\"treeview\">" ); string rootPage = GetAttributeValue("RootPage"); if ( ! string.IsNullOrEmpty( rootPage ) ) { Guid pageGuid = rootPage.AsGuid(); allPages = allPages.Where( a => a.ParentPage.Guid == pageGuid ); } else { allPages = allPages.Where( a => a.ParentPageId == null ); } foreach ( var page in allPages.OrderBy( a => a.Order ).ThenBy( a => a.InternalName ).Include(a => a.Blocks).ToList() ) { sb.Append( PageNode( PageCache.Read( page ), expandedPageIds, rockContext ) ); } sb.AppendLine( "</ul>" ); lPages.Text = sb.ToString(); }
/// <summary> /// Builds a dictionary containing the content of the provided <see cref="System.ServiceModel.Syndication.SyndicationItem"/> /// </summary> /// <param name="i">The <see cref="System.ServiceModel.Syndicawtion.SyndicationItem"/> to be converted to a dictionary.</param> /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page.</param> /// <returns>A <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the provided syndication item.</returns> private static Dictionary<string, object> BuildSyndicationItem( SyndicationItem i, string detailPage ) { Dictionary<string, object> itemDictionary = new Dictionary<string, object>(); if ( i != null ) { itemDictionary.Add( "AttributeExtensions", i.AttributeExtensions.ToDictionary( a => a.Key.ToString(), a => a.Value ) ); string detailPageUrl = string.Empty; if ( !String.IsNullOrWhiteSpace( detailPage ) ) { Rock.Model.Page page = new Rock.Model.PageService().Get( new Guid( detailPage ) ); Dictionary<string, string> queryString = new Dictionary<string, string>(); queryString.Add( "feedItemId", System.Web.HttpUtility.UrlEncode( i.Id ) ); detailPageUrl = new PageReference( page.Id, 0, queryString ).BuildUrl(); } List<Dictionary<string, object>> authors = new List<Dictionary<string, object>>(); foreach ( var a in i.Authors ) { authors.Add( BuildSyndicationPerson( a ) ); } itemDictionary.Add( "Authors", authors ); itemDictionary.Add( "BaseUri", i.BaseUri == null ? null : i.BaseUri.ToString() ); List<Dictionary<string, object>> categories = new List<Dictionary<string, object>>(); foreach ( var c in i.Categories ) { categories.Add( BuildSyndicationCategory( c ) ); } itemDictionary.Add( "Categories", categories ); itemDictionary.Add( "Content", i.Content == null ? null : System.Web.HttpUtility.HtmlDecode( ( (TextSyndicationContent)i.Content ).Text ) ); List<Dictionary<string, object>> contributors = new List<Dictionary<string, object>>(); foreach ( var c in i.Contributors ) { contributors.Add( BuildSyndicationPerson( c ) ); } itemDictionary.Add( "Contributors", contributors ); itemDictionary.Add( "Copyright", i.Copyright == null ? null : i.Copyright.Text ); itemDictionary.Add( "DetailPageUrl", detailPageUrl ); itemDictionary.Add( "ElementExtensions", i.ElementExtensions ); itemDictionary.Add( "Id", i.Id ); itemDictionary.Add( "LastUpdatedTime", i.LastUpdatedTime.ToLocalTime().DateTime ); List<Dictionary<string, object>> link = new List<Dictionary<string, object>>(); foreach ( var l in i.Links ) { link.Add( BuildSyndicationLink( l ) ); } itemDictionary.Add( "Links", link ); itemDictionary.Add( "PublishDate", i.PublishDate.ToLocalTime().DateTime ); itemDictionary.Add( "Summary", i.Summary == null ? null : i.Summary.Text ); itemDictionary.Add( "Title", i.Title == null ? null : i.Title.Text ); } return itemDictionary; }
/// <summary> /// Gets a <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the contents of the syndicated feed. /// </summary> /// <param name="feedUrl">A <see cref="System.String"/> representing the URL of the feed.</param> /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page. </param> /// <param name="cacheDuration">A <see cref="System.Int32"/> representing the length of time that the content of the RSS feed will be saved to cache.</param> /// <param name="message">A <see cref="System.Collections.Generic.Dictionary{string,object}"/> that will contain any error or alert messages that are returned.</param> /// <param name="isError">A <see cref="System.Boolean"/> that is <c>true</c> if an error has occurred, otherwise <c>false</c>.</param> /// <returns></returns> public static Dictionary<string, object> GetFeed( string feedUrl, string detailPage, int cacheDuration, ref Dictionary<string, string> message, ref bool isError ) { Dictionary<string, object> feedDictionary = new Dictionary<string, object>(); if ( message == null ) { message = new Dictionary<string, string>(); } if ( String.IsNullOrEmpty( feedUrl ) ) { message.Add( "Feed URL not provided.", "The RSS Feed URL has not been provided. Please update the \"RSS Feed URL\" attribute in the block settings." ); return feedDictionary; } if ( !System.Text.RegularExpressions.Regex.IsMatch( feedUrl, @"^(http://|https://|)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?" ) ) { message.Add( "Feed URL not valid.", "The Feed URL is not formatted properly. Please verify the \"RSS Feed URL\" attribute in block settings." ); isError = false; return feedDictionary; } ObjectCache feedCache = RockMemoryCache.Default; if ( feedCache[GetFeedCacheKey( feedUrl )] != null ) { feedDictionary = (Dictionary<string, object>)feedCache[GetFeedCacheKey( feedUrl )]; } else { XDocument feed = null; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create( feedUrl ); using ( HttpWebResponse resp = (HttpWebResponse)req.GetResponse() ) { if ( resp.StatusCode == HttpStatusCode.OK ) { XmlReader feedReader = XmlReader.Create( resp.GetResponseStream() ); feed = XDocument.Load( feedReader ); feedReader.Close(); } else { message.Add( "Error loading feed.", string.Format( "An error has occurred while loading the feed. Status Code: {0} - {1}", (int)resp.StatusCode, resp.StatusDescription ) ); isError = true; } } if ( feed != null ) { string detailPageBaseUrl = string.Empty; int detailPageID = 0; if(!String.IsNullOrEmpty(detailPage)) { detailPageID = new Rock.Model.PageService( new Rock.Data.RockContext() ).Get( new Guid( detailPage ) ).Id; detailPageBaseUrl = new PageReference( detailPageID ).BuildUrl(); } if ( detailPageID > 0 ) { detailPageBaseUrl = new PageReference( detailPageID ).BuildUrl(); } Dictionary<string, XNamespace> namespaces = feed.Root.Attributes() .Where( a => a.IsNamespaceDeclaration ) .GroupBy( a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName, a => XNamespace.Get( a.Value ) ) .ToDictionary( g => g.Key, g => g.First() ); feedDictionary = BuildElementDictionary( feed.Elements().First(), namespaces ); if ( feedDictionary.Count == 1 && feedDictionary.First().Value.GetType() == typeof(Dictionary<string,object>) ) { feedDictionary = (Dictionary<string, object>)feedDictionary.First().Value; } if ( feedDictionary.ContainsKey("lastBuildDate") ) { feedDictionary["lastBuildDate"] = DateTimeOffset.Parse( feedDictionary["lastBuildDate"].ToString() ).LocalDateTime; } if ( feedDictionary.ContainsKey("updated") ) { feedDictionary["updated"] = DateTimeOffset.Parse( feedDictionary["updated"].ToString() ).LocalDateTime; } if ( feedDictionary.ContainsKey( "item" ) || feedDictionary.ContainsKey( "entry" ) ) { List<Dictionary<string, object>> articles = (List<Dictionary<string, object>>)feedDictionary.Where( x => x.Key == "item" || x.Key == "entry" ).FirstOrDefault().Value; foreach ( var article in articles ) { string idEntry = String.Empty; string idEntryHashed = string.Empty; if ( article.ContainsKey( "id" ) ) { idEntry = article["id"].ToString(); } if ( article.ContainsKey( "guid" ) ) { if ( article["guid"].GetType() == typeof( Dictionary<string, object> ) ) { idEntry = ( (Dictionary<string, object>)article["guid"] )["value"].ToString(); } else { idEntry = article["guid"].ToString(); } } if ( !String.IsNullOrWhiteSpace( idEntry ) ) { System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.SHA1.Create(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach ( byte b in hashAlgorithm.ComputeHash( System.Text.Encoding.UTF8.GetBytes( idEntry ) ) ) { sb.Append( b.ToString( "X2" ) ); } idEntryHashed = sb.ToString(); Dictionary<string, string> queryString = new Dictionary<string, string>(); queryString.Add( "feedItemId", idEntryHashed ); if ( detailPageID > 0 ) { article.Add( "detailPageUrl", new PageReference( detailPageID, 0, queryString ).BuildUrl() ); } article.Add( "articleHash", idEntryHashed ); } if ( article.ContainsKey( "pubDate" ) ) { article["pubDate"] = DateTimeOffset.Parse( article["pubDate"].ToString() ).LocalDateTime; } if ( article.ContainsKey( "updated" ) ) { article["updated"] = DateTimeOffset.Parse( article["updated"].ToString() ).LocalDateTime; } } } if(!String.IsNullOrEmpty(detailPageBaseUrl)) { feedDictionary.Add( "DetailPageBaseUrl", detailPageBaseUrl ); } } if ( feedDictionary != null ) { feedCache.Set( GetFeedCacheKey( feedUrl ), feedDictionary, DateTimeOffset.Now.AddMinutes( cacheDuration ) ); } } return feedDictionary; }
protected void lbSave_Click( object sender, EventArgs e ) { if ( updatePage ) { var pageCache = PageCache.Read( RockPage.PageId ); if ( pageCache != null && ( pageCache.PageTitle != tbName.Text || pageCache.Description != tbDesc.Text ) ) { var rockContext = new RockContext(); var service = new PageService( rockContext ); var page = service.Get( pageCache.Id ); page.InternalName = tbName.Text; page.PageTitle = tbName.Text; page.BrowserTitle = tbName.Text; page.Description = tbDesc.Text; rockContext.SaveChanges(); Rock.Web.Cache.PageCache.Flush( page.Id ); pageCache = PageCache.Read( RockPage.PageId ); var breadCrumb = RockPage.BreadCrumbs.Where( c => c.Url == RockPage.PageReference.BuildUrl() ).FirstOrDefault(); if ( breadCrumb != null ) { breadCrumb.Name = pageCache.BreadCrumbText; } } } SetAttributeValue( "Query", ceQuery.Text ); SetAttributeValue( "QueryParams", tbParams.Text ); SetAttributeValue( "UrlMask", tbUrlMask.Text ); SetAttributeValue( "Columns", tbColumns.Text ); SetAttributeValue( "ShowColumns", ddlHideShow.SelectedValue ); SetAttributeValue( "FormattedOutput", ceFormattedOutput.Text ); SetAttributeValue( "PersonReport", cbPersonReport.Checked.ToString() ); SetAttributeValue( "MergeFields", tbMergeFields.Text ); SaveAttributeValues(); ShowView(); }
/// <summary> /// Sets the values on select. /// </summary> protected override void SetValuesOnSelect() { var pages = new PageService( new RockContext() ).Queryable().Where( p => ItemIds.Contains( p.Id.ToString() ) ); this.SetValues( pages ); }
/// <summary> /// Renders the Ads using Liquid. /// </summary> private void Render() { var rockContext = new RockContext(); MarketingCampaignAdService marketingCampaignAdService = new MarketingCampaignAdService( rockContext ); var qry = marketingCampaignAdService.Queryable(); // limit to date range DateTime currentDateTime = RockDateTime.Now.Date; qry = qry.Where( a => ( a.StartDate <= currentDateTime ) && ( currentDateTime <= a.EndDate ) ); // limit to approved qry = qry.Where( a => a.MarketingCampaignAdStatus == MarketingCampaignAdStatus.Approved ); /* Block Attributes */ // Audience string audience = GetAttributeValue( "Audience" ); if ( !string.IsNullOrWhiteSpace( audience ) ) { var idList = new List<int>(); foreach ( string guid in audience.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) ) { var definedValue = DefinedValueCache.Read( new Guid( guid ) ); if ( definedValue != null ) { idList.Add( definedValue.Id ); } } qry = qry.Where( a => a.MarketingCampaign.MarketingCampaignAudiences.Any( x => idList.Contains( x.AudienceTypeValueId ) ) ); } // AudiencePrimarySecondary string audiencePrimarySecondary = GetAttributeValue( "AudiencePrimarySecondary" ); if ( !string.IsNullOrWhiteSpace( audiencePrimarySecondary ) ) { // 1 = Primary, 2 = Secondary List<int> idlist = audiencePrimarySecondary.SplitDelimitedValues().Select( a => int.Parse( a ) ).ToList(); if ( idlist.Contains( 1 ) && !idlist.Contains( 2 ) ) { // only show to Primary Audiences qry = qry.Where( a => a.MarketingCampaign.MarketingCampaignAudiences.Any( x => x.IsPrimary == true ) ); } else if ( idlist.Contains( 2 ) && !idlist.Contains( 1 ) ) { // only show to Secondary Audiences qry = qry.Where( a => a.MarketingCampaign.MarketingCampaignAudiences.Any( x => x.IsPrimary == false ) ); } } // Campuses string campuses = GetAttributeValue( "Campuses" ); if ( !string.IsNullOrWhiteSpace( campuses ) ) { List<int> idlist = campuses.SplitDelimitedValues().Select( a => int.Parse( a ) ).ToList(); qry = qry.Where( a => a.MarketingCampaign.MarketingCampaignCampuses.Any( x => idlist.Contains( x.CampusId ) ) ); } // Ad Types string adtypes = GetAttributeValue( "AdTypes" ); if ( !string.IsNullOrWhiteSpace( adtypes ) ) { List<int> idlist = adtypes.SplitDelimitedValues().Select( a => int.Parse( a ) ).ToList(); qry = qry.Where( a => idlist.Contains( a.MarketingCampaignAdTypeId ) ); } // Image Types string imageTypes = GetAttributeValue( "ImageTypes" ); List<string> imageTypeFilter = null; if ( !string.IsNullOrWhiteSpace( imageTypes ) ) { imageTypeFilter = imageTypes.SplitDelimitedValues().ToList(); } // Campus Context Campus campusContext = this.ContextEntity<Campus>(); if ( campusContext != null ) { // limit to ads that are targeted to the current campus context qry = qry.Where( a => a.MarketingCampaign.MarketingCampaignCampuses.Any( x => x.CampusId.Equals( campusContext.Id ) ) ); } // Max Items string maxItems = GetAttributeValue( "MaxItems" ); int? maxAdCount = null; if ( !string.IsNullOrWhiteSpace( maxItems ) ) { int parsedCount = 0; if ( int.TryParse( maxItems, out parsedCount ) ) { maxAdCount = parsedCount; } } List<MarketingCampaignAd> marketingCampaignAdList; qry = qry.OrderBy( a => a.Priority ).ThenBy( a => a.StartDate ).ThenBy( a => a.MarketingCampaign.Title ); if ( maxAdCount == null ) { marketingCampaignAdList = qry.ToList(); } else { marketingCampaignAdList = qry.Take( maxAdCount.Value ).ToList(); } // build dictionary for liquid var ads = new List<Dictionary<string, object>>(); foreach ( var marketingCampaignAd in marketingCampaignAdList ) { var ad = new Dictionary<string, object>(); // DetailPage string detailPageUrl = string.Empty; string detailPageGuid = GetAttributeValue( "DetailPage" ); if ( !string.IsNullOrWhiteSpace( detailPageGuid ) ) { Rock.Model.Page detailPage = new PageService( rockContext ).Get( new Guid( detailPageGuid ) ); if ( detailPage != null ) { Dictionary<string, string> queryString = new Dictionary<string, string>(); queryString.Add( "ad", marketingCampaignAd.Id.ToString() ); detailPageUrl = new PageReference( detailPage.Id, 0, queryString ).BuildUrl(); } } string eventGroupName = marketingCampaignAd.MarketingCampaign.EventGroup != null ? marketingCampaignAd.MarketingCampaign.EventGroup.Name : string.Empty; // Marketing Campaign Fields ad.Add( "Title", marketingCampaignAd.MarketingCampaign.Title ); ad.Add( "ContactEmail", marketingCampaignAd.MarketingCampaign.ContactEmail ); ad.Add( "ContactFullName", marketingCampaignAd.MarketingCampaign.ContactFullName ); ad.Add( "ContactPhoneNumber", marketingCampaignAd.MarketingCampaign.ContactPhoneNumber ); ad.Add( "LinkedEvent", eventGroupName ); // Specific Ad Fields ad.Add( "AdType", marketingCampaignAd.MarketingCampaignAdType.Name ); ad.Add( "StartDate", marketingCampaignAd.StartDate.ToString() ); ad.Add( "EndDate", marketingCampaignAd.EndDate.ToString() ); ad.Add( "Priority", marketingCampaignAd.Priority ); ad.Add( "Url", marketingCampaignAd.Url ); ad.Add( "DetailPageUrl", detailPageUrl ); // Ad Attributes var attributes = new List<Dictionary<string, object>>(); ad.Add( "Attributes", attributes ); marketingCampaignAd.LoadAttributes(); Rock.Attribute.Helper.AddDisplayControls( marketingCampaignAd, phContent ); // create image resize width/height from block settings Dictionary<string, Rock.Field.ConfigurationValue> imageConfig = new Dictionary<string, Rock.Field.ConfigurationValue>(); if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "ImageWidth" ) ) && Int32.Parse( GetAttributeValue( "ImageWidth" ) ) != Int16.MinValue ) imageConfig.Add( "width", new Rock.Field.ConfigurationValue( GetAttributeValue( "ImageWidth" ) ) ); if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "ImageHeight" ) ) && Int32.Parse( GetAttributeValue( "ImageHeight" ) ) != Int16.MinValue ) imageConfig.Add( "height", new Rock.Field.ConfigurationValue( GetAttributeValue( "ImageHeight" ) ) ); foreach ( var item in marketingCampaignAd.Attributes ) { AttributeCache attribute = item.Value; List<AttributeValue> attributeValues = marketingCampaignAd.AttributeValues[attribute.Key]; foreach ( AttributeValue attributeValue in attributeValues ) { string valueHtml = string.Empty; // if block attributes limit image types, limit images if ( attribute.FieldType.Guid.Equals( new Guid( Rock.SystemGuid.FieldType.IMAGE ) ) ) { if ( imageTypeFilter != null ) { if ( !imageTypeFilter.Contains( attribute.Key ) ) { // skip to next attribute if this is an image attribute and it doesn't match the image key filter continue; } else { valueHtml = attribute.FieldType.Field.FormatValue( this, attributeValue.Value, imageConfig, false ); } } } else { valueHtml = attribute.FieldType.Field.FormatValue( this, attributeValue.Value, attribute.QualifierValues, false ); } var valueNode = new Dictionary<string, object>(); valueNode.Add( "Key", attribute.Key ); valueNode.Add( "Name", attribute.Name ); valueNode.Add( "Value", valueHtml ); attributes.Add( valueNode ); } } ads.Add( ad ); } var data = new Dictionary<string, object>(); data.Add( "Ads", ads ); data.Add( "ApplicationPath", HttpRuntime.AppDomainAppVirtualPath ); string content; try { content = GetTemplate().Render( Hash.FromDictionary( data ) ); } catch ( Exception ex ) { // liquid compile error string exMessage = "An excception occurred while compiling the Liquid template."; if ( ex.InnerException != null ) exMessage += "<br /><em>" + ex.InnerException.Message + "</em>"; content = "<div class='alert warning' style='margin: 24px auto 0 auto; max-width: 500px;' ><strong>Liquid Compile Error</strong><p>" + exMessage + "</p></div>"; } // check for errors if (content.Contains("No such template")) { // get template name Match match = Regex.Match(GetAttributeValue("Template"), @"'([^']*)"); if (match.Success) { content = String.Format("<div class='alert alert-warning'><h4>Warning</h4>Could not find the template _{1}.liquid in {0}.</div>", ResolveRockUrl("~~/Assets/Liquid"), match.Groups[1].Value); } else { content = "<div class='alert alert-warning'><h4>Warning</h4>Unable to parse the template name from settings.</div>"; } } if (content.Contains("error")) { content = "<div class='alert alert-warning'><h4>Warning</h4>" + content + "</div>"; } phContent.Controls.Clear(); phContent.Controls.Add( new LiteralControl( content ) ); // add debug info if (GetAttributeValue("EnableDebug").AsBoolean()) { StringBuilder debugInfo = new StringBuilder(); debugInfo.Append("<p /><div class='alert alert-info'><h4>Debug Info</h4>"); debugInfo.Append("<pre>"); debugInfo.Append("<p /><strong>Ad Data</strong> (referenced as 'Ads.' in Liquid)<br>"); debugInfo.Append(data.LiquidHelpText() + "</pre>"); debugInfo.Append("</div>"); phContent.Controls.Add(new LiteralControl(debugInfo.ToString())); } }
/// <summary> /// This method takes the attribute values of the original blocks, and creates copies of them that point to the copied blocks. /// In addition, any block attribute value pointing to a page in the original page tree is now updated to point to the /// corresponding page in the copied page tree. /// </summary> /// <param name="pageGuidDictionary">The dictionary containing the original page guids and the corresponding copied page guids.</param> /// <param name="blockGuidDictionary">The dictionary containing the original block guids and the corresponding copied block guids.</param> /// <param name="rockContext">The rock context.</param> /// <param name="currentPersonAliasId">The current person alias identifier.</param> private void GenerateBlockAttributeValues( Dictionary<Guid, Guid> pageGuidDictionary, Dictionary<Guid, Guid> blockGuidDictionary, RockContext rockContext, int? currentPersonAliasId = null ) { var attributeValueService = new AttributeValueService( rockContext ); var pageService = new PageService( rockContext ); var blockService = new BlockService( rockContext ); var pageGuid = Rock.SystemGuid.EntityType.PAGE.AsGuid(); var blockGuid = Rock.SystemGuid.EntityType.BLOCK.AsGuid(); Dictionary<Guid, int> blockIntDictionary = blockService.Queryable() .Where( p => blockGuidDictionary.Keys.Contains( p.Guid ) || blockGuidDictionary.Values.Contains( p.Guid ) ) .ToDictionary( p => p.Guid, p => p.Id ); var attributeValues = attributeValueService.Queryable().Where( a => a.Attribute.EntityType.Guid == blockGuid && blockIntDictionary.Values.Contains( a.EntityId.Value ) ) .ToList(); foreach ( var attributeValue in attributeValues ) { var newAttributeValue = attributeValue.Clone( false ); newAttributeValue.CreatedByPersonAlias = null; newAttributeValue.CreatedByPersonAliasId = currentPersonAliasId; newAttributeValue.CreatedDateTime = RockDateTime.Now; newAttributeValue.ModifiedByPersonAlias = null; newAttributeValue.ModifiedByPersonAliasId = currentPersonAliasId; newAttributeValue.ModifiedDateTime = RockDateTime.Now; newAttributeValue.Id = 0; newAttributeValue.Guid = Guid.NewGuid(); newAttributeValue.EntityId = blockIntDictionary[blockGuidDictionary[blockIntDictionary.Where( d => d.Value == attributeValue.EntityId.Value ).FirstOrDefault().Key]]; if ( attributeValue.Attribute.FieldType.Guid == Rock.SystemGuid.FieldType.PAGE_REFERENCE.AsGuid() ) { if ( pageGuidDictionary.ContainsKey( attributeValue.Value.AsGuid() ) ) { newAttributeValue.Value = pageGuidDictionary[attributeValue.Value.AsGuid()].ToString(); } } attributeValueService.Add( newAttributeValue ); } rockContext.SaveChanges(); }
/// <summary> /// Handles the Click event of the lbExport control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbExport_Click( object sender, EventArgs e ) { if ( _pageId.HasValue ) { var pageService = new PageService( new RockContext() ); var page = pageService.Get( _pageId.Value ); var packageService = new PackageService(); var pageName = page.InternalName.Replace( " ", "_" ) + ( cbExportChildren.Checked ? "_wChildPages" : string.Empty ); using ( var stream = packageService.ExportPage( page, cbExportChildren.Checked ) ) { EnableViewState = false; Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AddHeader( "content-disposition", "attachment; filename=" + pageName + ".nupkg" ); Response.Charset = string.Empty; Response.BinaryWrite( stream.ToArray() ); Response.Flush(); Response.End(); } } }
/// <summary> /// Copies any auths for the original pages and blocks over to the copied pages and blocks. /// </summary> /// <param name="pageGuidDictionary">The dictionary containing the original page guids and the corresponding copied page guids.</param> /// <param name="blockGuidDictionary">The dictionary containing the original block guids and the corresponding copied block guids.</param> /// <param name="rockContext">The rock context.</param> /// <param name="currentPersonAliasId">The current person alias identifier.</param> private void GeneratePageBlockAuths( Dictionary<Guid, Guid> pageGuidDictionary, Dictionary<Guid, Guid> blockGuidDictionary, RockContext rockContext, int? currentPersonAliasId = null ) { var authService = new AuthService( rockContext ); var pageService = new PageService( rockContext ); var blockService = new BlockService( rockContext ); var pageGuid = Rock.SystemGuid.EntityType.PAGE.AsGuid(); var blockGuid = Rock.SystemGuid.EntityType.BLOCK.AsGuid(); Dictionary<Guid, int> pageIntDictionary = pageService.Queryable() .Where( p => pageGuidDictionary.Keys.Contains( p.Guid ) || pageGuidDictionary.Values.Contains( p.Guid ) ) .ToDictionary( p => p.Guid, p => p.Id ); Dictionary<Guid, int> blockIntDictionary = blockService.Queryable() .Where( p => blockGuidDictionary.Keys.Contains( p.Guid ) || blockGuidDictionary.Values.Contains( p.Guid ) ) .ToDictionary( p => p.Guid, p => p.Id ); var pageAuths = authService.Queryable().Where( a => a.EntityType.Guid == pageGuid && pageIntDictionary.Values.Contains( a.EntityId.Value ) ) .ToList(); var blockAuths = authService.Queryable().Where( a => a.EntityType.Guid == blockGuid && blockIntDictionary.Values.Contains( a.EntityId.Value ) ) .ToList(); foreach ( var pageAuth in pageAuths ) { var newPageAuth = pageAuth.Clone( false ); newPageAuth.CreatedByPersonAlias = null; newPageAuth.CreatedByPersonAliasId = currentPersonAliasId; newPageAuth.CreatedDateTime = RockDateTime.Now; newPageAuth.ModifiedByPersonAlias = null; newPageAuth.ModifiedByPersonAliasId = currentPersonAliasId; newPageAuth.ModifiedDateTime = RockDateTime.Now; newPageAuth.Id = 0; newPageAuth.Guid = Guid.NewGuid(); newPageAuth.EntityId = pageIntDictionary[pageGuidDictionary[pageIntDictionary.Where( d => d.Value == pageAuth.EntityId.Value ).FirstOrDefault().Key]]; authService.Add( newPageAuth ); } foreach ( var blockAuth in blockAuths ) { var newBlockAuth = blockAuth.Clone( false ); newBlockAuth.CreatedByPersonAlias = null; newBlockAuth.CreatedByPersonAliasId = currentPersonAliasId; newBlockAuth.CreatedDateTime = RockDateTime.Now; newBlockAuth.ModifiedByPersonAlias = null; newBlockAuth.ModifiedByPersonAliasId = currentPersonAliasId; newBlockAuth.ModifiedDateTime = RockDateTime.Now; newBlockAuth.Id = 0; newBlockAuth.Guid = Guid.NewGuid(); newBlockAuth.EntityId = blockIntDictionary[blockGuidDictionary[blockIntDictionary.Where( d => d.Value == blockAuth.EntityId.Value ).FirstOrDefault().Key]]; authService.Add( newBlockAuth ); } rockContext.SaveChanges(); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { if ( !Page.IsPostBack && _pageId.HasValue ) { var rockContext = new RockContext(); LoadSites( rockContext ); PageService pageService = new PageService( rockContext ); Rock.Model.Page page = pageService.Queryable( "Layout,PageRoutes" ) .Where( p => p.Id == _pageId.Value ) .FirstOrDefault(); if ( page.Layout != null ) { ddlSite.SelectedValue = page.Layout.SiteId.ToString(); LoadLayouts( rockContext, SiteCache.Read( page.Layout.SiteId ) ); ddlLayout.SelectedValue = page.Layout.Id.ToString(); } rptProperties.DataSource = _tabs; rptProperties.DataBind(); tbPageName.Text = page.InternalName; tbPageTitle.Text = page.PageTitle; tbBrowserTitle.Text = page.BrowserTitle; ppParentPage.SetValue( pageService.Get( page.ParentPageId ?? 0 ) ); tbIconCssClass.Text = page.IconCssClass; cbPageTitle.Checked = page.PageDisplayTitle; cbPageBreadCrumb.Checked = page.PageDisplayBreadCrumb; cbPageIcon.Checked = page.PageDisplayIcon; cbPageDescription.Checked = page.PageDisplayDescription; ddlMenuWhen.SelectedValue = ( (int)page.DisplayInNavWhen ).ToString(); cbMenuDescription.Checked = page.MenuDisplayDescription; cbMenuIcon.Checked = page.MenuDisplayIcon; cbMenuChildPages.Checked = page.MenuDisplayChildPages; cbBreadCrumbIcon.Checked = page.BreadCrumbDisplayIcon; cbBreadCrumbName.Checked = page.BreadCrumbDisplayName; cbRequiresEncryption.Checked = page.RequiresEncryption; cbEnableViewState.Checked = page.EnableViewState; cbIncludeAdminFooter.Checked = page.IncludeAdminFooter; tbCacheDuration.Text = page.OutputCacheDuration.ToString(); tbDescription.Text = page.Description; ceHeaderContent.Text = page.HeaderContent; tbPageRoute.Text = string.Join( ",", page.PageRoutes.Select( route => route.Route ).ToArray() ); // Add enctype attribute to page's <form> tag to allow file upload control to function Page.Form.Attributes.Add( "enctype", "multipart/form-data" ); } base.OnLoad( e ); }
/// <summary> /// Reads new values entered by the user for the field /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public override string GetEditValue( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues ) { PagePicker ppPage = control as PagePicker; string result = null; if ( ppPage != null ) { //// Value is in format "Page.Guid,PageRoute.Guid" //// If only a Page is specified, this is just a reference to a page without a special route if ( ppPage.IsPageRoute ) { int? pageRouteId = ppPage.PageRouteId; var pageRoute = new PageRouteService().Get( pageRouteId ?? 0 ); if ( pageRoute != null ) { result = string.Format( "{0},{1}", pageRoute.Page.Guid, pageRoute.Guid ); } } else { var page = new PageService().Get( ppPage.PageId ?? 0 ); if ( page != null ) { result = page.Guid.ToString(); } } } return result; }
/// <summary> /// Binds the exception list filter. /// </summary> private void BindExceptionListFilter() { BindSitesFilter(); int siteId; var rockContext = new RockContext(); if ( int.TryParse( fExceptionList.GetUserPreference( "Site" ), out siteId ) && ddlSite.Items.FindByValue( siteId.ToString() ) != null ) { ddlSite.SelectedValue = siteId.ToString(); } int pageId; if ( int.TryParse( fExceptionList.GetUserPreference( "Page" ), out pageId ) ) { PageService pageService = new PageService( rockContext ); ppPage.SetValue( pageService.Get( pageId ) ); } else { ppPage.SetValue( None.Id ); } int userPersonId; if ( int.TryParse( fExceptionList.GetUserPreference( "User" ), out userPersonId ) ) { PersonService personService = new PersonService( rockContext ); ppUser.SetValue( personService.Get( userPersonId ) ); } if ( !String.IsNullOrEmpty( fExceptionList.GetUserPreference( "Status Code" ) ) ) { txtStatusCode.Text = fExceptionList.GetUserPreference( "Status Code" ); } DateTime startDate; if ( DateTime.TryParse( fExceptionList.GetUserPreference( "Start Date" ), out startDate ) ) { dpStartDate.Text = startDate.ToShortDateString(); } DateTime endDate; if ( DateTime.TryParse( fExceptionList.GetUserPreference( "End Date" ), out endDate ) ) { dpEndDate.Text = endDate.ToShortDateString(); } }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click( object sender, EventArgs e ) { if ( Page.IsValid ) { Rock.Model.Page page; var rockContext = new RockContext(); var pageService = new PageService( rockContext ); int pageId = hfPageId.Value.AsInteger(); if ( pageId == 0 ) { page = new Rock.Model.Page(); if ( _page != null ) { page.ParentPageId = _page.Id; page.LayoutId = _page.LayoutId; } else { page.ParentPageId = null; page.LayoutId = PageCache.Read( RockPage.PageId ).LayoutId; } page.PageTitle = dtbPageName.Text; page.BrowserTitle = page.PageTitle; page.EnableViewState = true; page.IncludeAdminFooter = true; page.MenuDisplayChildPages = true; Rock.Model.Page lastPage = pageService.GetByParentPageId( _page.Id ).OrderByDescending( b => b.Order ).FirstOrDefault(); if ( lastPage != null ) { page.Order = lastPage.Order + 1; } else { page.Order = 0; } pageService.Add( page ); } else { page = pageService.Get( pageId ); } page.LayoutId = ddlLayout.SelectedValueAsInt().Value; page.InternalName = dtbPageName.Text; if ( page.IsValid ) { rockContext.SaveChanges(); PageCache.Flush( page.Id ); if ( _page != null ) { Rock.Security.Authorization.CopyAuthorization( _page, page ); _page.FlushChildPages(); } BindGrid(); } rGrid.Visible = true; pnlDetails.Visible = false; } }
/// <summary> /// Binds the pages grid. /// </summary> protected void BindPagesGrid() { pnlPages.Visible = false; int siteId = PageParameter( "siteId" ).AsInteger(); if ( siteId == 0 ) { // quit if the siteId can't be determined return; } hfSiteId.SetValue( siteId ); pnlPages.Visible = true; // Question: Is this RegisterLayouts necessary here? Since if it's a new layout // there would not be any pages on them (which is our concern here). // It seems like it should be the concern of some other part of the puzzle. LayoutService.RegisterLayouts( Request.MapPath( "~" ), SiteCache.Read( siteId ) ); //var layouts = layoutService.Queryable().Where( a => a.SiteId.Equals( siteId ) ).Select( a => a.Id ).ToList(); // Find all the pages that are related to this site... // 1) pages used by one of this site's layouts and // 2) the site's 'special' pages used directly by the site. var rockContext = new RockContext(); var siteService = new SiteService( rockContext ); var pageService = new PageService( rockContext ); var site = siteService.Get( siteId ); if ( site != null ) { var sitePages = new List<int> { site.DefaultPageId ?? -1, site.LoginPageId ?? -1, site.RegistrationPageId ?? -1, site.PageNotFoundPageId ?? -1 }; var qry = pageService.Queryable("Layout") .Where( t => t.Layout.SiteId == siteId || sitePages.Contains( t.Id ) ); string layoutFilter = gPagesFilter.GetUserPreference( "Layout" ); if ( !string.IsNullOrWhiteSpace( layoutFilter ) && layoutFilter != Rock.Constants.All.Text ) { qry = qry.Where( a => a.Layout.ToString() == layoutFilter ); } SortProperty sortProperty = gPages.SortProperty; if ( sortProperty != null ) { qry = qry.Sort( sortProperty ); } else { qry = qry .OrderBy( t => t.Layout.Name ) .ThenBy( t => t.InternalName ); } gPages.DataSource = qry.ToList(); gPages.DataBind(); } }
/// <summary> /// Handles the OnSave event of the masterPage control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void masterPage_OnSave( object sender, EventArgs e ) { Page.Validate( BlockValidationGroup ); if ( Page.IsValid && _pageId.HasValue ) { var rockContext = new RockContext(); var pageService = new PageService( rockContext ); var routeService = new PageRouteService( rockContext ); var contextService = new PageContextService( rockContext ); var page = pageService.Get( _pageId.Value ); int parentPageId = ppParentPage.SelectedValueAsInt() ?? 0; if ( page.ParentPageId != parentPageId ) { if ( page.ParentPageId.HasValue ) { PageCache.Flush( page.ParentPageId.Value ); } if ( parentPageId != 0 ) { PageCache.Flush( parentPageId ); } } page.InternalName = tbPageName.Text; page.PageTitle = tbPageTitle.Text; page.BrowserTitle = tbBrowserTitle.Text; if ( parentPageId != 0 ) { page.ParentPageId = parentPageId; } else { page.ParentPageId = null; } page.LayoutId = ddlLayout.SelectedValueAsInt().Value; int? orphanedIconFileId = null; page.IconCssClass = tbIconCssClass.Text; page.PageDisplayTitle = cbPageTitle.Checked; page.PageDisplayBreadCrumb = cbPageBreadCrumb.Checked; page.PageDisplayIcon = cbPageIcon.Checked; page.PageDisplayDescription = cbPageDescription.Checked; page.DisplayInNavWhen = (DisplayInNavWhen)Enum.Parse( typeof( DisplayInNavWhen ), ddlMenuWhen.SelectedValue ); page.MenuDisplayDescription = cbMenuDescription.Checked; page.MenuDisplayIcon = cbMenuIcon.Checked; page.MenuDisplayChildPages = cbMenuChildPages.Checked; page.BreadCrumbDisplayName = cbBreadCrumbName.Checked; page.BreadCrumbDisplayIcon = cbBreadCrumbIcon.Checked; page.RequiresEncryption = cbRequiresEncryption.Checked; page.EnableViewState = cbEnableViewState.Checked; page.IncludeAdminFooter = cbIncludeAdminFooter.Checked; page.OutputCacheDuration = int.Parse( tbCacheDuration.Text ); page.Description = tbDescription.Text; page.HeaderContent = ceHeaderContent.Text; // new or updated route foreach ( var pageRoute in page.PageRoutes.ToList() ) { var existingRoute = RouteTable.Routes.OfType<Route>().FirstOrDefault( a => a.RouteId() == pageRoute.Id ); if ( existingRoute != null ) { RouteTable.Routes.Remove( existingRoute ); } routeService.Delete( pageRoute ); } page.PageRoutes.Clear(); foreach ( string route in tbPageRoute.Text.SplitDelimitedValues() ) { var pageRoute = new PageRoute(); pageRoute.Route = route.TrimStart( new char[] { '/' } ); pageRoute.Guid = Guid.NewGuid(); page.PageRoutes.Add( pageRoute ); } foreach ( var pageContext in page.PageContexts.ToList() ) { contextService.Delete( pageContext ); } page.PageContexts.Clear(); foreach ( var control in phContext.Controls ) { if ( control is RockTextBox ) { var tbContext = control as RockTextBox; if ( !string.IsNullOrWhiteSpace( tbContext.Text ) ) { var pageContext = new PageContext(); pageContext.Entity = tbContext.ID.Substring( 8 ).Replace( '_', '.' ); pageContext.IdParameter = tbContext.Text; page.PageContexts.Add( pageContext ); } } } if ( page.IsValid ) { rockContext.SaveChanges(); foreach ( var pageRoute in new PageRouteService( rockContext ).GetByPageId( page.Id ) ) { RouteTable.Routes.AddPageRoute( pageRoute ); } if ( orphanedIconFileId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedIconFileId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } Rock.Web.Cache.PageCache.Flush( page.Id ); string script = "if (typeof window.parent.Rock.controls.modal.close === 'function') window.parent.Rock.controls.modal.close('PAGE_UPDATED');"; ScriptManager.RegisterStartupScript( this.Page, this.GetType(), "close-modal", script, true ); } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { Site site; if ( Page.IsValid ) { var rockContext = new RockContext(); SiteService siteService = new SiteService( rockContext ); SiteDomainService siteDomainService = new SiteDomainService( rockContext ); bool newSite = false; int siteId = int.Parse( hfSiteId.Value ); if ( siteId == 0 ) { newSite = true; site = new Rock.Model.Site(); siteService.Add( site ); } else { site = siteService.Get( siteId ); } site.Name = tbSiteName.Text; site.Description = tbDescription.Text; site.Theme = ddlTheme.Text; site.DefaultPageId = ppDefaultPage.PageId; site.DefaultPageRouteId = ppDefaultPage.PageRouteId; site.LoginPageId = ppLoginPage.PageId; site.LoginPageRouteId = ppLoginPage.PageRouteId; site.CommunicationPageId = ppCommunicationPage.PageId; site.CommunicationPageRouteId = ppCommunicationPage.PageRouteId; site.RegistrationPageId = ppRegistrationPage.PageId; site.RegistrationPageRouteId = ppRegistrationPage.PageRouteId; site.PageNotFoundPageId = ppPageNotFoundPage.PageId; site.PageNotFoundPageRouteId = ppPageNotFoundPage.PageRouteId; site.ErrorPage = tbErrorPage.Text; site.GoogleAnalyticsCode = tbGoogleAnalytics.Text; site.FacebookAppId = tbFacebookAppId.Text; site.FacebookAppSecret = tbFacebookAppSecret.Text; var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList<string>(); site.SiteDomains = site.SiteDomains ?? new List<SiteDomain>(); // Remove any deleted domains foreach ( var domain in site.SiteDomains.Where( w => !currentDomains.Contains( w.Domain ) ).ToList() ) { site.SiteDomains.Remove( domain ); siteDomainService.Delete( domain ); } foreach ( string domain in currentDomains ) { SiteDomain sd = site.SiteDomains.Where( d => d.Domain == domain ).FirstOrDefault(); if ( sd == null ) { sd = new SiteDomain(); sd.Domain = domain; sd.Guid = Guid.NewGuid(); site.SiteDomains.Add( sd ); } } if ( !site.DefaultPageId.HasValue && !newSite ) { ppDefaultPage.ShowErrorMessage( "Default Page is required." ); return; } if ( !site.IsValid ) { // Controls will render the error messages return; } rockContext.WrapTransaction( () => { rockContext.SaveChanges(); if ( newSite ) { Rock.Security.Authorization.CopyAuthorization( RockPage.Layout.Site, site, rockContext ); } } ); SiteCache.Flush( site.Id ); // Create the default page is this is a new site if ( !site.DefaultPageId.HasValue && newSite ) { var siteCache = SiteCache.Read( site.Id ); // Create the layouts for the site, and find the first one LayoutService.RegisterLayouts( Request.MapPath( "~" ), siteCache ); var layoutService = new LayoutService( rockContext ); var layouts = layoutService.GetBySiteId( siteCache.Id ); Layout layout = layouts.FirstOrDefault( l => l.FileName.Equals( "FullWidth", StringComparison.OrdinalIgnoreCase ) ); if ( layout == null ) { layout = layouts.FirstOrDefault(); } if ( layout != null ) { var pageService = new PageService( rockContext ); var page = new Page(); page.LayoutId = layout.Id; page.PageTitle = siteCache.Name + " Home Page"; page.InternalName = page.PageTitle; page.BrowserTitle = page.PageTitle; page.EnableViewState = true; page.IncludeAdminFooter = true; page.MenuDisplayChildPages = true; var lastPage = pageService.GetByParentPageId( null ). OrderByDescending( b => b.Order ).FirstOrDefault(); page.Order = lastPage != null ? lastPage.Order + 1 : 0; pageService.Add( page ); rockContext.SaveChanges(); site = siteService.Get( siteCache.Id ); site.DefaultPageId = page.Id; rockContext.SaveChanges(); SiteCache.Flush( site.Id ); } } var qryParams = new Dictionary<string, string>(); qryParams["siteId"] = site.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } }
/// <summary> /// Handles the Delete event of the gPages control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gPages_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); PageService pageService = new PageService( rockContext ); var pageViewService = new PageViewService(rockContext); var siteService = new SiteService(rockContext); Rock.Model.Page page = pageService.Get( new Guid( e.RowKeyValue.ToString() ) ); if ( page != null ) { string errorMessage; if ( !pageService.CanDelete( page, out errorMessage, includeSecondLvl: true ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Alert ); return; } foreach (var site in siteService.Queryable()) { if (site.DefaultPageId == page.Id) { site.DefaultPageId = null; site.DefaultPageRouteId = null; } if (site.LoginPageId == page.Id) { site.LoginPageId = null; site.LoginPageRouteId = null; } if (site.RegistrationPageId == page.Id) { site.RegistrationPageId = null; site.RegistrationPageRouteId = null; } } foreach (var pageView in pageViewService.GetByPageId(page.Id)) { pageView.Page = null; pageView.PageId = null; } pageService.Delete( page ); rockContext.SaveChanges(); PageCache.Flush( page.Id ); } BindPagesGrid(); }