private static MenuItem CreateMenuItem(PageData page, ContentReference currentContentLink, List<ContentReference> pagePath, IContentLoader contentLoader, Func<IEnumerable<PageData>, IEnumerable<PageData>> filter)
 {
     var menuItem = new MenuItem(page)
         {
             Selected = page.ContentLink.CompareToIgnoreWorkID(currentContentLink) ||
                        pagePath.Contains(page.ContentLink),
             HasChildren =
                 new Lazy<bool>(() => filter(contentLoader.GetChildren<PageData>(page.ContentLink)).Any())
         };
     return menuItem;
 }
 private static MenuItem CreateMenuItem(PageData page, ContentReference currentContentLink, ContentReference rootLink, IContentLoader contentLoader, Func<IEnumerable<PageData>, IEnumerable<PageData>> filter)
 {
     var menuItem = new MenuItem
     {
         Page = page,
         Selected = page.ContentLink.CompareToIgnoreWorkID(currentContentLink),
         HasChildren = new Lazy<bool>(() => filter(contentLoader.GetChildren<PageData>(page.ContentLink)).Any()),
         HasSelectedChildPage = new Lazy<bool>(() => HasSelectedChildPage(rootLink, currentContentLink, page))
     };
     return menuItem;
 }
Example #3
0
        public SearchFilter GetSearchFilterForNode(NodeContent nodeContent)
        {
            var configFilter = new SearchFilter
            {
                field        = BaseCatalogIndexBuilder.FieldConstants.Node,
                Descriptions = new Descriptions
                {
                    defaultLocale = _languageResolver.GetPreferredCulture().Name
                },
                Values = new SearchFilterValues()
            };

            var desc = new Description
            {
                locale = "en",
                Value  = _localizationService.GetString("/Facet/Category")
            };

            configFilter.Descriptions.Description = new[] { desc };

            var nodes      = _contentLoader.GetChildren <NodeContent>(nodeContent.ContentLink).ToList();
            var nodeValues = new SimpleValue[nodes.Count];
            var index      = 0;

            foreach (var node in nodes)
            {
                var val = new SimpleValue
                {
                    key          = node.Code,
                    value        = node.Code,
                    Descriptions = new Descriptions
                    {
                        defaultLocale = _languageResolver.GetPreferredCulture().Name
                    }
                };
                var desc2 = new Description
                {
                    locale = _languageResolver.GetPreferredCulture().Name,
                    Value  = node.DisplayName
                };
                val.Descriptions.Description = new[] { desc2 };

                nodeValues[index] = val;
                index++;
            }
            configFilter.Values.SimpleValue = nodeValues;
            return(configFilter);
        }
        public ActionResult Index2(StartPage currentPage)
        {
            ContentReference nodeRef = _refConv.GetContentLink("");
            var catalog = _contentLoader2.Get <CatalogContent>(nodeRef);

            ViewBag.Variants = _contentLoader2.GetChildren <ShirtVariation>(nodeRef).ToList();

            var cart   = LoadOrCreateCart();
            var totals = ((IOrderGroup)cart).GetTotal();

            ViewBag.Cart            = cart;
            ViewBag.Totals          = totals;
            ViewBag.LineItemsTotals = totals;//(cart.OrderForms.First())[cart.OrderForms.First().Shipments.First()];

            return(View(currentPage));
        }
        //TODO: Jämföra med Haglunds
        protected IPageViewModel <TPage> CreatePageViewModel <TPage>
            (TPage currentPage) where TPage : SitePageData
        {
            var viewModel = PageViewModel.Create(currentPage);

            viewModel.StartPage = loader.Get <StartPage>(ContentReference.StartPage);
            //FilterForVisitorn tar bort opubliserade pages + sidor som användaren inte har access till
            viewModel.MenuPages = FilterForVisitor.Filter(
                loader.GetChildren <SitePageData>(ContentReference.StartPage))
                                  .Cast <SitePageData>()
                                  .Where(page => page.VisibleInMenu);

            viewModel.Section = currentPage.ContentLink.GetSection();

            return(viewModel);
        }
