public override bool IsInVirtualRole(IPrincipal principal, object context)
        {
            var httpContext = HttpContext.Current;
            if (httpContext == null)
                return false;

            var queryStringToken = httpContext.Request.QueryString["token"];
            if (string.IsNullOrEmpty(queryStringToken))
                return false;

            if (!ParseGuid(queryStringToken))
                return false;

            var pageRef = new PageReference(httpContext.Request.QueryString["id"]);
            var pageLanguage = httpContext.Request.QueryString["epslanguage"];
            
            var tokenGuid = new Guid(queryStringToken);
            if (tokenGuid == Guid.Empty)
                return false;

            Logger.InfoFormat("Token present and has the correct format {0}", tokenGuid);

            var tokenStore = new AccessTokenDataStore();
            return tokenStore.PresentToken(tokenGuid, pageRef.ID, pageRef.WorkID, pageLanguage);
        }
        public override void Given()
        {
            base.Given();

            _startPageReference = ContentRepository
                .Publish<StartPage>(ContentReference.RootPage);

            _oldParentReference = ContentRepository
                .GetDefault<StartPage>(_startPageReference)
                .With(p =>
                    {
                        p.PageName = "OldParent";
                        p.LinkURL = "oldparent";
                    })
                .SaveAndPublish(ContentRepository);

            _newParent = ContentRepository.GetDefault<StartPage>(_startPageReference);
            _newParent.PageName = "NewParent";
            _newParent.LinkURL = "newparent";
            ContentRepository.Save(_newParent, SaveAction.Publish, AccessLevel.NoAccess);

            _pageToMove = ContentRepository.GetDefault<StartPage>(_oldParentReference);
            _pageToMove.PageName = "PageToMove";
            ContentRepository.Save(_pageToMove, SaveAction.Publish, AccessLevel.NoAccess);
        }
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var rockContext = new RockContext();
            var breadCrumbs = new List<BreadCrumb>();

            ConnectionRequest connectionRequest = null;

            int? requestId = PageParameter( "ConnectionRequestId" ).AsIntegerOrNull();
            if ( requestId.HasValue && requestId.Value > 0 )
            {
                connectionRequest = new ConnectionRequestService( rockContext ).Get( requestId.Value );
            }

            if ( connectionRequest != null )
            {
                breadCrumbs.Add( new BreadCrumb( connectionRequest.PersonAlias.Person.FullName, pageReference ) );
            }
            else
            {
                var connectionOpportunity = new ConnectionOpportunityService( rockContext ).Get( PageParameter( "ConnectionOpportunityId" ).AsInteger() );
                if ( connectionOpportunity != null )
                {
                    breadCrumbs.Add( new BreadCrumb( String.Format( "New {0} Connection Request", connectionOpportunity.Name ), pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Connection Request", pageReference ) );
                }
            }

            return breadCrumbs;
        }
        /// <summary>
        /// Gets the bread crumbs.
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            var itemIds = GetNavHierarchy().AsIntegerList();
            int? itemId = PageParameter( pageReference, "contentItemId" ).AsIntegerOrNull();
            if ( itemId != null )
            {
                itemIds.Add( itemId.Value );
            }

            foreach( var contentItemId in itemIds )
            {
                ContentChannelItem contentItem = new ContentChannelItemService( new RockContext() ).Get( contentItemId );
                if ( contentItem != null )
                {
                    breadCrumbs.Add( new BreadCrumb( contentItem.Title, pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Content Item", pageReference ) );
                }
            }

            return breadCrumbs;
        }
Example #5
0
        public string GetNewUrl(string oldUrl)
        {
            if(!oldUrl.EndsWith("/"))
            {
                oldUrl += "/";
            }

            // lookup Url in DDS
            var store = typeof(UrlRemapEntity).GetStore();
            var foundItem = store.Items<UrlRemapEntity>().FirstOrDefault(i => i.OldUrl.Equals(oldUrl));

            if(foundItem != null)
            {
                var reference = new PageReference(foundItem.PageId);
                var pageData = DataFactory.Instance.GetPage(reference);
                pageData = pageData.GetPageLanguage(foundItem.LanguageBranch);
                var builder = new UrlBuilder(UriSupport.AddLanguageSelection(pageData.LinkURL, pageData.LanguageBranch));

                if(Global.UrlRewriteProvider.ConvertToExternal(builder, pageData.PageLink, Encoding.UTF8))
                {
                    return builder.Uri.ToString();
                }
            }

            return null;
        }
        protected internal ContentReference(PageReference pageReference)
        {
            if(pageReference == null)
                throw new ArgumentNullException("pageReference");

            this._pageReference = pageReference;
        }
        private void AddPersonToNews()
        {
            var employees = GetEmployees().Select(e => e.FirstName + " " + e.LastName).ToArray();
            var random = new Random();

            var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
            var pagereference = new PageReference(5);

            var news = repo.GetChildren<Nyhet>(pagereference);

            foreach (var n in news)
            {
                if (!string.IsNullOrEmpty(n.Author))
                {
                    continue;
                }
                var clone = (Nyhet) n.CreateWritableClone();

                var empNo = random.Next(employees.Length);
                var emp = employees[empNo];

                clone.Author = emp;
                clone.MainIntro = n.MainIntro + " Oppdiktet av " + emp + ".";

                repo.Save(clone, SaveAction.Publish);
            }
        }
        public virtual PageDataCollection List(PageReference pageLink)
        {
            // Using functionality from
            // http://world.episerver.com/documentation/Items/Developers-Guide/EPiServer-CMS/9/Search/Searching-for-pages-based-on-page-type/
            string pageTypeId = _pageTypeRepository.Load<StandardPage>()?.ID.ToString();
            if (pageTypeId == null)
            {
                return new PageDataCollection();
            }

            PropertyCriteria productPageTypeCriterion = new PropertyCriteria
            {
                Name = "PageTypeID",
                Type = PropertyDataType.PageType,
                Value = pageTypeId,
                Condition = CompareCondition.Equal,
                Required = true
            };

            var criteria = new PropertyCriteriaCollection
            {
                productPageTypeCriterion
            };

            PageDataCollection pageDataCollection = _searchPages.FindPagesWithCriteria(pageLink, criteria);

            return pageDataCollection;
        }
Example #9
0
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            Guid entityTypeGuid = Guid.Empty;
            Guid.TryParse( GetAttributeValue( "EntityType" ), out entityTypeGuid );
            var entityType = EntityTypeCache.Read( entityTypeGuid );
            if ( entityType == null )
            {
                return base.GetBreadCrumbs( pageReference );
            }

            var breadCrumbs = new List<BreadCrumb>();

            int parentCategoryId = int.MinValue;
            if ( int.TryParse( PageParameter( "CategoryId" ), out parentCategoryId ) )
            {
                var category = CategoryCache.Read( parentCategoryId );
                while ( category != null )
                {
                    var parms = new Dictionary<string, string>();
                    parms.Add( "CategoryId", category.Id.ToString() );
                    breadCrumbs.Add( new BreadCrumb( category.Name, new PageReference( pageReference.PageId, 0, parms ) ) );

                    category = category.ParentCategory;
                }
            }

            breadCrumbs.Add( new BreadCrumb( entityType.FriendlyName + " Categories", new PageReference( pageReference.PageId ) ) );

            breadCrumbs.Reverse();

            return breadCrumbs;
        }
        protected override void establish_context()
        {
            base.establish_context();

            _repository = new PageDataRepository(new DataFactoryQueryExecutor());

            var pageType = PageType.List().First();

            _root = PageReference.RootPage;
            var start = DataFactory.Instance.GetDefaultPageData(_root, pageType.ID);
            start.PageName = "start";
            start.URLSegment = "start";
            _start = DataFactory.Instance.Save(start, SaveAction.Publish);

            var child = DataFactory.Instance.GetDefaultPageData(start.PageLink, pageType.ID);
            child.PageName = "child";
            child.URLSegment = "child";
            _child = DataFactory.Instance.Save(child, SaveAction.Publish);

            var child2 = DataFactory.Instance.GetDefaultPageData(start.PageLink, pageType.ID);
            child2.PageName = "child";
            child2.URLSegment = "child";
            child2.StopPublish = DateTime.Today;
            _child2 = DataFactory.Instance.Save(child2, SaveAction.Publish);
        }
Example #11
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? batchId = PageParameter( pageReference, "batchId" ).AsIntegerOrNull();
            if ( batchId != null )
            {
                string batchName = new FinancialBatchService( new RockContext() )
                    .Queryable().Where( b => b.Id == batchId.Value )
                    .Select( b => b.Name )
                    .FirstOrDefault();

                if ( !string.IsNullOrWhiteSpace( batchName ) )
                {
                    breadCrumbs.Add( new BreadCrumb( batchName, pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Batch", pageReference ) );
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
Example #12
0
        public string ConvertUrlToExternal(PageData pageData = null, PageReference p = null)
        {
            if (pageData == null && p == null)
            {
                return string.Empty;
            }
            var page = pageData ?? _repository.Get<PageData>(p);

            var pageUrlBuilder = new UrlBuilder(page.LinkURL);

            Global.UrlRewriteProvider.ConvertToExternal(pageUrlBuilder, page.PageLink, Encoding.UTF8);

            string pageURL = pageUrlBuilder.ToString();

            UriBuilder uriBuilder = new UriBuilder(SiteDefinition.Current.SiteUrl);

            uriBuilder.Path = pageURL;
            var jj = ServiceLocator.Current.GetInstance<UrlResolver>().GetUrl(p);
            if (uriBuilder.Path == "/")
                return uriBuilder.Uri.AbsoluteUri;

            string[] words = uriBuilder.Uri.AbsoluteUri.Split(new char[] {':', '/', '.'},
                        StringSplitOptions.RemoveEmptyEntries);
            bool reoccurs = words.Count(q => q == "http") > 1;

            if (reoccurs)
                return uriBuilder.Uri.LocalPath.StartsWith("/") ? uriBuilder.Uri.LocalPath.Remove(0,1) : uriBuilder.Uri.LocalPath;

            return uriBuilder.Uri.AbsoluteUri;
        }
Example #13
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int controllerId = int.MinValue;
            if ( int.TryParse( PageParameter( "controller" ), out controllerId ) )
            {
                var controller = new RestControllerService( new RockContext() ).Get( controllerId );
                if ( controller != null )
                {
                    string name = controller.Name.SplitCase();
                    var controllerType = Reflection.FindTypes( typeof( Rock.Rest.ApiControllerBase ) )
                        .Where( a => a.Key.Equals( controller.ClassName ) ).Select( a => a.Value ).FirstOrDefault();
                    if ( controllerType != null )
                    {
                        var obsoleteAttribute = controllerType.GetCustomAttribute<System.ObsoleteAttribute>();
                        if (obsoleteAttribute != null)
                        {
                            hlblWarning.Text = string.Format( "Obsolete: {1}", controller.Name.SplitCase(), obsoleteAttribute.Message );
                        }
                    }

                    lControllerName.Text = name + " Controller";
                    breadCrumbs.Add( new BreadCrumb( name, pageReference ) );
                }
            }

            return breadCrumbs;
        }
        private PageReference CreatePageFromJson(PageObject pageObject, PageReference parent, IContentRepository contentRepo)
        {
            BasePage newPage;
            switch (pageObject.Type)
            {
                case 0:
                    ArticlePage aPage = contentRepo.GetDefault<ArticlePage>(parent);
                    aPage.MainBody = pageObject.MainBodyText;
                    newPage = aPage;
                    break;
                case 1:
                    newPage = contentRepo.GetDefault<FolderPage>(parent);
                    break;
                case 2:
                    ListPage lPage = contentRepo.GetDefault<ListPage>(parent);
                    lPage.MainBody = pageObject.MainBodyText;
                    newPage = lPage;
                    break;
                case 3:
                    newPage = contentRepo.GetDefault<PersonPage>(parent);
                    break;
                case 4:
                    newPage = contentRepo.GetDefault<PortalPage>(parent);
                    break;
                default:
                    newPage = contentRepo.GetDefault<ArticlePage>(parent);
                    break;
            }

            newPage.PageName = pageObject.PageName;
            newPage.IntroText = pageObject.IntroText;
            contentRepo.Save(newPage, SaveAction.Publish);
            return newPage.PageLink;
        }
		/// <summary>
		/// Lists the versions.
		/// </summary>
		/// <param name="pageLink">The page link.</param>
		/// <param name="languageBranch">The language branch.</param>
		/// <returns></returns>
		public override PageVersionCollection ListVersions(PageReference pageLink, string languageBranch)
		{
			var versions = new PageVersionCollection();
			versions.AddRange(PageVersion.List(pageLink).Where(version =>
				version.LanguageBranch.Equals(languageBranch, StringComparison.OrdinalIgnoreCase)));
			return versions;
		}
        public PageDataCollection List(PageReference pageLink)
        {
            // This is to display before and after SessionState
            Thread.Sleep(3000);

            return new PageDataCollection();
        }
Example #17
0
 public static RouteValueDictionary GetPageRoute(this RequestContext requestContext, PageReference pageLink)
 {
     var values = new RouteValueDictionary();
     values[RoutingConstants.NodeKey] = pageLink;
     values[RoutingConstants.LanguageKey] = ContentLanguage.PreferredCulture.Name;
     return values;
 }
Example #18
0
        public void Send(PageReference mailReference, NameValueCollection nameValueCollection, string toEmail, string language)
        {
            var body = GetHtmlBodyForMail(mailReference, nameValueCollection, language);
            var mailPage = _contentLoader.Get<MailBasePage>(mailReference);

            Send(mailPage.MailTitle, body, toEmail);
        }
        private static void CreateNews()
        {
            var dir = new DirectoryInfo(@"c:\temp\news");

            foreach (var fil in dir.GetFiles())
            {
                using (var stream = fil.OpenRead())
                using (var reader = new StreamReader(stream))
                {
                    var title = reader.ReadLine();
                    var ingress = reader.ReadLine();
                    var content = reader.ReadLine();

                    var pagereference = new PageReference(5);

                    var repo = ServiceLocator.Current.GetInstance<IContentRepository>();

                    var newPage = repo.GetDefault<Nyhet>(pagereference);
                    newPage.PageName = title;
                    newPage.MainIntro = ingress;
                    newPage.MainBody = new XhtmlString(content);
                    repo.Save(newPage, SaveAction.Publish);
                }
            }
        }
 public FakePageReferenceFacade(PageReference rootPage,
     PageReference startPage,
     PageReference wasteBasket)
 {
     this.startPage = startPage;
     this.rootPage = rootPage;
     this.wasteBasket = wasteBasket;
 }
 public PageDataCollection FindPagesWithCriteria(PageReference start, params PropertyCriteria[] criteria)
 {
     foreach (var criterion in criteria)
     {
         Console.WriteLine(criterion.EquatableWithFormatting());
     }
     return _inner.FindPagesWithCriteria(start, criteria);
 }
 private static IEnumerable<string> FindUsagesFor(PageReference pageReference)
 {
     var references = DataFactory.Instance.GetLinksToPages(pageReference);
     if(references == null || !references.Any())
     {
         return new[] {"-"};
     }
     return references.Select(reference => reference.ID.ToString(CultureInfo.InvariantCulture));
 }
		/// <summary>
		///     <see cref="PageProviderBase.GetLocalPage"/>
		/// </summary>
		/// <param name="pageLink">Page link</param>
		/// <param name="languageSelector">Language selector</param>
		/// <returns>Page Data</returns>
		protected override PageData GetLocalPage(PageReference pageLink, ILanguageSelector languageSelector)
		{
			if (pageLink == null || PageReference.IsNullOrEmpty(pageLink))
			{
				return null;
			}

			return GetPage(MappedPPDB.Instance.LoadMapping(Name, pageLink.ID).Key, pageLink, languageSelector);
		}
        private IOrganizeChildren GetChildrenOrganizer(PageReference pageLink)
        {
            if (PageReference.IsNullOrEmpty(pageLink))
            {
                return null;
            }

            return DataFactory.Instance.GetPage(pageLink) as IOrganizeChildren;
        }
Example #25
0
 private static string PageUrl(this UrlHelper urlHelper, PageReference pageLink, object routeValues, IContentRepository contentRepository)
 {
     if (contentRepository == null)
         contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
     if (PageReference.IsNullOrEmpty(pageLink))
         return string.Empty;
     PageData page = contentRepository.Get<PageData>((ContentReference)pageLink);
     return UrlExtensions.PageUrl(urlHelper, page, routeValues);
 }
Example #26
0
        // Private Methods (1)
        /// <summary>
        /// Gets the pages from the XML document.
        /// </summary>
        /// <param name="rootElement">The root element containing the page marker definitions.</param>
        /// <returns>The list of pages described by the XML.</returns>
        private List<PageReference> GetPages(XElement rootElement)
        {
            if (rootElement == null)
                return null;

            IEnumerable<XElement> pageTargets = rootElement.Elements(_ncxNamespace + _PAGETARGET_NODE_NAME);
            if (pageTargets == null || pageTargets.Count() == 0)
                return null;

            List<PageReference> pages = new List<PageReference>();
            foreach (XElement currentTarget in pageTargets)
            {
                PageReference currentPage = new PageReference();

                //An exception will be thrown if either of these attributes are missing or have invalid values (A2S).
                string playOrder = currentTarget.Attribute("playOrder").Value;
                string pageType = currentTarget.Attribute("type").Value;
                string pageNumber = currentTarget.Attribute("value").Value;
                currentPage.AbsoluteOrder = Int32.Parse(playOrder);
                currentPage.PageType = (PageType)Enum.Parse(typeof(PageType), pageType, true);
                currentPage.PageNumber = Int32.Parse(pageNumber);

                XElement contentLink = currentTarget.Element(_ncxNamespace + "content");
                //An exception will be thrown if the content element and/or its src attribute is missing.
                // These must be specified (A2S).
                currentPage.SmilReference = contentLink.Attribute("src").Value;

                XElement label = currentTarget.Element(_ncxNamespace + "navLabel");
                //An exception will be thrown if the label is missing - a navLabel element must be specified (A2S)

                string text = String.Empty;
                XElement textElement = label.Element(_ncxNamespace + "text");
                if (textElement != null)
                {
                    text = textElement.Value;
                }
                currentPage.Text = text;

                XElement audioElement = label.Element(_ncxNamespace + "audio");
                if (audioElement != null)
                {
                    currentPage.Audio = new Audio();
                    currentPage.Audio.SourceUri = new Uri(audioElement.Attribute("src").Value, UriKind.Relative);
                    currentPage.Audio.ClipStart = ValueConversionHelper.GetConvertedTimeSpan
                        (audioElement.Attribute("clipBegin").Value);
                    currentPage.Audio.ClipEnd = ValueConversionHelper.GetConvertedTimeSpan
                        (audioElement.Attribute("clipEnd").Value);
                }

                pages.Add(currentPage);
            }
            //TODO: Do we really need to sort?
            pages.Sort();

            return pages;
        }
 private IEnumerable<PageData> GetChildrenOf(PageReference reference)
 {
     foreach (PageReference descendant in _pageSource.GetDescendents(reference))
     {
         PageData data = _pageSource.GetPage(descendant);
         if (data == null)
             throw new InvalidOperationException("Could not get page " + descendant);
         yield return data;
     }
 }
        public override void Given()
        {
            base.Given();

            var startPageReference = ContentRepository.Publish<StartPage>(ContentReference.RootPage, "StartPage");
            var childPage1Reference = ContentRepository.Publish<StartPage>(startPageReference, "ChildPage1");
            var childPage1ChildPage1Reference = ContentRepository.Publish<StandardPage>(childPage1Reference, "ChildPage1-ChildPage1");

            _pageToUseRef = ContentRepository.Publish<StandardPage>(childPage1ChildPage1Reference, "ChildPage1-ChildPage3-ChildPage1");
        }
        public override void Given()
        {
            base.Given();

            _startPageReference = ContentRepository.Publish<StartPage>(ContentReference.RootPage);

            ContentRepository.Publish<StartPage>(_startPageReference, "ChildPage1");
            ContentRepository.Publish<StartPage>(_startPageReference, "ChildPage2");
            ContentRepository.Publish<StandardPage>(_startPageReference, "ChildPage3");
        }
        public static void RenderMainNavigation(this HtmlHelper html, PageReference rootLink = null,
            ContentReference contentLink = null,
            bool includeRoot = true, IContentLoader contentLoader = null)
        {
            contentLink = contentLink ?? html.ViewContext.RequestContext.GetContentLink();
            rootLink = rootLink ?? ContentReference.StartPage;

            var writer = html.ViewContext.Writer;

            // top level
            writer.WriteLine("<nav class=\"navbar navbar-inverse\">");
            writer.WriteLine("<ul class=\"nav navbar-nav\">");
            if (includeRoot)
            {
                if (rootLink.CompareToIgnoreWorkID(contentLink))
                {
                    writer.WriteLine("<li class=\"active\">");
                }
                else
                {
                    writer.WriteLine("<li>");
                }

                writer.WriteLine(html.PageLink(rootLink).ToHtmlString());
                writer.WriteLine("</li>");
            }

            // hämta ut alla barn från start

            contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();

            var topLevelPages = contentLoader.GetChildren<PageData>(rootLink);
            topLevelPages = FilterForVisitor.Filter(topLevelPages).OfType<PageData>().Where(x => x.VisibleInMenu);

            var currentBranch = contentLoader.GetAncestors(contentLink).Select(x => x.ContentLink).ToList();
            currentBranch.Add(contentLink);
            //skriv ut dom
            foreach (var topLevelPage in topLevelPages)
            {
                if (currentBranch.Any(x => x.CompareToIgnoreWorkID(topLevelPage.ContentLink)))
                {
                    writer.WriteLine("<li class=\"active\">");
                }
                else
                {
                    writer.WriteLine("<li>");
                }

                writer.WriteLine(html.PageLink(topLevelPage).ToHtmlString());
                writer.WriteLine("</li>");
            }
            //Close top level
            writer.WriteLine("</ul");
            writer.WriteLine("</nav>");
        }
Example #31
0
 /// <summary>
 /// Handles the Click event of the btnCancel 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 btnCancel_Click(object sender, EventArgs e)
 {
     if (hfGroupTypeId.Value.Equals("0"))
     {
         var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId);
         NavigateToPage(pageRef);
     }
     else
     {
         var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId);
         pageRef.Parameters.Add("CheckinTypeId", hfGroupTypeId.Value);
         NavigateToPage(pageRef);
     }
 }
        /// <summary>
        /// Prepares all links in a LinkItemCollection for output
        /// by filtering out inaccessible links and ensures all links are correct.
        /// </summary>
        /// <param name="linkItemCollection">The collection of links to prepare.</param>
        /// <param name="targetExternalLinksToNewWindow">True will set target to _blank if target is not specified for the LinkItem.</param>
        /// <returns>A prepared and filtered list of LinkItems</returns>
        public static IEnumerable <LinkItem> ToPreparedLinkItems(this LinkItemCollection linkItemCollection, bool targetExternalLinksToNewWindow)
        {
            var contentLoader = ServiceLocator.Current.GetInstance <IContentLoader>();

            if (linkItemCollection != null)
            {
                foreach (var linkItem in linkItemCollection)
                {
                    var url = new UrlBuilder(linkItem.Href);
                    if (PermanentLinkMapStore.ToMapped(url))
                    {
                        var pr = PermanentLinkUtility.GetContentReference(url);
                        if (!PageReference.IsNullOrEmpty(pr))
                        {
                            // page
                            var page = contentLoader.Get <PageData>(pr);
                            if (IsPageAccessible(page))
                            {
                                linkItem.Href = page.LinkURL;
                                yield return(linkItem);
                            }
                        }
                        else
                        {
                            // document
                            if (IsFileAccessible(linkItem.Href))
                            {
                                Global.UrlRewriteProvider.ConvertToExternal(url, null, System.Text.Encoding.UTF8);
                                linkItem.Href = url.Path;
                                yield return(linkItem);
                            }
                        }
                    }
                    else if (!linkItem.Href.StartsWith("~"))
                    {
                        // external
                        if (targetExternalLinksToNewWindow && string.IsNullOrEmpty(linkItem.Target))
                        {
                            linkItem.Target = "_blank";
                        }
                        if (linkItem.Href.StartsWith("mailto:") || linkItem.Target == "null")
                        {
                            linkItem.Target = string.Empty;
                        }
                        yield return(linkItem);
                    }
                }
            }
        }
Example #33
0
        public LinkViewModel CreateLinkViewModel(PageReference linkReference, string displayText)
        {
            if (linkReference == null)
            {
                return(null);
            }

            var linkViewModel = new LinkViewModel
            {
                Url         = GetFriendlyUrl(linkReference),
                DisplayText = displayText
            };

            return(linkViewModel);
        }
Example #34
0
        /// <summary>
        /// Gets the page by page reference.
        /// </summary>
        /// <param name="reference">The reference.</param>
        /// <returns></returns>
        protected PageData GetPage(PageReference reference)
        {
            if (PageReference.IsNullOrEmpty(reference))
            {
                return(null);
            }

            PageBase pageBase = (Page as PageBase);

            if (pageBase == null)
            {
                return(null);
            }
            return(pageBase.GetPage(reference));
        }
        PageReference CreateMonthContainer(string pageName, PageReference parent)
        {
            var existingContainerPage = GetContainerPageByName(pageName, parent);

            if (existingContainerPage == null)
            {
                var parentContentReference = _contentRepository.Get <ContainerPageType>(parent);
                var containerPage          = _contentRepository.GetDefault <ContainerPageType>(parentContentReference.ContentLink);
                containerPage.Name = pageName;
                _contentRepository.Save(containerPage, SaveAction.Publish, AccessLevel.NoAccess);
                _logger.Information($"Creating year container for month: {pageName}");
                return(containerPage.ContentLink.ToPageReference());
            }
            return(existingContainerPage.ContentLink.ToPageReference());
        }
Example #36
0
 /// <summary>
 /// Gets a page reference pointing out the root page for the page collection to toggle visibility for.
 /// It looks at <see cref="PageLink"/> property and <see cref="PageLinkProperty"/> in named order to find a <see cref="PageReference"/>.
 /// </summary>
 /// <returns>A <see cref="PageReference"/>; or <c>null</c> if none has been set.</returns>
 private PageReference GetListPageLink()
 {
     if (_pageLink == null)
     {
         if (!PageReference.IsNullOrEmpty(PageLink))
         {
             _pageLink = PageLink;
         }
         else if (!String.IsNullOrEmpty(PageLinkProperty))
         {
             _pageLink = CurrentPage[PageLinkProperty] as PageReference;
         }
     }
     return(_pageLink);
 }
Example #37
0
        /// <summary>
        /// Sets up a new workroom and redirects to that workroom when it's been set up.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CreateNewWorkroom_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                PageData newWorkroom = CopyAndSetUpWorkroomPage(PageReference.Parse(SelectTemplateDropDown.SelectedValue));

                CreateFolder(newWorkroom);

                SetUpAccessRights(newWorkroom);

                DeleteNotPublishedPageVersions(newWorkroom.PageLink);

                Response.Redirect(newWorkroom.LinkURL);
            }
        }
