Exemple #1
0
        /// <summary>
        /// Creates the page configuration icon.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <returns></returns>
        protected string CreatePageConfigIcon( PageCache page )
        {
            var pagePropertyUrl = ResolveUrl( string.Format( "~/PageProperties/{0}?t=Page Properties", page.Id ) );

            return string.Format(
                "&nbsp;<span class='rollover-item' onclick=\"javascript: Rock.controls.modal.show($(this), '{0}'); event.stopImmediatePropagation();\" title=\"Page Properties\"><i class=\"fa fa-cog\"></i>&nbsp;</span>",
                pagePropertyUrl );
        }
        public string GetLink(PageCache cache, string politicianKey)
        {
            if (cache == null)
            {
                return(GetLinkFromDatabase(politicianKey));
            }

            var methodInfo = typeof(PoliticiansCache).GetMethod("Get" + DatabaseColumn);

            return
                (methodInfo.Invoke(cache.Politicians, new object[] { politicianKey }) as
                 string);
        }
Exemple #3
0
        /// <summary>
        /// Handles the Click event of the lbWizardInstance 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 lbWizardInstance_Click(object sender, EventArgs e)
        {
            var qryParams = new Dictionary <string, string>();
            var pageCache = PageCache.Get(RockPage.PageId);

            if (pageCache != null &&
                pageCache.ParentPage != null &&
                pageCache.ParentPage.ParentPage != null)
            {
                qryParams.Add("RegistrationInstanceId", RegistrationInstanceId.ToString());
                NavigateToPage(pageCache.ParentPage.ParentPage.Guid, qryParams);
            }
        }
        // Page Functions

        private PageCache GetPageForDefaultRoute(RequestContext requestContext)
        {
            int?routeData_PageId = requestContext.RouteData.Values["PageId"]?.ToString()?.AsIntegerOrNull();

            if (routeData_PageId.HasValue)
            {
                return(PageCache.Get(routeData_PageId.Value));
            }
            else
            {
                return(null);
            }
        }
Exemple #5
0
        /// <summary>
        /// Outputs server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter" /> object and stores tracing information about the control if tracing is enabled.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter" /> object that receives the control content.</param>
        public override void RenderControl(HtmlTextWriter writer)
        {
            var rockPage = this.Page as RockPage;

            if (rockPage != null)
            {
                var pageCache = PageCache.Get(rockPage.PageId);
                if (pageCache != null && pageCache.PageDisplayTitle && !string.IsNullOrWhiteSpace(rockPage.PageTitle))
                {
                    writer.Write(rockPage.PageTitle);
                }
            }
        }
Exemple #6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void flushOfThePageCacheOnShutdownHappensIfTheDbIsHealthy() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void FlushOfThePageCacheOnShutdownHappensIfTheDbIsHealthy()
        {
            PageCache pageCache = spy(PageCacheRule.getPageCache(Fs.get()));

            NeoStoreDataSource ds = DsRule.getDataSource(Dir.databaseLayout(), Fs.get(), pageCache);

            ds.Start();
            verify(pageCache, never()).flushAndForce();

            ds.Stop();
            ds.Shutdown();
            verify(pageCache).flushAndForce(Org.Neo4j.Io.pagecache.IOLimiter_Fields.Unlimited);
        }
Exemple #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void flushOfThePageCacheHappensOnlyOnceDuringShutdown() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void FlushOfThePageCacheHappensOnlyOnceDuringShutdown()
        {
            PageCache          pageCache = spy(PageCacheRule.getPageCache(Fs.get()));
            NeoStoreDataSource ds        = DsRule.getDataSource(Dir.databaseLayout(), Fs.get(), pageCache);

            ds.Start();
            verify(pageCache, never()).flushAndForce();
            verify(pageCache, never()).flushAndForce(any(typeof(IOLimiter)));

            ds.Stop();
            ds.Shutdown();
            verify(pageCache).flushAndForce(Org.Neo4j.Io.pagecache.IOLimiter_Fields.Unlimited);
        }