Example #6
0
        public virtual LayoutModel CreateLayoutModel(ContentReference currentContentLink, RequestContext requestContext)
        {
            var startPageContentLink = SiteDefinition.Current.StartPage;

            if (currentContentLink.CompareToIgnoreWorkID(startPageContentLink))
            {
                startPageContentLink = currentContentLink;
            }

            var startPage = _contentLoader.Get <EpiserverStartPage>(startPageContentLink);

            return(new LayoutModel
            {
                Menu = _contentLoader.GetChildren <PageData>(startPage.ContentLink).Where(x => x.VisibleInMenu)
            });
        }
        private IEnumerable <ISettingsPage> GetSettingsPages(IContent content)
        {
            var rtnList   = new List <ISettingsPage>();
            var ancenters = Enumerable.Repeat(content, 1).Concat(_contentLoader.GetAncestors(content.ContentLink));

            foreach (var ancenter in ancenters)
            {
                if (ancenter is ISettingsPage settingsPage)
                {
                    rtnList.Add(settingsPage);
                }
                var settingsPages = _contentLoader.GetChildren <ISettingsPage>(ancenter.ContentLink);
                rtnList.AddRange(settingsPages);
            }
            return(rtnList);
        }
        private void UpdateListWithFeatured(ref List <ProductTileViewModel> productViewModels, GenericNode node)
        {
            if (!node.FeaturedProducts?.FilteredItems?.Any() ?? true)
            {
                return;
            }
            var market   = _currentMarket.GetCurrentMarket();
            var currency = _currencyService.GetCurrentCurrency();
            var index    = 0;

            foreach (var item in node.FeaturedProducts.FilteredItems)
            {
                var content = item.GetContent();
                if (content is EntryContentBase featuredEntry)
                {
                    if (productViewModels.Any(x => x.Code.Equals(featuredEntry.Code)))
                    {
                        productViewModels.RemoveAt(productViewModels.IndexOf(productViewModels.First(x => x.Code.Equals(featuredEntry.Code))));
                    }
                    else
                    {
                        productViewModels.RemoveAt(productViewModels.IndexOf(productViewModels.Last()));
                    }

                    productViewModels.Insert(index, featuredEntry.GetProductTileViewModel(market, currency, true));
                    index++;
                }
                else if (content is GenericNode featuredNode)
                {
                    foreach (var nodeEntry in _contentLoader.GetChildren <EntryContentBase>(content.ContentLink)
                             .Where(x => !(x is VariationContent))
                             .Take(featuredNode.PartialPageSize))
                    {
                        if (productViewModels.Any(x => x.Code.Equals(nodeEntry.Code)))
                        {
                            productViewModels.RemoveAt(productViewModels.IndexOf(productViewModels.First(x => x.Code.Equals(nodeEntry.Code))));
                        }
                        else
                        {
                            productViewModels.RemoveAt(productViewModels.IndexOf(productViewModels.Last()));
                        }
                        productViewModels.Insert(index, nodeEntry.GetProductTileViewModel(market, currency, true));
                        index++;
                    }
                }
            }
        }
        public IList <IPriceDetailValue> List(ContentReference catalogContentReference)
        {
            var contentToFetchPrices = new List <EntryContentBase>();
            var catalogContentItem   = _contentLoader.Get <CatalogContentBase>(catalogContentReference);

            if (catalogContentItem == null)
            {
                return(Enumerable.Empty <IPriceDetailValue>().ToList());
            }
            else if (catalogContentItem is VariationContent)
            {
                contentToFetchPrices.Add(catalogContentItem as VariationContent);
            }
            else if (catalogContentItem is ProductContent)
            {
                contentToFetchPrices.Add(catalogContentItem as ProductContent);
            }
            else if (catalogContentItem is NodeContent)
            {
                contentToFetchPrices.AddRange(_contentLoader.GetChildren <EntryContentBase>(catalogContentItem.ContentLink));
            }
            else if (catalogContentItem is BundleContent)
            {
                var bundleContent = catalogContentItem as BundleContent;
                contentToFetchPrices.AddRange(_contentLoader.GetItems(bundleContent.GetEntries(_relationRepository),
                                                                      catalogContentItem.Language).OfType <EntryContentBase>());
            }
            else if (catalogContentItem is PackageContent)
            {
                var packageContent = catalogContentItem as PackageContent;
                contentToFetchPrices.AddRange(_contentLoader.GetItems(packageContent.GetEntries(_relationRepository),
                                                                      catalogContentItem.Language).OfType <EntryContentBase>());
            }

            //Get linked variants for any products in our fetch list and add them to the list
            var variants = new List <EntryContentBase>();

            foreach (var content in contentToFetchPrices)
            {
                variants.AddRange(GetAttachedVariants(content));
            }

            contentToFetchPrices.AddRange(variants);

            return(InMemoryPriceDatabase.Prices.Where(x => contentToFetchPrices.Select(c => c.Code).Contains(x.Value.CatalogKey.CatalogEntryCode))
                   .Select(x => x.Value).ToList());
        }
        private Dictionary <StartPage, IEnumerable <SitePageData> > GetStartPagesWithDescendants()
        {
            var dictionary = new Dictionary <StartPage, IEnumerable <SitePageData> >();
            var startPages = _contentLoader.GetChildren <StartPage>(SiteDefinition.Current.RootPage, new LoaderOptions {
                LanguageLoaderOption.MasterLanguage()
            });

            foreach (var startPage in startPages)
            {
                var descendants = _contentLoader.GetDescendents(startPage.ContentLink).ToSitePageData().Where(p =>
                                                                                                              !(p.Robots is null) && !p.Robots.ToLower().Contains("noindex") && !(p is IExcludeFromSiteMap));

                dictionary.Add(startPage, descendants);
            }

            return(dictionary);
        }
        private IEnumerable <MenuItem> GetMenuItemsRecursive(ContentReference contentLink)
        {
            var publishedFilter = new FilterPublished();
            var accessFilter    = new FilterAccess();

            var menuItems = _contentLoader
                            .GetChildren <BasePageData>(contentLink)
                            .Where(p => p.VisibleInSiteMap && !publishedFilter.ShouldFilter(p) && !accessFilter.ShouldFilter(p))
                            .Select(p => new MenuItem
            {
                Name        = p.Name,
                ContentLink = p.ContentLink,
                Children    = GetMenuItemsRecursive(p.ContentLink)
            });

            return(menuItems);
        }
        public ActionResult Index(StartPage currentPage)
        {
            var model = new StartPageViewModel
            {
                CurrentPage = currentPage,
                Layout      = layoutFactory.BuildRootLayout(currentPage)
            };

            model.ChildPages = loader.GetChildren <PageData>(currentPage.ContentLink)
                               .Filter(new FilterAccess())
                               .Filter(new FilterPublished())
                               .Filter(new FilterTemplate())
                               .ToList();


            return(View(model));
        }