Example #38
0
        /// <returns>A link to the contanier of the PageList</returns>
        /// <remarks>Both SeeMoreText and PageLinkProperty must be set in order for the link to function correctly.</remarks>
        protected string GetContainerLink()
        {
            if (SeeMoreText != null && PageLinkProperty != null)
            {
                string _linkTag = "<a href=\"{0}\">{1}</a>";

                PageReference containerPage = CurrentPage[PageLinkProperty] as PageReference;
                if (containerPage != null)
                {
                    PageData page = GetPage(containerPage);
                    return(string.Format(_linkTag, HttpUtility.UrlPathEncode(page.LinkURL), SeeMoreText));
                }
            }
            return(string.Empty);
        }
Example #39
0
        public static PageData GetPage(int page)
        {
            PageReference pr = new PageReference(page);

            try {
                if (pr != null && pr != PageReference.EmptyReference)
                {
                    return(DataFactory.Instance.GetPage(pr));
                }
                return(null);
            }
            catch (PageNotFoundException pageNotFound) {
                return(null);
            }
        }
Example #40
0
        /// <summary>
        /// Handles the update of MainIntro and MainBody when an item in the news list is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void LinkButton_Command(Object sender, CommandEventArgs e)
        {
            NewsListPage newsListPage = Page as NewsListPage;

            if (newsListPage != null)
            {
                PageReference pageRef = new PageReference((string)e.CommandArgument);
                SelectedPageId = pageRef;
                if (newsListPage.CurrentDisplayMode != DisplayMode.View)
                {
                    newsListPage.CurrentDisplayMode = DisplayMode.View;
                }
                newsListPage.UpdateDisplayTexts(pageRef);
            }
        }