Exemple #8
0
        /// <summary>
        /// Navigates/redirects to the parent <see cref="Rock.Model.Page"/>.
        /// </summary>
        /// <param name="queryString">A <see cref="System.Collections.Generic.Dictionary{String,String}"/> containing the query string parameters to include in the linked <see cref="Rock.Model.Page"/> URL.
        /// Each <see cref="System.Collections.Generic.KeyValuePair{String,String}"/> the key value is a <see cref="System.String"/> that represents the name of the query string
        /// parameter, and the value is a <see cref="System.String"/> that represents the query string value. This dictionary defaults to a null value.</param>
        public void NavigateToParentPage(Dictionary <string, string> queryString = null)
        {
            var pageCache = PageCache.Read(RockPage.PageId);

            if (pageCache != null)
            {
                var parentPage = pageCache.ParentPage;
                if (parentPage != null)
                {
                    NavigateToPage(parentPage.Guid, queryString);
                }
            }
        }
        public static string CreateEditMethod()
        {
            StringBuilder updateContent = new StringBuilder("string updateSql = \"update ");

            updateContent.AppendFormat(" {0} set ", PageCache.TableName);
            StringBuilder updateParamsContent = new StringBuilder("List<SqlParameter> listParams = new List<SqlParameter>();\r\n");

            var editModel = PageCache.GetCmd("编辑");

            if (editModel != null)
            {
                int index = 0;
                foreach (var item in editModel.AttrList)
                {
                    string attribute = item.ColName;
                    if (index == 0)
                    {
                        updateContent.AppendFormat("{0}=@{0}", attribute);
                    }
                    else
                    {
                        updateContent.AppendFormat(",{0}=@{0}", attribute);
                    }

                    updateParamsContent.AppendFormat("\t\t\tlistParams.Add(new SqlParameter(\"@{0}\", {1}) {{ Value = model.{0} }});\r\n", attribute, item.DbType.ToMsSqlDbType());

                    index++;
                }

                updateContent.Append(" where ");
                updateContent.AppendFormat(" {0}=@{0} \";", PageCache.KeyId);
                updateParamsContent.AppendFormat("\t\t\tlistParams.Add(new SqlParameter(\"@{0}\", {1}) {{ Value = model.{0} }});\r\n", PageCache.KeyId, PageCache.KeyId_DbType.ToMsSqlDbType());

                string template = @"
        public bool Update{0}({0} model)
        {{
			{1}
            {2}
            using (SqlConnection sqlcn = ConnectionFactory.{3})
            {{
                return SqlHelper.ExecuteNonQuery(sqlcn, CommandType.Text, updateSql, listParams.ToArray()) > 0;
            }}
        }}
";
                return(string.Format(template, PageCache.TableName_Model, updateContent.ToString(), updateParamsContent.ToString(), PageCache.DatabaseName));
            }
            else
            {
                return(string.Empty);
            }
        }
        public static string CreateAddMethod()
        {
            StringBuilder addContent       = new StringBuilder();
            StringBuilder valueContent     = new StringBuilder(") values (");
            StringBuilder addparamsContent = new StringBuilder("List<SqlParameter> listParams = new List<SqlParameter>();\r\n");

            addContent.AppendFormat("string insertSql = \"insert {0}(", PageCache.TableName);
            var addModel = PageCache.GetCmd("添加");

            if (addModel != null)
            {
                int index = 0;
                foreach (var item in addModel.AttrList)
                {
                    string attribute = item.ColName;
                    if (index == 0)
                    {
                        addContent.Append(attribute);
                        valueContent.Append("@" + attribute);
                    }
                    else
                    {
                        addContent.Append(" ," + attribute);
                        valueContent.Append(" ,@" + attribute);
                    }

                    addparamsContent.AppendFormat("\t\t\tlistParams.Add(new SqlParameter(\"@{0}\", {1}) {{ Value = model.{0} }});\r\n", attribute, item.DbType.ToMsSqlDbType());

                    index++;
                }

                addContent.Append(valueContent.ToString() + ")\";");
                string template = @"
        public bool Add{0}({0} model)
        {{
			{1}
            {2}
            using (SqlConnection sqlcn = ConnectionFactory.{3})
            {{
                return SqlHelper.ExecuteNonQuery(sqlcn, CommandType.Text, insertSql, listParams.ToArray()) > 0;
            }}
        }}
";

                return(string.Format(template, PageCache.TableName_Model, addContent.ToString(), addparamsContent.ToString(), PageCache.DatabaseName));
            }
            else
            {
                return(string.Empty);
            }
        }
        /// <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 == null)
            {
                int pageId = Convert.ToInt32(PageParameter("Page"));
                _page = Rock.Web.Cache.PageCache.Read(pageId);
            }

            if (!Page.IsPostBack && _page.IsAuthorized("Administrate", CurrentPerson))
            {
                PageService     pageService = new PageService();
                Rock.Model.Page page        = pageService.Get(_page.Id);

                rptProperties.DataSource = _tabs;
                rptProperties.DataBind();

                LoadDropdowns();

                tbPageName.Text  = _page.Name;
                tbPageTitle.Text = _page.Title;
                ppParentPage.SetValue(pageService.Get(page.ParentPageId ?? 0));
                ddlLayout.Text       = _page.Layout;
                imgIcon.BinaryFileId = page.IconFileId;
                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;
                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);
        }
Exemple #12
0
        /// <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();
        }
Exemple #13
0
        public static FusionIndexProvider NewInstance(PageCache pageCache, File databaseDirectory, FileSystemAbstraction fs, IndexProvider.Monitor monitor, Config config, OperationalMode operationalMode, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector)
        {
            bool readOnly           = IndexProviderFactoryUtil.IsReadOnly(config, operationalMode);
            bool archiveFailedIndex = config.Get(GraphDatabaseSettings.archive_failed_index);

            IndexDirectoryStructure.Factory luceneDirStructure      = directoriesByProviderKey(databaseDirectory);
            IndexDirectoryStructure.Factory childDirectoryStructure = SubProviderDirectoryStructure(databaseDirectory);

            LuceneIndexProvider   lucene   = IndexProviderFactoryUtil.LuceneProvider(fs, luceneDirStructure, monitor, config, operationalMode);
            TemporalIndexProvider temporal = IndexProviderFactoryUtil.TemporalProvider(pageCache, fs, childDirectoryStructure, monitor, recoveryCleanupWorkCollector, readOnly);
            SpatialIndexProvider  spatial  = IndexProviderFactoryUtil.SpatialProvider(pageCache, fs, childDirectoryStructure, monitor, recoveryCleanupWorkCollector, readOnly, config);

            return(new FusionIndexProvider(EMPTY, EMPTY, spatial, temporal, lucene, new FusionSlotSelector00(), ProviderDescriptor, directoriesByProvider(databaseDirectory), fs, archiveFailedIndex));
        }
Exemple #14
0
        protected void lbWizardTemplate_Click(object sender, EventArgs e)
        {
            var qryParams = new Dictionary <string, string>();
            var pageCache = PageCache.Read(RockPage.PageId);

            if (pageCache != null &&
                pageCache.ParentPage != null &&
                pageCache.ParentPage.ParentPage != null &&
                pageCache.ParentPage.ParentPage.ParentPage != null)
            {
                qryParams.Add("RegistrationTemplateId", TemplateState != null ? TemplateState.Id.ToString() : "0");
                NavigateToPage(pageCache.ParentPage.ParentPage.ParentPage.Guid, qryParams);
            }
        }
Exemple #15
0
        /// <summary>
        /// Forgotten password. This presents a form for user to enter their email address.
        /// If password encryption mode allows it, a password reminder email is sent. Otherwise, a password reset email is sent.
        /// </summary>
        public ActionResult ForgottenPassword()
        {
            var data = new ForgotPasswordViewModel();

            TrackingBreadcrumb.Current.AddBreadcrumb(1, "Forgotten Password");
#if pages
            data.ContentPage = PageCache.GetByPageCode("ForgottenPassword");
            if (data.ContentPage == null)
            {
                throw new Exception("Forgotten Password page not found");
            }
#endif
            return(View(data));
        }