Example #13
0
        public static void RenderTopNavigation(this HtmlHelper html,
                                               PageReference rootLink       = null,
                                               ContentReference contentLink = null,
                                               bool includeRoot             = true,
                                               IContentLoader contentLoader = null
                                               )
        {
            rootLink = rootLink ?? ContentReference.StartPage;

            contentLink = contentLink ?? html.ViewContext.RequestContext.GetContentLink();

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

            var topLevelPages = contentLoader.GetChildren <PageData>(rootLink);
            var urlResolver   = ServiceLocator.Current.GetInstance <UrlResolver>();

            var writer = html.ViewContext.Writer;

            writer.WriteLine("");
            writer.WriteLine("<nav class='navbar navbar-expand-lg navbar-light bg-light'>");
            writer.WriteLine("<a class='navbar-brand' href='/'>STOCK</a>");
            writer.WriteLine("<button class='navbar-toggler' type='button' data-toggle='collapse' data-target='#navbarSupportedContent' aria-controls='navbarSupportedContent' aria-expanded='false' aria-label='Toggle navigation'>");
            writer.WriteLine("<span class='navbar-toggler-icon'></span>");
            writer.WriteLine("</button>");

            writer.WriteLine("<div class='collapse navbar-collapse' id='navbarSupportedContent'>");
            writer.WriteLine("<ul class='navbar-nav mr-auto'>");

            if (includeRoot)
            {
                writer.WriteLine("<li class='nav-item'>");
                writer.WriteLine("<a class='nav-link' href='#'>" + contentLoader.Get <PageData>(rootLink).Name + "<span class='sr-only'>(current)</span></a>");
                writer.WriteLine("</li>");
            }

            foreach (var topLevelPage in topLevelPages)
            {
                writer.WriteLine("<li class='nav-item'>");
                writer.WriteLine("<a class='nav-link' href='" + urlResolver.GetUrl(topLevelPage) + "'>" + topLevelPage.Name + "</a>");
                writer.WriteLine("</li>");
            }
            writer.WriteLine("</ul>");
            writer.WriteLine("</div>");
            writer.WriteLine("</nav>");
        }
        public override ActionResult Index(ListingBlock currentBlock)
        {
            var viewModel = new ListingBlockViewModel
            {
                Heading = currentBlock.Heading
            };

            if (currentBlock.ShowChildrenOfThisPage != null)
            {
                IEnumerable <PageData> allChildren      = _loader.GetChildren <PageData>(currentBlock.ShowChildrenOfThisPage);
                IEnumerable <IContent> filteredChildren = FilterForVisitor.Filter(allChildren);

                viewModel.Pages = filteredChildren.Cast <PageData>()
                                  .Where(p => p.VisibleInMenu);
            }

            return(PartialView(viewModel));
        }