Example #41
0
        public static string ExternalUrlFromReference(this PageReference p)
        {
            var loader         = ServiceLocator.Current.GetInstance <IContentLoader>();
            var page           = loader.Get <PageData>(p);
            var pageUrlBuilder = new UrlBuilder(page.LinkURL);

            EPiServer.Global.UrlRewriteProvider.ConvertToExternal(pageUrlBuilder, page.LinkURL, UTF8Encoding.UTF8);
            var pageUrl = pageUrlBuilder.ToString();

            var uriBuilder = new UriBuilder(EPiServer.Web.SiteDefinition.Current.SiteUrl);

            uriBuilder.Path = pageUrl;

            return(uriBuilder.Uri.AbsoluteUri);
        }
        private IEnumerable <PageData> FindPages(CategoryListBlock currentBlock) //, Category categoryParameter)
        {
            IEnumerable <PageData> pages = null;

            var           pageRouteHelper = ServiceLocator.Current.GetInstance <PageRouteHelper>();
            PageData      currentPage     = pageRouteHelper.Page ?? contentLoader.Service.Get <PageData>(ContentReference.StartPage);
            PageReference listRoot        = currentPage.PageLink;

            if (currentPage.PageTypeName == typeof(CompareStartPage).GetPageType().Name)
            {
                pages = contentLoader.Service.GetChildren <CategoryPage>(currentPage.ContentLink);
            }

            return(pages ?? new List <PageData>());
        }
        public SiteSettingsPage UpdateSettingsPage(
            MetadataContainerReferences metadataContainerReferences,
            PageReference searchPageReference)
        {
            var clone = metadataContainerReferences.SettingsPage.CreateWritableClone() as SiteSettingsPage;

            clone.SearchPage = searchPageReference;

            var reference = WebsiteDependencies.ContentRepository.Save(
                clone,
                SaveAction.Publish,
                AccessLevel.NoAccess);

            return(reference != null ? clone : null);
        }