Exemple #16
0
		 /// <summary>
		 /// Throws <seealso cref="FormatViolationException"/> if format has changed.
		 /// </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("EmptyTryBlock") @Override protected void verifyFormat(java.io.File storeFile) throws java.io.IOException, FormatViolationException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
		 protected internal override void VerifyFormat( File storeFile )
		 {
			  PageCache pageCache = _pageCacheRule.getPageCache( GlobalFs.get() );
			  try
			  {
					  using ( GBPTree<MutableLong, MutableLong> ignored = ( new GBPTreeBuilder<MutableLong, MutableLong>( pageCache, storeFile, Layout ) ).build() )
					  {
					  }
			  }
			  catch ( MetadataMismatchException e )
			  {
					throw new FormatViolationException( this, e );
			  }
		 }
Exemple #17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void startDb() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void StartDb()
        {
            _temporaryDirectory = TestDirectory.directory("temp");
            _graphDb            = ( GraphDatabaseAPI )(new TestGraphDatabaseFactory()).setFileSystem(_fsa).newEmbeddedDatabase(TestDirectory.databaseDir());
            CreateLegacyIndex();
            CreatePropertyIndex();
            AddData(_graphDb);

            _catchupServer = new TestCatchupServer(_fsa, _graphDb);
            _catchupServer.start();
            _catchupClient = (new CatchupClientBuilder()).build();
            _catchupClient.start();
            _pageCache = _graphDb.DependencyResolver.resolveDependency(typeof(PageCache));
        }