Example #15
0
        private SitePageSettings GetSitePageSettings()
        {
            var settingsPage = new SitePageSettings();

            if (SiteDefinition.Current.StartPage == ContentReference.EmptyReference)
            {
                return(settingsPage);
            }

            var settingsPages = _contentLoader.GetChildren <SitePageSettings>(SiteDefinition.Current.StartPage).ToList();

            if (settingsPages.Any())
            {
                settingsPage = settingsPages.FirstOrDefault();
            }

            return(settingsPage);
        }
        private static void RenderFooterText(StringBuilder stringBuilder, SitePageData page, IContentLoader loader)
        {
            stringBuilder.Append($"{CreateLink(page)}");
            var childPages = FilterForVisitor
                             .Filter(loader.GetChildren <SitePageData>(page.ContentLink))
                             .Cast <SitePageData>().Where(p => p.VisibleInMenu);

            if (childPages != null && childPages.Count() > 0)
            {
                stringBuilder.Append("<ul>");
                foreach (var childPage in childPages)
                {
                    stringBuilder.Append("<li>");
                    RenderFooterText(stringBuilder, childPage, loader);
                    stringBuilder.Append("</li>");
                }
                stringBuilder.Append("</ul>");
            }
        }
Example #17
0
        public IEnumerable <IStatisticItem> GetStatisticItems(ContentReference rootContentReference)
        {
            var rootBlogCategory = _categoryRepository.Get("Blog Category");

            if (rootBlogCategory == null)
            {
                return(new List <IStatisticItem>());
            }
            var categories = rootBlogCategory.Categories.Select(category => category.Name).ToList();
            var pageDatas  = _contentLoader.GetChildren <IHaveCategory>(rootContentReference);

            return((from category in categories
                    let count = pageDatas.Count(pageData => string.Equals(pageData.BlogCategory, category, StringComparison.InvariantCultureIgnoreCase))
                                select new StatisticItem
            {
                Name = category,
                Count = count
            }).ToList());
        }
        /// <summary>
        /// Creates a new MenuItem from provided PageData.
        /// </summary>
        private static MenuItem CreateMenuItem(
            PageData page,
            ContentReference currentContentLink,
            List <ContentReference> pagePath,
            IContentLoader contentLoader,
            Func <IEnumerable <PageData>, IEnumerable <PageData> > filter)
        {
            var selected           = page.ContentLink.CompareToIgnoreWorkID(currentContentLink);
            var ancestorOfSelected = !selected && pagePath.Contains(page.ContentLink);

            var menuItem = new MenuItem(page)
            {
                Selected           = selected,
                AncestorOfSelected = ancestorOfSelected,
                HasChildren        = new Lazy <bool>(() => filter(
                                                         contentLoader.GetChildren <PageData>(page.ContentLink)).Any())
            };

            return(menuItem);
        }
Example #19
0
        public async Task Index(ContentReference rootContentLink, IndexContentRequest indexContentRequest)
        {
            if (indexContentRequest.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (indexContentRequest.IgnoreContent.Contains(rootContentLink))
            {
                return;
            }

            if (indexContentRequest.VisitedContent.Contains(rootContentLink))
            {
                return;
            }

            if (indexContentRequest.Statistics.Exceptions.Count >= indexContentRequest.ExceptionThreshold)
            {
                return;
            }

            try
            {
                await IndexLanguageVersions(rootContentLink, indexContentRequest);

                indexContentRequest.VisitedContent.Add(rootContentLink);
            }
            catch (Exception e)
            {
                indexContentRequest.Statistics.FailedContentReferences.Add(rootContentLink);
                indexContentRequest.Statistics.Exceptions.Add(e);
            }

            var children = _contentLoader.GetChildren <PageData>(rootContentLink);

            foreach (var child in children)
            {
                await Index(child.ContentLink, indexContentRequest);
            }
        }
Example #20
0
        public ActionResult Index()
        {
            var items = _contentLoader
                        .GetChildren <SBRobotsTxt>(ContentReference.StartPage, new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            });

            var content = "User-agent: *" + Environment.NewLine + "Disallow: /episerver";

            if (items != null)
            {
                var robotTxtPages = items.ToList();

                if (robotTxtPages.Any())
                {
                    content = robotTxtPages.First().RobotsContent;
                }
            }

            return((ActionResult)this.Content(content, "text/plain", Encoding.UTF8));
        }