Example #44
0
        private TResult CreateChild <TResult>(
            PageReference parentLink, string pageName)
            where TResult : PageData
        {
            TResult child;
            var     resultPageTypeId = PageTypeResolver.Instance
                                       .GetPageTypeID(typeof(TResult));

            child = DataFactory.Instance.GetDefaultPageData(
                parentLink, resultPageTypeId.Value) as TResult;
            child.PageName = pageName;
            DataFactory.Instance.Save(
                child, SaveAction.Publish, AccessLevel.NoAccess);
            return(child);
        }
        public async Task <ActionResult> UpdateSocialSecurityNumber(HandleSignInInformationPage currentPage,
                                                                    FormCollection collection)
        {
            if (SiteUser == null)
            {
                return(HttpNotFound());
            }

            var socialSecurityNumber = collection["SocialSecurityNumber"];
            var regex = new Regex(@"^([0-9]{12})$");

            if (!regex.IsMatch(socialSecurityNumber))
            {
                TempData["SocialNumberInvalid"] = "Den personnummer är inte giltigt.";
            }
            else
            {
                var result = await _securityRepository.UpdateSocialSecurityNumberAsync(SiteUser.UserName, socialSecurityNumber);

                if (result)
                {
                    //var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
                    var startPage = _contentRepo.Get <StartPage>(ContentReference.StartPage);
                    if (startPage == null)
                    {
                        return(RedirectToAction("Index", new { node = currentPage.ContentLink }));
                    }
                    if (PageReference.IsNullOrEmpty(startPage.SettingsPage))
                    {
                        return(RedirectToAction("Index", new { node = currentPage.ContentLink }));
                    }

                    var settingPage = _contentRepo.Get <SettingsPage>(startPage.SettingsPage);

                    if (settingPage == null)
                    {
                        return(RedirectToAction("Index", new { node = currentPage.ContentLink }));
                    }

                    TempData["UpdatePersonNumberSuccess"] = true;
                    return(RedirectToAction("Index", new { node = settingPage.MyAccountLink }));
                }

                TempData["SocialNumberInvalid"] = "Det går inte att uppdatera personnummer. Var god försök igen!";
            }

            return(RedirectToAction("Index", new { node = currentPage.ContentLink }));
        }