Exemple #18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") private SwitchToSlaveCopyThenBranch newSwitchToSlaveSpy(org.neo4j.io.pagecache.PageCache pageCacheMock, org.neo4j.com.storecopy.StoreCopyClient storeCopyClient)
        private SwitchToSlaveCopyThenBranch NewSwitchToSlaveSpy(PageCache pageCacheMock, StoreCopyClient storeCopyClient)
        {
            ClusterMembers clusterMembers = mock(typeof(ClusterMembers));
            ClusterMember  master         = mock(typeof(ClusterMember));

            when(master.StoreId).thenReturn(_storeId);
            when(master.HARole).thenReturn(HighAvailabilityModeSwitcher.MASTER);
            when(master.HasRole(eq(HighAvailabilityModeSwitcher.MASTER))).thenReturn(true);
            when(master.InstanceId).thenReturn(new InstanceId(1));
            when(clusterMembers.Members).thenReturn(asList(master));

            Dependencies         resolver             = new Dependencies();
            DatabaseAvailability databaseAvailability = mock(typeof(DatabaseAvailability));

            when(databaseAvailability.Started).thenReturn(true);
            resolver.SatisfyDependencies(_requestContextFactory, clusterMembers, mock(typeof(TransactionObligationFulfiller)), mock(typeof(OnlineBackupKernelExtension)), mock(typeof(IndexConfigStore)), mock(typeof(TransactionCommittingResponseUnpacker)), mock(typeof(DataSourceManager)), mock(typeof(StoreLockerLifecycleAdapter)), mock(typeof(FileSystemWatcherService)), databaseAvailability);

            NeoStoreDataSource dataSource = mock(typeof(NeoStoreDataSource));

            when(dataSource.StoreId).thenReturn(_storeId);
            when(dataSource.DependencyResolver).thenReturn(resolver);

            DatabaseTransactionStats transactionCounters = mock(typeof(DatabaseTransactionStats));

            when(transactionCounters.NumberOfActiveTransactions).thenReturn(0L);

            Response <HandshakeResult> response = mock(typeof(Response));

            when(response.ResponseConflict()).thenReturn(new HandshakeResult(42, 2));
            when(_masterClient.handshake(anyLong(), any(typeof(StoreId)))).thenReturn(response);
            when(_masterClient.ProtocolVersion).thenReturn(Org.Neo4j.Kernel.ha.com.slave.MasterClient_Fields.Current);

            TransactionIdStore transactionIdStoreMock = mock(typeof(TransactionIdStore));

            // note that the checksum (the second member of the array) is the same as the one in the handshake mock above
            when(transactionIdStoreMock.LastCommittedTransaction).thenReturn(new TransactionId(42, 42, 42));

            MasterClientResolver masterClientResolver = mock(typeof(MasterClientResolver));

            when(masterClientResolver.Instantiate(anyString(), anyInt(), anyString(), any(typeof(Monitors)), argThat(_storeId => true), any(typeof(LifeSupport)))).thenReturn(_masterClient);

            return(spy(new SwitchToSlaveCopyThenBranch(TestDirectory.databaseLayout(), NullLogService.Instance, ConfigMock(), mock(typeof(HaIdGeneratorFactory)), mock(typeof(DelegateInvocationHandler)), mock(typeof(ClusterMemberAvailability)), _requestContextFactory, _pullerFactory, masterClientResolver, mock(typeof(SwitchToSlave.Monitor)), storeCopyClient, Suppliers.singleton(dataSource), Suppliers.singleton(transactionIdStoreMock), slave =>
            {
                SlaveServer server = mock(typeof(SlaveServer));
                InetSocketAddress inetSocketAddress = InetSocketAddress.createUnresolved("localhost", 42);

                when(server.SocketAddress).thenReturn(inetSocketAddress);
                return server;
            }, _updatePuller, pageCacheMock, mock(typeof(Monitors)), () => transactionCounters)));
        }
        public static string CreateAddMethod()
        {
            var addModel = PageCache.GetCmd("添加");

            if (addModel != null)
            {
                StringBuilder addContent   = new StringBuilder();
                StringBuilder valueContent = new StringBuilder(") values (");
                addContent.AppendFormat("string insertSql = \"insert into {0}(", PageCache.TableName);
                int index = 0;
                foreach (var item in addModel.AttrList)
                {
                    string attribute = item.ColName;
                    if (index == 0)
                    {
                        addContent.Append(attribute);
                        valueContent.Append("@" + attribute);
                    }
                    else
                    {
                        addContent.Append(" ," + attribute);
                        valueContent.Append(" ,@" + attribute);
                    }

                    index++;
                }

                addContent.Append(valueContent.ToString() + ")\";");
                string template = @"
        public bool Add{3}({0} model)
        {{
			{1}
            using (IDbConnection sqlcn = ConnectionFactory.{2})
            {{
                return sqlcn.Execute(insertSql, model) > 0;
            }}
        }}
";

                return(string.Format(template,
                                     PageCache.TableName_Model,
                                     addContent.ToString(),
                                     PageCache.DatabaseName,
                                     PageCache.TableName));
            }
            else
            {
                return(string.Empty);
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setupTwoIndexes() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SetupTwoIndexes()
        {
            _pageCache = _pageCacheRule.getPageCache(Fs);

            // Define two indexes based on different labels and different configuredSettings
            _layoutUtil1            = CreateLayoutTestUtil(_indexId1, 42);
            _layoutUtil2            = CreateLayoutTestUtil(_indexId2, 43);
            _schemaIndexDescriptor1 = _layoutUtil1.indexDescriptor();
            _schemaIndexDescriptor2 = _layoutUtil2.indexDescriptor();

            // Create the two indexes as empty, based on differently configured configuredSettings above
            CreateEmptyIndex(_schemaIndexDescriptor1, _configuredSettings1);
            CreateEmptyIndex(_schemaIndexDescriptor2, _configuredSettings2);
        }
Exemple #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PageReference"/> class from a url.
        /// </summary>
        /// <param name="uri">The URI e.g.: new Uri( ResolveRockUrlIncludeRoot("~/Person/5")</param>
        /// <param name="applicationPath">The application path e.g.: HttpContext.Current.Request.ApplicationPath</param>
        public PageReference(Uri uri, string applicationPath)
        {
            Parameters = new Dictionary <string, string>();

            var routeInfo = new Rock.Web.RouteInfo(uri, applicationPath);

            if (routeInfo != null)
            {
                if (routeInfo.RouteData.Values["PageId"] != null)
                {
                    PageId = routeInfo.RouteData.Values["PageId"].ToString().AsInteger();
                }

                else if (routeInfo.RouteData.DataTokens["PageRoutes"] != null)
                {
                    var pages = routeInfo.RouteData.DataTokens["PageRoutes"] as List <PageAndRouteId>;
                    if (pages != null && pages.Count > 0)
                    {
                        if (pages.Count == 1)
                        {
                            var pageAndRouteId = pages.First();
                            PageId  = pageAndRouteId.PageId;
                            RouteId = pageAndRouteId.RouteId;
                        }
                        else
                        {
                            SiteCache site = SiteCache.GetSiteByDomain(uri.Host);
                            if (site != null)
                            {
                                foreach (var pageAndRouteId in pages)
                                {
                                    var pageCache = PageCache.Get(pageAndRouteId.PageId);
                                    if (pageCache != null && pageCache.Layout != null && pageCache.Layout.SiteId == site.Id)
                                    {
                                        PageId  = pageAndRouteId.PageId;
                                        RouteId = pageAndRouteId.RouteId;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    foreach (var routeParm in routeInfo.RouteData.Values)
                    {
                        Parameters.Add(routeParm.Key, (string)routeParm.Value);
                    }
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext)
        {
            SiteCache.UpdateCachedEntity(this.Id, entityState);

            using (var rockContext = new RockContext())
            {
                foreach (int pageId in new PageService(rockContext).GetBySiteId(this.Id)
                         .Select(p => p.Id)
                         .ToList())
                {
                    PageCache.UpdateCachedEntity(pageId, EntityState.Detached);
                }
            }
        }
 /*
  * Test access to be able to control page size.
  */
 internal NativeLabelScanStore(PageCache pageCache, DatabaseLayout directoryStructure, FileSystemAbstraction fs, FullStoreChangeStream fullStoreChangeStream, bool readOnly, Monitors monitors, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector, int pageSize)
 {
     this._pageCache                    = pageCache;
     this._fs                           = fs;
     this._pageSize                     = pageSize;
     this._fullStoreChangeStream        = fullStoreChangeStream;
     this._directoryStructure           = directoryStructure;
     this._storeFile                    = GetLabelScanStoreFile(directoryStructure);
     this._readOnly                     = readOnly;
     this._monitors                     = monitors;
     this._monitor                      = monitors.NewMonitor(typeof(Org.Neo4j.Kernel.api.labelscan.LabelScanStore_Monitor));
     this._recoveryCleanupWorkCollector = recoveryCleanupWorkCollector;
     this._fileSystem                   = fs;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="PageReference" /> class.
        /// </summary>
        /// <param name="linkedPageValue">The linked page value.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="queryString">The query string.</param>
        public PageReference(string linkedPageValue, Dictionary <string, string> parameters = null, NameValueCollection queryString = null)
        {
            if (!string.IsNullOrWhiteSpace(linkedPageValue))
            {
                string[] items = linkedPageValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                //// linkedPageValue 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

                Guid pageGuid = Guid.Empty;
                if (items.Length > 0)
                {
                    if (Guid.TryParse(items[0], out pageGuid))
                    {
                        var pageCache = PageCache.Get(pageGuid);
                        if (pageCache != null)
                        {
                            // Set the page
                            PageId = pageCache.Id;

                            Guid pageRouteGuid = Guid.Empty;
                            if (items.Length == 2)
                            {
                                if (Guid.TryParse(items[1], out pageRouteGuid))
                                {
                                    var pageRouteInfo = pageCache.PageRoutes.FirstOrDefault(a => a.Guid == pageRouteGuid);
                                    if (pageRouteInfo != null)
                                    {
                                        // Set the route
                                        RouteId = pageRouteInfo.Id;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (parameters != null)
            {
                Parameters = new Dictionary <string, string>(parameters);
            }

            if (queryString != null)
            {
                QueryString = new NameValueCollection(queryString);
            }
        }
Exemple #25
0
        public RecordStorageEngine(DatabaseLayout databaseLayout, Config config, PageCache pageCache, FileSystemAbstraction fs, LogProvider logProvider, LogProvider userLogProvider, TokenHolders tokenHolders, SchemaState schemaState, ConstraintSemantics constraintSemantics, JobScheduler scheduler, TokenNameLookup tokenNameLookup, LockService lockService, IndexProviderMap indexProviderMap, IndexingService.Monitor indexingServiceMonitor, DatabaseHealth databaseHealth, ExplicitIndexProvider explicitIndexProvider, IndexConfigStore indexConfigStore, IdOrderingQueue explicitIndexTransactionOrdering, IdGeneratorFactory idGeneratorFactory, IdController idController, Monitors monitors, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector, OperationalMode operationalMode, VersionContextSupplier versionContextSupplier)
        {
            this._tokenHolders   = tokenHolders;
            this._schemaState    = schemaState;
            this._lockService    = lockService;
            this._databaseHealth = databaseHealth;
            this._explicitIndexProviderLookup      = explicitIndexProvider;
            this._indexConfigStore                 = indexConfigStore;
            this._constraintSemantics              = constraintSemantics;
            this._explicitIndexTransactionOrdering = explicitIndexTransactionOrdering;

            this._idController = idController;
            StoreFactory factory = new StoreFactory(databaseLayout, config, idGeneratorFactory, pageCache, fs, logProvider, versionContextSupplier);

            _neoStores = factory.OpenAllNeoStores(true);

            try
            {
                _schemaCache   = new SchemaCache(constraintSemantics, Collections.emptyList(), indexProviderMap);
                _schemaStorage = new SchemaStorage(_neoStores.SchemaStore);

                NeoStoreIndexStoreView neoStoreIndexStoreView = new NeoStoreIndexStoreView(lockService, _neoStores);
                bool readOnly = config.Get(GraphDatabaseSettings.read_only) && operationalMode == OperationalMode.single;
                monitors.AddMonitorListener(new LoggingMonitor(logProvider.GetLog(typeof(NativeLabelScanStore))));
                _labelScanStore = new NativeLabelScanStore(pageCache, databaseLayout, fs, new FullLabelStream(neoStoreIndexStoreView), readOnly, monitors, recoveryCleanupWorkCollector);

                _indexStoreView        = new DynamicIndexStoreView(neoStoreIndexStoreView, _labelScanStore, lockService, _neoStores, logProvider);
                this._indexProviderMap = indexProviderMap;
                _indexingService       = IndexingServiceFactory.createIndexingService(config, scheduler, indexProviderMap, _indexStoreView, tokenNameLookup, Iterators.asList(_schemaStorage.loadAllSchemaRules()), logProvider, userLogProvider, indexingServiceMonitor, schemaState, readOnly);

                _integrityValidator = new IntegrityValidator(_neoStores, _indexingService);
                _cacheAccess        = new BridgingCacheAccess(_schemaCache, schemaState, tokenHolders);

                _explicitIndexApplierLookup = new Org.Neo4j.Kernel.Impl.Api.ExplicitIndexApplierLookup_Direct(explicitIndexProvider);

                _labelScanStoreSync = new WorkSync <Supplier <LabelScanWriter>, LabelUpdateWork>(_labelScanStore.newWriter);

                _commandReaderFactory = new RecordStorageCommandReaderFactory();
                _indexUpdatesSync     = new WorkSync <IndexingUpdateService, IndexUpdatesWork>(_indexingService);

                _denseNodeThreshold = config.Get(GraphDatabaseSettings.dense_node_threshold);
                _recordIdBatchSize  = config.Get(GraphDatabaseSettings.record_id_batch_size);
            }
            catch (Exception failure)
            {
                _neoStores.close();
                throw failure;
            }
        }
Exemple #26
0
        /// <summary>
        /// Navigates to parent.
        /// </summary>
        /// <param name="targetPage">The target page.</param>
        private void NavigateToParent(int targetPage)
        {
            if (PageNumber > targetPage)
            {
                var pageCache = PageCache.Read(RockPage.PageId);
                if (pageCache != null)
                {
                    if (
                        (targetPage == 2 && !EventCalendarId.HasValue) ||
                        (targetPage == 3 && !EventItemId.HasValue) ||
                        (targetPage == 4 && !EventItemOccurrenceId.HasValue)
                        )
                    {
                        // We don't have the parameter neccessary to navigate, so just return
                        return;
                    }

                    // Build the querystring parameters
                    var qryParams = new Dictionary <string, string>();
                    if (targetPage >= 2 && EventCalendarId.HasValue)
                    {
                        qryParams.Add("EventCalendarId", EventCalendarId.Value.ToString());
                    }
                    if (targetPage >= 3 && EventItemId.HasValue)
                    {
                        qryParams.Add("EventItemId", EventItemId.Value.ToString());
                    }
                    if (targetPage >= 4 && EventItemOccurrenceId.HasValue)
                    {
                        qryParams.Add("EventItemOccurrenceId", EventItemOccurrenceId.Value.ToString());
                    }

                    // Find the target page
                    var parentPage  = pageCache.ParentPage;
                    int currentPage = PageNumber - 1;
                    while (parentPage != null && currentPage > targetPage)
                    {
                        parentPage = parentPage.ParentPage;
                        currentPage--;
                    }

                    // Navigate to the parent page
                    if (parentPage != null)
                    {
                        NavigateToPage(parentPage.Guid, qryParams);
                    }
                }
            }
        }
Exemple #27
0
        internal ModularDatabaseCreationContext(string databaseName, PlatformModule platformModule, DatabaseEditionContext editionContext, Procedures procedures, GraphDatabaseFacade facade)
        {
            this._databaseName = databaseName;
            this._config       = platformModule.Config;
            DatabaseIdContext idContext = editionContext.IdContext;

            this._idGeneratorFactory = idContext.IdGeneratorFactory;
            this._idController       = idContext.IdController;
            this._databaseLayout     = platformModule.StoreLayout.databaseLayout(databaseName);
            this._logService         = platformModule.Logging;
            this._scheduler          = platformModule.JobScheduler;
            this._globalDependencies = platformModule.Dependencies;
            this._tokenHolders       = editionContext.CreateTokenHolders();
            this._tokenNameLookup    = new NonTransactionalTokenNameLookup(_tokenHolders);
            this._locks = editionContext.CreateLocks();
            this._statementLocksFactory    = editionContext.CreateStatementLocksFactory();
            this._schemaWriteGuard         = editionContext.SchemaWriteGuard;
            this._transactionEventHandlers = new TransactionEventHandlers(facade);
            this._monitors = new Monitors(platformModule.Monitors);
            this._indexingServiceMonitor = _monitors.newMonitor(typeof(IndexingService.Monitor));
            this._physicalLogMonitor     = _monitors.newMonitor(typeof(LogFileCreationMonitor));
            this._fs = platformModule.FileSystem;
            this._transactionStats = editionContext.CreateTransactionMonitor();
            this._databaseHealth   = new DatabaseHealth(platformModule.PanicEventGenerator, _logService.getInternalLog(typeof(DatabaseHealth)));
            this._transactionHeaderInformationFactory = editionContext.HeaderInformationFactory;
            this._commitProcessFactory  = editionContext.CommitProcessFactory;
            this._autoIndexing          = new InternalAutoIndexing(platformModule.Config, _tokenHolders.propertyKeyTokens());
            this._indexConfigStore      = new IndexConfigStore(_databaseLayout, _fs);
            this._explicitIndexProvider = new DefaultExplicitIndexProvider();
            this._pageCache             = platformModule.PageCache;
            this._constraintSemantics   = editionContext.ConstraintSemantics;
            this._tracers    = platformModule.Tracers;
            this._procedures = procedures;
            this._ioLimiter  = editionContext.IoLimiter;
            this._clock      = platformModule.Clock;
            this._databaseAvailabilityGuard    = editionContext.CreateDatabaseAvailabilityGuard(_clock, _logService, _config);
            this._databaseAvailability         = new DatabaseAvailability(_databaseAvailabilityGuard, _transactionStats, platformModule.Clock, AwaitActiveTransactionDeadlineMillis);
            this._coreAPIAvailabilityGuard     = new CoreAPIAvailabilityGuard(_databaseAvailabilityGuard, editionContext.TransactionStartTimeout);
            this._accessCapability             = editionContext.AccessCapability;
            this._storeCopyCheckPointMutex     = new StoreCopyCheckPointMutex();
            this._recoveryCleanupWorkCollector = platformModule.RecoveryCleanupWorkCollector;
            this._databaseInfo               = platformModule.DatabaseInfo;
            this._versionContextSupplier     = platformModule.VersionContextSupplier;
            this._collectionsFactorySupplier = platformModule.CollectionsFactorySupplier;
            this._kernelExtensionFactories   = platformModule.KernelExtensionFactories;
            this._watcherServiceFactory      = editionContext.WatcherServiceFactory;
            this._facade          = facade;
            this._engineProviders = platformModule.EngineProviders;
        }
Exemple #28
0
        /// <summary>
        /// Gets the java script.
        /// </summary>
        /// <param name="badge"></param>
        /// <returns></returns>
        protected override string GetJavaScript(BadgeCache badge)
        {
            if (Person == null)
            {
                return(null);
            }

            var interactionChannelGuid = GetAttributeValue(badge, "InteractionChannel").AsGuidOrNull();
            var badgeColor             = GetAttributeValue(badge, "BadgeColor");

            if (!interactionChannelGuid.HasValue || string.IsNullOrEmpty(badgeColor))
            {
                return(null);
            }

            var dateRange = GetAttributeValue(badge, "DateRange");
            var badgeIcon = GetAttributeValue(badge, "BadgeIconCss");

            var pageId             = PageCache.Get(GetAttributeValue(badge, "DetailPage").AsGuid())?.Id;
            var interactionChannel = InteractionChannelCache.Get(interactionChannelGuid.Value);
            var detailPageUrl      = VirtualPathUtility.ToAbsolute($"~/page/{pageId}?ChannelId={interactionChannel?.Id}");

            return($@"
                $.ajax({{
                    type: 'GET',
                    url: Rock.settings.get('baseUrl') + 'api/Badges/InteractionsInRange/{Person.Id}/{interactionChannel.Id}/{HttpUtility.UrlEncode( dateRange )}' ,
                    statusCode: {{
                        200: function (data, status, xhr) {{

                        var interactionCount = data;
                        var opacity = 0;
                        if(data===0){{
                            opacity = 0.4;
                        }} else {{
                            opacity = 1;
                        }}
                        var linkUrl = '{detailPageUrl}';

                        if (linkUrl != '') {{
                                badgeContent = '<a href=\'' + linkUrl + '\'><span class=\'badge-content fa-layers fa-fw\' style=\'opacity:'+ opacity +'\'><i class=\'fa {badgeIcon} badge-icon\' style=\'color: {badgeColor}\'></i><span class=\'fa-layers-counter\'>'+ interactionCount +'</span></span></a>';
                            }} else {{
                                badgeContent = '<div class=\'badge-content fa-layers \' style=\'opacity:'+ opacity +'\'><i class=\'fa {badgeIcon} badge-icon\' style=\'color: {badgeColor}\'></i><span class=\'fa-layers-counter\'>'+ interactionCount +'</span></div>';
                            }}

                            $('.badge-interactioninrange.badge-id-{badge.Id}').html(badgeContent);
                        }}
                    }},
                }});");
        }
Exemple #29
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void selectForStoreOrConfigWithWrongConfiguredFormat()
        public virtual void SelectForStoreOrConfigWithWrongConfiguredFormat()
        {
            PageCache pageCache = PageCache;

            Config config = config("unknown_format");

            try
            {
                selectForStoreOrConfig(config, _testDirectory.databaseLayout(), _fs, pageCache, _log);
            }
            catch (Exception e)
            {
                assertThat(e, instanceOf(typeof(System.ArgumentException)));
            }
        }
Exemple #30
0
        /// <summary>
        /// Handles the GridReorder event of the gLayoutBlocks control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        protected void gLayoutBlocks_GridReorder(object sender, GridReorderEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                BlockService blockService = new BlockService(rockContext);
                var          blocks       = blockService.GetByLayoutAndZone(_Page.LayoutId, _ZoneName).ToList();
                blockService.Reorder(blocks, e.OldIndex, e.NewIndex);
                rockContext.SaveChanges();
            }

            PageCache.RemoveLayoutBlocks(_Page.LayoutId);
            PageUpdated = true;

            BindGrids();
        }
Exemple #31
0
        private void ShowSite()
        {
            lSite.Text = string.Empty;

            int?pageId = ppPage.SelectedValueAsInt();

            if (pageId.HasValue)
            {
                var page = PageCache.Read(pageId.Value);
                if (page != null && page.Layout != null && page.Layout.Site != null)
                {
                    lSite.Text = page.Layout.Site.Name;
                }
            }
        }
Exemple #32
0
 /// <summary>
 /// Sets the page.
 /// </summary>
 /// <param name="pageCache">The page cache.</param>
 internal void SetPage(PageCache pageCache)
 {
     _pageCache = pageCache;
 }
Exemple #33
0
 /// <summary>
 /// Creates the copy icon.
 /// </summary>
 /// <param name="block">The block.</param>
 /// <returns></returns>
 protected string CreatePageCopyIcon( PageCache page )
 {
     return string.Format(
         "&nbsp;<span class='rollover-item' onclick=\"javascript: __doPostBack('CopyPage', '{0}'); event.stopImmediatePropagation();\" title=\"Clone Page and Descendants\"><i class=\"fa fa-clone\"></i>&nbsp;</span>",
         page.Id );
 }
Exemple #34
0
        /// <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 == null )
            {
                int pageId = Convert.ToInt32( PageParameter( "Page" ) );
                _page = Rock.Web.Cache.PageCache.Read( pageId );
            }

            if ( !Page.IsPostBack && _page.IsAuthorized( "Administrate", CurrentPerson ) )
            {
                PageService pageService = new PageService();
                Rock.Model.Page page = pageService.Get( _page.Id );

                LoadSites();
                if ( _page.Layout != null )
                {
                    ddlSite.SelectedValue = _page.Layout.SiteId.ToString();
                    LoadLayouts( _page.Layout.Site );
                    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 );

        }
Exemple #35
0
        /// <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 )
        {
            try
            {
                int pageId = int.MinValue;
                if ( int.TryParse( PageParameter( "Page" ), out pageId ) )
                {
                    _page = Rock.Web.Cache.PageCache.Read( pageId );

                    DialogMasterPage masterPage = this.Page.Master as DialogMasterPage;
                    if ( masterPage != null )
                    {
                        masterPage.OnSave += new EventHandler<EventArgs>( masterPage_OnSave );
                        masterPage.SubTitle = string.Format( "Id: {0}", _page.Id );
                    }

                    if ( _page.IsAuthorized( "Administrate", CurrentPerson ) )
                    {
                        ddlMenuWhen.BindToEnum( typeof( DisplayInNavWhen ) );

                        phAttributes.Controls.Clear();
                        Rock.Attribute.Helper.AddEditControls( _page, phAttributes, !Page.IsPostBack );

                        var blockContexts = new Dictionary<string, string>();
                        foreach ( var block in _page.Blocks )
                        {
                            var blockControl = TemplateControl.LoadControl( block.BlockType.Path ) as RockBlock;
                            if ( blockControl != null )
                            {
                                blockControl.SetBlock( block );
                                foreach ( var context in blockControl.ContextTypesRequired )
                                {
                                    if ( !blockContexts.ContainsKey( context.Name ) )
                                    {
                                        blockContexts.Add( context.Name, context.FriendlyName );
                                    }
                                }
                            }
                        }

                        phContextPanel.Visible = blockContexts.Count > 0;

                        foreach ( var context in blockContexts )
                        {
                            var tbContext = new RockTextBox();
                            tbContext.ID = string.Format( "context_{0}", context.Key.Replace( '.', '_' ) );
                            tbContext.Required = true;
                            tbContext.Label = context.Value + " Parameter Name";
                            tbContext.Help = "The page parameter name that contains the id of this context entity.";
                            if ( _page.PageContexts.ContainsKey( context.Key ) )
                            {
                                tbContext.Text = _page.PageContexts[context.Key];
                            }

                            phContext.Controls.Add( tbContext );
                        }
                    }
                    else
                    {
                        DisplayError( "You are not authorized to edit this page" );
                    }
                }
                else
                {
                    DisplayError( "Invalid Page Id value" );
                }
            }
            catch ( SystemException ex )
            {
                DisplayError( ex.Message );
            }

            base.OnInit( e );
        }
Exemple #36
0
        /// <summary>
        /// Adds the page nodes.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="expandedPageIdList">The expanded page identifier list.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        protected string PageNode( PageCache page, List<int> expandedPageIdList, RockContext rockContext )
        {
            var sb = new StringBuilder();

            string pageSearch = this.PageParameter( "pageSearch" );
            bool isSelected = false;
            if ( !string.IsNullOrWhiteSpace( pageSearch ) )
            {
                isSelected = page.InternalName.IndexOf( pageSearch, StringComparison.OrdinalIgnoreCase ) >= 0;
            }

            bool isExpanded = expandedPageIdList.Contains( page.Id );

            var authRoles = Authorization.AuthRules( EntityTypeCache.Read<Rock.Model.Page>().Id, page.Id, Authorization.VIEW );
            string authHtml = string.Empty;
            if (authRoles.Any())
            {
                authHtml += string.Format(
                    "&nbsp<i class=\"fa fa-lock\">&nbsp;</i>{0}",
                    authRoles.Select( a => "<span class=\"badge badge-" + (a.AllowOrDeny == 'A' ? "success" : "danger")  + "\">" + a.DisplayName + "</span>"  ).ToList().AsDelimited( " " ) );
            }

            int pageEntityTypeId = EntityTypeCache.Read( "Rock.Model.Page" ).Id;

            sb.AppendFormat(
                "<li data-expanded='{4}' data-model='Page' data-id='p{0}'><span><span class='rollover-container'><i class=\"fa fa-file-o\">&nbsp;</i><a href='{1}'>{2}</a> {6} {7}<span class='js-auth-roles hidden'>{5}</span></span></span>{3}",
                page.Id, // 0
                new PageReference( page.Id ).BuildUrl(), // 1
                isSelected ? "<strong>" + page.InternalName + "</strong>" : page.InternalName, // 2
                Environment.NewLine, // 3
                isExpanded.ToString().ToLower(), // 4
                authHtml, // 5
                CreatePageConfigIcon(page), // 6
                CreateSecurityIcon( pageEntityTypeId, page.Id, page.InternalName) // 7
            );

            var childPages = page.GetPages( rockContext );
            if ( childPages.Any() || page.Blocks.Any() )
            {
                sb.AppendLine( "<ul>" );

                foreach ( var childPage in childPages.OrderBy( a => a.Order ).ThenBy( a => a.InternalName ) )
                {
                    sb.Append( PageNode( childPage, expandedPageIdList, rockContext ) );
                }

                foreach ( var block in page.Blocks.OrderBy( b => b.Order ) )
                {
                    string blockName = block.Name;
                    string blockCacheName = BlockTypeCache.Read( block.BlockTypeId, rockContext ).Name;
                    if (blockName != blockCacheName)
                    {
                        blockName = blockName + " (" + blockCacheName + ")";
                    }

                    int blockEntityTypeId = EntityTypeCache.Read( "Rock.Model.Block" ).Id;

                    sb.AppendFormat( "<li data-expanded='false' data-model='Block' data-id='b{0}'><span><span class='rollover-container'> <i class='fa fa-th-large'>&nbsp;</i> {2} {1} {4}</span></span></li>{3}",
                        block.Id, // 0
                        CreateConfigIcon( block ), // 1
                        blockName,  // 2
                        Environment.NewLine, //3
                        CreateSecurityIcon( blockEntityTypeId, block.Id, block.Name ) // 4
                    );
                }

                sb.AppendLine( "</ul>" );
            }

            sb.AppendLine( "</li>" );

            return sb.ToString();
        }
Exemple #37
0
        /// <summary>
        /// Sets the page.
        /// </summary>
        /// <param name="pageCache">The <see cref="Rock.Web.Cache.PageCache"/>.</param>
        internal void SetPage( PageCache pageCache )
        {
            _pageCache = pageCache;

            SaveContextItem( "Rock:PageId", _pageCache.Id );
            SaveContextItem( "Rock:LayoutId", _pageCache.LayoutId );
            SaveContextItem( "Rock:SiteId", _pageCache.Layout.SiteId );

            if ( this.Master is RockMasterPage )
            {
                var masterPage = (RockMasterPage)this.Master;
                masterPage.SetPage( pageCache );
            }
        }
Exemple #38
0
        /// <summary>
        /// Gets the parent page references.
        /// </summary>
        /// <returns></returns>
        public static List<PageReference> GetParentPageReferences(RockPage rockPage, PageCache currentPage, PageReference currentPageReference)
        {
            // Get previous page references in nav history
            var pageReferenceHistory = HttpContext.Current.Session["RockPageReferenceHistory"] as List<PageReference>;

            // Current page heirarchy references
            var pageReferences = new List<PageReference>();

            if (currentPage != null)
            {
                var parentPage = currentPage.ParentPage;
                if ( parentPage != null )
                {
                    var currentParentPages = parentPage.GetPageHierarchy();
                    if ( currentParentPages != null && currentParentPages.Count > 0 )
                    {
                        currentParentPages.Reverse();
                        foreach ( PageCache page in currentParentPages )
                        {
                            PageReference parentPageReference = null;
                            if ( pageReferenceHistory != null )
                            {
                                parentPageReference = pageReferenceHistory.Where( p => p.PageId == page.Id ).FirstOrDefault();
                            }

                            if ( parentPageReference == null )
                            {
                                parentPageReference = new PageReference( );
                                parentPageReference.PageId = page.Id;

                                parentPageReference.BreadCrumbs = new List<BreadCrumb>();
                                parentPageReference.QueryString = new NameValueCollection();
                                parentPageReference.Parameters = new Dictionary<string, string>();

                                string bcName = page.BreadCrumbText;
                                if ( bcName != string.Empty )
                                {
                                    parentPageReference.BreadCrumbs.Add( new BreadCrumb( bcName, parentPageReference.BuildUrl() ) );
                                }

                                foreach ( var block in page.Blocks.Where( b=> b.BlockLocation == Model.BlockLocation.Page) )
                                {
                                    try
                                    {
                                        System.Web.UI.Control control = rockPage.TemplateControl.LoadControl(block.BlockType.Path);
                                        if (control is RockBlock)
                                        {
                                            RockBlock rockBlock = control as RockBlock;
                                            rockBlock.SetBlock(page, block);
                                            rockBlock.GetBreadCrumbs(parentPageReference).ForEach(c => parentPageReference.BreadCrumbs.Add(c));
                                        }
                                        control = null;
                                    }
                                    catch (Exception ex)
                                    {
                                        ExceptionLogService.LogException(ex, HttpContext.Current, currentPage.Id, currentPage.Layout.SiteId);
                                    }
                                }

                            }

                            parentPageReference.BreadCrumbs.ForEach( c => c.Active = false );
                            pageReferences.Add( parentPageReference );
                        }
                    }
                }
            }

            return pageReferences;
        }