Example #21
0
        public ActionResult Index(NewsDetailPage currentPage)
        {
            ViewBag.SubscriptionText        = SiteSettingsHandler.Instance.SiteSettings.SubscriptionText + "";
            ViewBag.SubscriptionDescription = SiteSettingsHandler.Instance.SiteSettings.SubscriptionDescription + "";
            ViewBag.MailChimpApiKey         = SiteSettingsHandler.Instance.SiteSettings.MailChimpApiKey + "";
            ViewBag.MailChimpListId         = SiteSettingsHandler.Instance.SiteSettings.MailChimpListId + "";
            ViewBag.SubscriptionUrlPost     = SiteSettingsHandler.Instance.SiteSettings.SubcriptionUrlPost + "";
            var newsDetailViewModel = new NewsDetailViewModel(currentPage)
            {
                RelatedNewsDetailPages =
                    _contentLoader.GetChildren <NewsDetailPage>(currentPage.ParentLink)
                    .Where(
                        x =>
                        x != currentPage && DateTime.Compare(x.StartPublish, DateTime.Now) < 0 &&
                        DateTime.Compare(x.StopPublish, DateTime.Now) > 0)
                    .OrderByDescending(x => x.StartPublish)
                    .Take(3)
            };

            return(View(newsDetailViewModel));
        }
Example #22
0
        public IEnumerable <IStatisticItem> GetStatisticItems(ContentReference rootContentReference)
        {
            var pageDatas      = _contentLoader.GetChildren <IHaveTag>(rootContentReference);
            var tags           = _tagRepository.GetAllTags();
            var statisticItems = new List <StatisticItem>();

            if (tags == null)
            {
                return(statisticItems);
            }
            foreach (var tag in tags)
            {
                var count = (from pageData in pageDatas where !string.IsNullOrEmpty(pageData.Tags) select pageData.Tags.Split(',')).Count(pageDataTags => pageDataTags.Any(x => string.Equals(x, tag.Name, StringComparison.InvariantCultureIgnoreCase)));
                statisticItems.Add(new StatisticItem
                {
                    Name  = tag.Name,
                    Count = count
                });
            }
            return(statisticItems);
        }
Example #23
0
        private CategoriesFilterViewModel GetCategoriesFilter(IContent currentContent, string query)
        {
            var bestBets         = new BestBetRepository().List().Where(i => i.PhraseCriterion.Phrase.CompareTo(query) == 0);
            var ownStyleBestBets = bestBets.Where(i => i.BestBetSelector is CommerceBestBetSelector && i.HasOwnStyle);
            var catalogId        = 0;
            var node             = currentContent as NodeContent;

            if (node != null)
            {
                catalogId = node.CatalogId;
            }
            var catalog = _contentLoader.GetChildren <CatalogContentBase>(_referenceConverter.GetRootLink())
                          .FirstOrDefault(x => catalogId == 0 || x.CatalogId == catalogId);

            if (catalog == null)
            {
                return(new CategoriesFilterViewModel());
            }

            var viewModel = new CategoriesFilterViewModel();
            var nodes     = _findClient.Search <NodeContent>()
                            .Filter(x => x.ParentLink.ID.Match(catalog.ContentLink.ID))
                            .FilterForVisitor()
                            .GetContentResult();

            foreach (var nodeContent in nodes)
            {
                var nodeFilter = new CategoryFilter
                {
                    DisplayName = nodeContent.DisplayName,
                    Url         = _urlResolver.GetUrl(nodeContent.ContentLink),
                    IsActive    = currentContent != null && currentContent.ContentLink == nodeContent.ContentLink,
                    IsBestBet   = ownStyleBestBets.Any(x => ((CommerceBestBetSelector)x.BestBetSelector).ContentLink.ID == nodeContent.ContentLink.ID)
                };
                viewModel.Categories.Add(nodeFilter);

                GetChildrenNode(currentContent, nodeContent, nodeFilter, ownStyleBestBets);
            }
            return(viewModel);
        }
        public ActionResult Index(ShoppingCategoryPage currentPage)
        {
            var model = new ShoppingCategoryViewModel(currentPage);

            model.Language = currentPage.Language.Name;

            if (currentPage.CatalogNodes != null)
            {
                model.CommerceCategoryIds = GetCommerceNodeIds(currentPage);
            }

            model.NumberOfProductsToShow = currentPage.NumberOfProductsToShow > 0 ? currentPage.NumberOfProductsToShow : DefaultNumProductsInList;

            if (currentPage.ParentLink != null)
            {
                var languageSelector         = new LanguageSelector(model.Language);
                var parent                   = _contentLoader.Get <IContent>(currentPage.ParentLink, languageSelector);
                ShoppingCategoryPage topNode = null;

                while (!(parent is HomePage))
                {
                    topNode = parent as ShoppingCategoryPage;
                    parent  = _contentLoader.Get <IContent>(parent.ParentLink, languageSelector);
                }

                if (topNode == null && parent is HomePage)
                {
                    topNode = currentPage;
                    model.CommerceCategoryIds = string.Empty;
                }
                if (topNode != null)
                {
                    model.ParentName               = topNode.Name;
                    model.CategoryPages            = _contentLoader.GetChildren <ShoppingCategoryPage>(topNode.ContentLink);
                    model.CommerceRootCategoryName = GetCommerceNodeNames(topNode);
                }
            }

            return(View(model));
        }