Example #46
0
        public static string ExternalURLFromReference(this PageReference p)
        {
            PageData page = DataFactory.Instance.Get <PageData>(p);

            UrlBuilder pageURLBuilder = new UrlBuilder(page.LinkURL);

            Global.UrlRewriteProvider.ConvertToExternal(pageURLBuilder, page.PageLink, UTF8Encoding.UTF8);

            string pageURL = pageURLBuilder.ToString();

            UriBuilder uriBuilder = new UriBuilder(EPiServer.Web.SiteDefinition.Current.SiteUrl);

            uriBuilder.Path = pageURL;

            return(uriBuilder.Uri.AbsoluteUri);
        }
        public PageData CreateLanguageBranch(PageReference pageLink, ILanguageSelector selector, AccessLevel access)
        {
            PageData masterPage = GetPage(pageLink);

            LanguageSelectorContext ls = new LanguageSelectorContext(masterPage);

            selector.LoadLanguage(ls);
            PageData      pageData  = ConstructContentData <PageData>(masterPage.PageName, masterPage.PageLink, masterPage.ParentLink, ls.SelectedLanguage);
            List <String> languages = new List <string>(masterPage.PageLanguages);

            languages.Add(ls.SelectedLanguage);
            pageData.InitializeData(languages);
            pageData.PageGuid    = masterPage.PageGuid;
            pageData.PageLink.ID = masterPage.PageLink.ID;
            return(pageData);
        }
Example #48
0
        /// <summary>
        /// Performs a search by redirecting to the search page
        /// </summary>
        protected void PerformSearch(object sender, EventArgs e)
        {
            var searchPageLink = PageReference.StartPage.GetPage <StartPage>().SearchPageLink;

            if (PageReference.IsNullOrEmpty(searchPageLink))
            {
                throw new ConfigurationErrorsException("No search page specified in site settings, please specify the 'Search Page' property on the start page");
            }

            var searchPageRedirectUrl = searchPageLink.GetPage().LinkURL;

            // Add query string parameter containing the search keywords to the search page's URL
            searchPageRedirectUrl = UriSupport.AddQueryString(searchPageRedirectUrl, "q", SearchKeywords.Text.Trim());

            Response.Redirect(searchPageRedirectUrl);
        }
Example #49
0
        void Redirect(string url)
        {
            if (UserCanAdministrate)
            {
                PageReference self = new PageReference(RockPage.PageId);

                nbWarning.Text = string.Format(
                    "If you were not an Administrator you would have been redirected to <a href=\"{0}\">{0}</a><br />Click <a href=\"{1}?clearCache=me\">here</a> to clear your cache key or <a href=\"{1}?clearCache=block\">here</a> to clear all cache keys for this block.",
                    url, self.BuildUrl());
            }
            else
            {
                Response.Redirect(url);
                Response.End();
            }
        }