Example #25
0
        private bool AddEntries(ZipArchive archive, ContentReference contentLink, string folderName)
        {
            var result = false;

            var children = _contentLoader.GetChildren <IContent>(contentLink).ToList();

            foreach (var content in children)
            {
                if (content is ContentFolder)
                {
                    result = AddEntries(archive, content.ContentLink, folderName + content.Name + "/") || result;
                }
                else if (content is IContentMedia)
                {
                    result = true;
                    var contentMedia = content as IContentMedia;
                    var routable     = content as IRoutable;
                    var extension    = Path.GetExtension(content.Name);
                    if (string.IsNullOrEmpty(extension))
                    {
                        extension = Path.GetExtension(routable.RouteSegment);
                    }
                    var zipEntry = archive.CreateEntry(folderName + Path.GetFileNameWithoutExtension(content.Name) + extension);

                    var bytes = contentMedia.BinaryData.ReadAllBytes();
                    using (var writer = new StreamWriter(zipEntry.Open()))
                    {
                        using (var m = new MemoryStream())
                        {
                            m.Write(bytes, 0, bytes.Length);
                            m.Seek(0, SeekOrigin.Begin);
                            m.WriteTo(writer.BaseStream);
                        }
                    }
                }
            }

            return(result);
        }
        public ActionResult Index()
        {
            // Note: the GetRoutedData extension method uses the partial router to
            // convert a URL segment into a Category instance.
            var category = Request.RequestContext.GetRoutedData <Category>();

            var categoriesPages = contentLoader
                                  .GetChildren <CategoriesPage>(ContentReference.StartPage);

            CategoriesPage currentPage = null;

            if (categoriesPages.Count() > 0)
            {
                currentPage = categoriesPages.First();
            }

            var model = PageViewModel.Create(currentPage);

            model.CurrentPage.NorthwindCategory = category;

            return(View("~/Features/NorthwindPartialRouter/Category.cshtml", model));
        }
        private IEnumerable <PageData> FindPages(CategoryListBlock currentBlock) //, Category categoryParameter)
        {
            IEnumerable <PageData> pages = null;

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

            if (currentPage.PageTypeName == typeof(CompareStartPage).GetPageType().Name)
            {
                //var categoryRepository = ServiceLocator.Current.GetInstance<CategoryRepository>();
                //var category = CategoryHelper.FindCompareCategory(categoryRepository, currentPage.Name);

                //if (category != null)
                //{
                //var listRoot = currentBlock.Root ?? currentPage.ContentLink.ToPageReference();
                //var compareStartPage = contentLoader.Get<CompareStartPage>(currentPage.ContentLink); //GetCompareStartPage(currentPage);


                //if (compareStartPage != null)
                //{
                pages = contentLoader.GetChildren <CategoryPage>(currentPage.ContentLink);

                /*if (ouFolderPage != null)
                 * {
                 *  var ouPages = contentLoader.GetChildren<OrganisationalUnitPage>(ouFolderPage.ContentLink).Where(o => o.Category.Contains(category.ID)).ToList();
                 *  if (ouPages != null && ouPages.Count > 0)
                 *  {
                 *      pages = ouPages;
                 *  }
                 * }*/
                //contentLoader.GetChildren<PageData>(compareStartPage.ContentLink.ToPageReference());
                //PageReference ouPage = CompareInitialization.GetOrganisationalUnitsPageRef(compareStartPage, contentRepository);

                //}
            }

            return(pages ?? new List <PageData>());
        }