Example #50
0
        private EventRegistrationModel CreateEventRegistrationModel(EventPageBase currentPage, string contentLink)
        {
            var model               = new EventRegistrationModel(currentPage);
            var repository          = ServiceLocator.Current.GetInstance <IContentLoader>();
            var localizationService = ServiceLocator.Current.GetInstance <LocalizationService>();

            var           pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance <EPiServer.Web.Routing.PageRouteHelper>();
            PageReference currentPageLink = pageRouteHelper.PageLink;

            model.HostPageData   = pageRouteHelper.Page;
            model.EventPageBase  = currentPage;
            model.Sessions       = BVNetwork.Attend.Business.API.AttendSessionEngine.GetSessionsList(model.EventPageBase.PageLink);
            model.AvailableSeats = AttendRegistrationEngine.GetAvailableSeats(model.EventPageBase.PageLink);
            model.PriceText      = model.EventPageBase.EventDetails.Price > 0 ? model.EventPageBase.EventDetails.Price + " " + localizationService.GetString("/eventRegistrationTemplate/norwegianCurrencey") : localizationService.GetString("/eventRegistrationTemplate/freeOfCharge");
            return(model);
        }
        /// <summary>
        /// Gets the top page reference, i e page beneath the start page, starting at the specified page reference
        /// </summary>
        public static PageReference GetTopPage(this PageReference pageLink)
        {
            if (PageReference.IsNullOrEmpty(pageLink))
            {
                throw new NotSupportedException("Current top page cannot be retrieved without a starting point, and the specified page link was empty");
            }

            var page = pageLink.GetPage();

            while (!PageReference.IsNullOrEmpty(page.ParentLink) && !page.ParentLink.CompareToIgnoreWorkID(PageReference.RootPage) && !page.ParentLink.CompareToIgnoreWorkID(PageReference.StartPage))
            {
                page = page.ParentLink.GetPage();
            }

            return(page.PageLink);
        }
Example #52
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? competencyPersonProjectAssessmentId = this.PageParameter( pageReference, "competencyPersonProjectAssessmentId" ).AsInteger();
            if ( competencyPersonProjectAssessmentId != null )
            {
                breadCrumbs.Add( new BreadCrumb( "Assessment", pageReference ) );
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
        public PageData FindPageByName(DateTime now, PageData articlePage)
        {
            // init string
            string nameYearPage  = now.Year.ToString();
            string nameMonthPage = now.Month.ToString();
            string nameDayPage   = now.Day.ToString();

            PageReference oParent = new PageReference(articlePage.ContentLink.ID);

            PageReference oYear  = FindAPageOfPageParent(oParent, nameYearPage);
            PageReference oMonth = FindAPageOfPageParent(oYear, nameMonthPage);
            PageData      oDay   = FindPageByNameToPage(oMonth, nameDayPage);


            return(oDay);
        }
Example #54
0
        /// <summary>
        /// Gets the canonical URL for a page. If LinkType is FetchData the original page URL will be the canonical link.
        /// </summary>
        /// <param name="pageLink">The PageReference to get canonical URL from.</param>
        /// <param name="considerFetchDataFrom">Consider fetch data from setting in EPiServer.</param>
        /// <returns></returns>
        public static string GetCanonicalUrl(this PageReference pageLink, bool considerFetchDataFrom = true)
        {
            if (PageReference.IsNullOrEmpty(pageLink))
            {
                return(null);
            }

            PageData page = pageLink.GetPage();

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

            return(page.GetCanonicalUrl(considerFetchDataFrom));
        }
 private IHttpActionResult GetSinglePage(PageReference pageReference = null)
 {
     if (pageReference == null)
     {
         return(Content(HttpStatusCode.BadRequest, "Missing page reference."));
     }
     try
     {
         var catalog = contentRepository.Get <IContent>(pageReference);
         return(Json(JObject.Parse(catalog.ToJson())));
     }
     catch
     {
         return(Content(HttpStatusCode.NotFound, "Page not found"));
     }
 }
Example #56
0
        public CmsqlQueryExecutionResult ExecuteQueries(IEnumerable <CmsqlQuery> queries)
        {
            List <CmsqlQueryExecutionError> errors = new List <CmsqlQueryExecutionError>();
            List <PageData> result = new List <PageData>();

            CmsqlExpressionParser expressionParser = new CmsqlExpressionParser();

            foreach (CmsqlQuery query in queries)
            {
                ContentType contentType = _contentTypeRepository.Load(query.ContentType);
                if (contentType == null)
                {
                    errors.Add(new CmsqlQueryExecutionError($"Couldn't load content-type '{query.ContentType}'."));
                    continue;
                }

                CmsqlExpressionVisitorContext visitorContext = expressionParser.Parse(contentType, query.Criteria);
                if (visitorContext.Errors.Any())
                {
                    errors.AddRange(visitorContext.Errors);
                    continue;
                }

                PageReference searchStartNodeRef = GetStartSearchFromNode(query.StartNode);
                if (PageReference.IsNullOrEmpty(searchStartNodeRef))
                {
                    errors.Add(new CmsqlQueryExecutionError($"Couldn't process start node '{query.StartNode}'."));
                    continue;
                }

                foreach (PropertyCriteriaCollection propertyCriteriaCollection in visitorContext.GetCriteria())
                {
                    PageDataCollection foundPages = _pageCriteriaQueryService.FindPagesWithCriteria(
                        searchStartNodeRef,
                        propertyCriteriaCollection);
                    if (foundPages != null && foundPages.Any())
                    {
                        result.AddRange(foundPages);
                    }
                }
            }

            IEnumerable <ICmsqlQueryResult> pageDataCmsqlQueryResults =
                result.Select(p => new PageDataCmsqlQueryResult(p)).ToList();

            return(new CmsqlQueryExecutionResult(pageDataCmsqlQueryResults, errors));
        }
Example #57
0
        /// <summary>
        /// Returns pages of a specific page type
        /// </summary>
        /// <param name="pageLink"></param>
        /// <param name="recursive"></param>
        /// <param name="pageTypeId">ID of the page type to filter by</param>
        /// <returns></returns>
        public IEnumerable <PageData> FindPagesByPageType(PageReference pageLink, bool recursive, int pageTypeId)
        {
            var pageCriteriaQueryService = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>();
            var contentProviderManager   = ServiceLocator.Current.GetInstance <IContentProviderManager>();
            var contentLoader            = ServiceLocator.Current.GetInstance <IContentLoader>();

            if (ContentReference.IsNullOrEmpty(pageLink))
            {
                throw new ArgumentNullException("pageLink", "No page link specified, unable to find pages");
            }

            var pages = recursive
                        ? FindPagesByPageTypeRecursively(pageLink, pageTypeId)
                        : contentLoader.GetChildren <PageData>(pageLink);

            return(pages);
        }
Example #58
0
        protected PageData GetPageWithChecks(PageReference pagelink)
        {
            if (pagelink == PageReference.EmptyReference)
            {
                throw new ArgumentException("PageReference to mailpage is empty, no content to send.", "pagelink");
            }

            // Load page
            PageData mailPage = null;

            if (ContentRepository.Service.TryGet <PageData>(pagelink, out mailPage) == false)
            {
                throw new NullReferenceException("Cannot load newsletter page (" + pagelink.ToString() + ")");
            }

            return(mailPage);
        }
Example #59
0
        public static T GetPageData <T>(
            bool visibleInMenu            = true,
            bool isPublished              = true,
            bool userHasAccess            = true,
            bool isNotInWaste             = true,
            PageShortcutType shortcutType = PageShortcutType.Normal,
            int id               = 0,
            int parentId         = 0,
            CultureInfo language = null) where T : PageData
        {
            var securityDescriptor = new Mock <IContentSecurityDescriptor>();

            securityDescriptor.Setup(m => m.HasAccess(It.IsAny <IPrincipal>(), It.IsAny <AccessLevel>())).Returns(userHasAccess);

            if (language == null)
            {
                language = CultureInfo.CurrentCulture;
            }

            PageReference pageLink   = id > 0 ? new PageReference(id) : GetPageReference();
            PageReference parentLink = parentId > 0 ? new PageReference(parentId) : GetPageReference();

            var pageGuid = Guid.NewGuid();
            var instance = new Mock <T>();

            instance.SetupAllProperties();
            instance.Setup(m => m.VisibleInMenu).Returns(visibleInMenu);
            instance.Setup(m => m.Status).Returns(isPublished ? VersionStatus.Published : VersionStatus.NotCreated);
            instance.Setup(m => m.GetSecurityDescriptor()).Returns(securityDescriptor.Object);
            instance.Setup(m => m.ContentGuid).Returns(pageGuid);
            instance.Setup(m => m.ParentLink).Returns(parentLink);
            instance.Setup(m => m.ContentLink).Returns(pageLink);
            instance.Setup(m => m.Language).Returns(language);
            instance.Setup(m => m.Property).Returns(new PropertyDataCollection());
            instance.Setup(m => m.StaticLinkURL).Returns($"/link/{pageGuid:N}.aspx?id={pageLink.ID}");

            ContentReference.WasteBasket = new PageReference(1);
            if (!isNotInWaste)
            {
                instance.Setup(m => m.ContentLink).Returns(ContentReference.WasteBasket);
            }

            instance.Object.PageTypeName = typeof(T).Name;
            instance.Object.LinkType     = shortcutType;
            return(instance.Object);
        }
Example #60
0
        public PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
        {
            // Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
            if (pageLink.CompareToIgnoreWorkID(EntryRoot))
            {
                pageLink = CloneRoot;
            }
            else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
            {
                pageLink = new PageReference(pageLink.ID);
            }

            var pages = DataFactory.Instance.FindPagesWithCriteria(pageLink, criterias, languageBranch, selector);

            // Return cloned search result set
            return(new PageDataCollection(pages.Select(ClonePage)));
        }