Example #28
0
        // this method must convert a Category entity into a partial URL path
        // e.g. the category named "Meat/Poultry"
        // into the URL "/Northwind/Meat_Poultry"
        public PartialRouteData GetPartialVirtualPath(Category content,
                                                      string language, RouteValueDictionary routeValues,
                                                      RequestContext requestContext)
        {
            var northwindPages = contentLoader
                                 .GetChildren <CategoriesPage>(ContentReference.StartPage);

            // the base of the URL will be the URL for the CategoriesPage instance
            var basePath = ContentReference.EmptyReference;

            if (northwindPages.Count() > 0)
            {
                basePath = northwindPages.First().ContentLink;
            }

            var partialRouteData = new PartialRouteData
            {
                BasePathRoot       = basePath,
                PartialVirtualPath = content.CategoryName.Replace('/', '_') + "/"
            };

            return(partialRouteData);
        }
        private IEnumerable <CalendarEventPage> GetEvents(int blockId)
        {
            var currentBlock = _contentLoader.Get <CalendarBlock>(new ContentReference(blockId));
            IEnumerable <CalendarEventPage> events;
            var root = currentBlock.EventsRoot;

            if (currentBlock.Recursive)
            {
                events = root.GetAllRecursively <CalendarEventPage>();
            }
            else
            {
                events = _contentLoader.GetChildren <CalendarEventPage>(root);
            }

            if (currentBlock.CategoryFilter != null && currentBlock.CategoryFilter.Any())
            {
                events = events.Where(x => x.Category.Intersect(currentBlock.CategoryFilter).Any());
            }

            events.Take(currentBlock.Count);

            return(events);
        }
Example #30
0
        public override IViewComponentResult Invoke(NavigationBlock currentBlock)
        {
            var rootNavigation = currentBlock.RootPage as ContentReference;

            if (ContentReference.IsNullOrEmpty(currentBlock.RootPage))
            {
                rootNavigation = _pageRouteHelper.ContentLink;
            }

            var childPages = _contentLoader.GetChildren <PageData>(rootNavigation);
            var model      = new NavigationBlockViewModel(currentBlock);

            if (childPages != null && childPages.Count() > 0)
            {
                var linkCollection = new List <NavigationItem>();
                foreach (var page in childPages)
                {
                    if (page.VisibleInMenu)
                    {
                        linkCollection.Add(new NavigationItem(page, Url));
                    }
                }

                model.Items.AddRange(linkCollection.Where(x => !string.IsNullOrEmpty(x.Url)));
            }

            if (string.IsNullOrEmpty(currentBlock.Heading))
            {
                model.Heading = _pageRouteHelper.Page.Name;
            }

            var view = View(model);

            view.ViewName = "~/Features/Blocks/NavigationBlock/NavigationBlock.cshtml";
            return(view);
        }
        public override ActionResult Index(CustomerListingBlock currentBlock)
        {
            var viewmodel = new ListingBlockViewModel

            {
                Heading = currentBlock.Heading
            };

            if (currentBlock.ChildrenOfThisPage != null)
            {
                IEnumerable <PageData> children = loader.GetChildren <PageData>(
                    currentBlock.ChildrenOfThisPage);
                // Remove pages:
                // 1. that are not published
                // 2. that the visitor does not have Read access to
                // 3. that do not have a page template
                IEnumerable <IContent> filteredChildren =
                    FilterForVisitor.Filter(children);
                // 4. that do not have "Display in navigation" selected
                viewmodel.Pages = filteredChildren.Cast <PageData>()
                                  .Where(page => page.VisibleInMenu);
            }
            return(PartialView(viewmodel));
        }
        public static IEnumerable <T> GetPublishedChildren <T>(this IContentLoader contentLoader, ContentReference contentLink) where T : IContent
        {
            var publishedStateAccessor = ServiceLocator.Current.GetInstance <IPublishedStateAssessor>();

            return(contentLoader.GetChildren <T>(contentLink).Where(x => publishedStateAccessor.IsPublished(x, PublishedStateCondition.None)));
        }
 public static IEnumerable<PageData> GetSiblings(this PageData pageData, IContentLoader contentLoader)
 {
     var filter = new FilterContentForVisitor();
     return contentLoader.GetChildren<PageData>(pageData.ParentLink).Where(page => !filter.ShouldFilter(page));
 }
    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 elements
      writer.WriteLine("<nav class=\"navbar navbar-inverse\">");
      writer.WriteLine("<ul class=\"nav navbar-nav\">");

      if (includeRoot)
      {
        //Link to the root page
        if (rootLink.CompareToIgnoreWorkID(contentLink))
        {
          writer.WriteLine("<li class=\"active\">");
        }
        else
        {
          writer.WriteLine("<li>");
        }
        writer.WriteLine(
          html.PageLink(rootLink).ToHtmlString());
        writer.WriteLine("</li>");
      }

      //Retrieve and filter the root pages children
      contentLoader = contentLoader ??
        ServiceLocator.Current.GetInstance<IContentLoader>();
      var topLevelPages = contentLoader
        .GetChildren<PageData>(rootLink);
      topLevelPages = FilterForVisitor.Filter(topLevelPages)
        .OfType<PageData>()
        .Where(x => x.VisibleInMenu);

      //Retrieve the "path" from the current page up to the
      //root page in the content tree in order to check if
      //a link should be highlighted.
      var currentBranch = contentLoader.GetAncestors(contentLink)
        .Select(x => x.ContentLink)
        .ToList();
      currentBranch.Add(contentLink);

      //Link to the root pages children
      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 element
      writer.WriteLine("</ul>");
      writer.WriteLine("</nav>");
    }
    private static void RenderSubNavigationLevel(
          HtmlHelper helper,
          ContentReference levelRootLink,
          IEnumerable<ContentReference> path,
          IContentLoader contentLoader)
    {
      //Retrieve and filter the pages on the current level
      var children = contentLoader.GetChildren<PageData>(levelRootLink);
      children = FilterForVisitor.Filter(children)
                                 .OfType<PageData>()
                                 .Where(x => x.VisibleInMenu);

      if (!children.Any())
      {
        //There's nothing to render on this level so we abort
        //in order not to write an empty ul element.
        return;
      }

      var writer = helper.ViewContext.Writer;

      //Open list element for the current level
      writer.WriteLine("<ul class=\"nav\">");

      //Project to an anonymous class in order to know
      //the index of each page in the collection when
      //iterating over it.
      var indexedChildren = children
        .Select((page, index) => new { index, page })
        .ToList();

      foreach (var levelItem in indexedChildren)
      {
        var page = levelItem.page;
        var partOfCurrentBranch = path.Any(x =>
          x.CompareToIgnoreWorkID(levelItem.page.ContentLink));

        if (partOfCurrentBranch)
        {
          //We highlight pages that are part of the current branch,
          //including the currently viewed page.
          writer.WriteLine("<li class=\"active\">");
        }
        else
        {
          writer.WriteLine("<li>");
        }
        writer.WriteLine(helper.PageLink(page).ToHtmlString());

        if (partOfCurrentBranch)
        {
          //The page is part of the current pages branch, 
          //so we render a level below it 
          RenderSubNavigationLevel(
            helper,
            page.ContentLink,
            path,
            contentLoader);
        }
        writer.WriteLine("</li>");
      }

      //Close list element
      writer.WriteLine("</ul>");
    }
        private static void RenderSubNavigationLevel(HtmlHelper helper, ContentReference levelRootLink,
            IEnumerable<ContentReference> path, IContentLoader contentLoader)
        {
            var children = contentLoader.GetChildren<PageData>(levelRootLink);
            children = FilterForVisitor.Filter(children).OfType<PageData>().Where(x => x.VisibleInMenu);

            if (!children.Any())
            {
                return;
            }

            var writer = helper.ViewContext.Writer;

            writer.WriteLine("<ul class=\"nav\">");

            var indexedChildren = children.Select((page, index) => new
            {
                index,
                page

            }).ToList();

            foreach (var levelItem in indexedChildren)
            {
                var page = levelItem.page;
                var partOfCurrentBranch = path.Any(x => x.CompareToIgnoreWorkID(levelItem.page.ContentLink));

                if (partOfCurrentBranch)
                {
                    writer.WriteLine("<li class=\"active\">");
                }
                else
                {

                    writer.WriteLine("<li>");
                }

                writer.WriteLine(helper.PageLink(page).ToHtmlString());

                if (partOfCurrentBranch)
                {
                    RenderSubNavigationLevel(helper, page.ContentLink, path, contentLoader);
                }

                writer.WriteLine("</li>");
            }

            writer.WriteLine("</ul>");
        }
        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>");
        }