示例#1
0
        protected virtual T CreateViewModel <T>(IContent currentContent, CommerceHomePage homePage, Customer.FoundationContact contact, bool isBookmarked)
            where T : CommerceHeaderViewModel, new()
        {
            var menuItems  = new List <MenuItemViewModel>();
            var menuCached = CacheManager.Get(homePage.ContentLink.ID + Constant.CacheKeys.MenuItems) as List <MenuItemViewModel>;

            if (menuCached != null)
            {
                menuItems = menuCached;
            }
            else
            {
                var menuItemBlocks = homePage.MainMenu?.FilteredItems.GetContentItems <MenuItemBlock>() ?? new List <MenuItemBlock>();
                menuItems = menuItemBlocks?
                            .Select(_ => new MenuItemViewModel
                {
                    Name       = _.Name,
                    ButtonText = _.ButtonText,
                    TeaserText = _.TeaserText,
                    Uri        = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                    {
                        ContextMode = ContextMode.Default
                    }),
                    ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                    ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                    ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                }).ToList() ?? new List <MenuItemViewModel>();

                var keyDependency = new List <string>();
                keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink)); // If The HomePage updates menu (remove MenuItems)

                foreach (var m in menuItemBlocks)
                {
                    keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey((m as IContent).ContentLink));
                }

                var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency);
                CacheManager.Insert(homePage.ContentLink.ID + Constant.CacheKeys.MenuItems, menuItems, eviction);
            }

            return(new T
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                Name = contact?.FirstName ?? "",
                IsBookmarked = isBookmarked,
                MenuItems = menuItems,
                LoginViewModel = new LoginViewModel
                {
                    ResetPasswordPage = homePage.ResetPasswordPage
                },
                RegisterAccountViewModel = new RegisterAccountViewModel
                {
                    Address = new AddressModel()
                },
                MobileNavigation = homePage.MobileNavigationPages,
            });
        }
示例#2
0
        public ActionResult ChangeCartItem(RequestParamsToCart param)
        {
            ModelState.Clear();
            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            if (WishList.Cart.GetAllLineItems().FirstOrDefault(x => x.Code == param.Code) == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NoContent, productName + " is not exist in the wishlist."));
            }

            _cartService.ChangeCartItem(WishList.Cart, 0, param.Code, param.Quantity, param.Size, param.NewSize);
            _orderRepository.Save(WishList.Cart);
            _trackingService.TrackWishlist(HttpContext);
            var          referencePages = _settingsService.GetSiteSettings <ReferencePageSettings>();
            WishListPage wishlistPage   = null;

            if (!referencePages?.WishlistPage.IsNullOrEmpty() ?? false)
            {
                wishlistPage = _contentLoader.Get <WishListPage>(referencePages.WishlistPage);
            }

            if (param.RequestFrom.Equals("axios", StringComparison.OrdinalIgnoreCase))
            {
                var viewModel = _cartViewModelFactory.CreateWishListViewModel(WishList.Cart, wishlistPage);
                return(PartialView("_WishlistListItem", viewModel));
            }

            return(Redirect(_urlResolver.GetUrl(wishlistPage)));
        }
示例#3
0
 private async Task <ProductViewModel> CreateProductViewModel(Product product)
 {
     return(new ProductViewModel
     {
         Product = product,
         Url = await _urlResolver.GetUrl(product),
     });
 }
        public ActionResult Index(ProjectListPage currentContent)
        {
            var allProjects = _contentLoader.GetChildren <ProjectPage.ProjectPage>(currentContent.ContentLink)
                              .Select(x => new ProjectTeaser(x.Title, BuildResponsiveImage(x.MainImage), x.Category
                                                             .Select(y => _categoryRepository.Get(y).Name)
                                                             .ToList(), _urlResolver.GetUrl(x.ContentLink)));

            return(View(new ProjectListPageViewModel(currentContent, allProjects.ToList())));
        }
        public async Task <IActionResult> Index(Product currentDocument)
        {
            var model = new ProductViewModel
            {
                Product = currentDocument,
                Url     = await _urlResolver.GetUrl(currentDocument)
            };

            return(View(model));
        }
示例#6
0
        public LinkItemGraphType(IUrlResolver urlResolver, IContentLoader contentLoader, IPermanentLinkMapper permanentLinkMapper)
        {
            Name = "LinkItem";

            Field <StringGraphType>("Attributes", resolve: x => JsonConvert.SerializeObject(x.Source.Attributes));
            Field <StringGraphType>("Href",
                                    arguments: new QueryArguments(
                                        new QueryArgument <BooleanGraphType>
            {
                DefaultValue = false,
                Name         = Constants.Arguments.ARGUMENT_ABSOLUTE_URL
            },
                                        new QueryArgument <BooleanGraphType>()
            {
                Name         = Constants.Arguments.ARGUMENT_ALLOWFALLBACK_LANG,
                Description  = "Allow Fallback Language",
                DefaultValue = true
            }
                                        ),
                                    resolve: x =>
            {
                var locale           = x.GetLocaleFromArgument();
                var absoluteUrl      = x.GetArgument <bool>(Constants.Arguments.ARGUMENT_ABSOLUTE_URL);
                var permanentLinkMap = permanentLinkMapper.Find(new UrlBuilder(x.Source.Href));

                if (permanentLinkMap == null)
                {
                    return(urlResolver.GetUrl(x.Source.Href));
                }

                var content = contentLoader
                              .Get <IContent>(
                    permanentLinkMap.ContentReference,
                    x.CreateLoaderOptionsFromAgruments()
                    );

                var localizable = content as ILocale;

                if (content != null && GraphTypeFilter.ShouldFilter(content))
                {
                    return(null);
                }

                if (localizable != null)
                {
                    return(permanentLinkMap.ContentReference.GetUrl(localizable.Language.Name, absoluteUrl));
                }

                return(urlResolver.GetUrl(x.Source.Href));
            });
            Field(x => x.Target);
            Field(x => x.Text);
            Field(x => x.Title);
        }
        public THeaderViewModel CreateHeaderViewModel <THeaderViewModel>(IContent currentContent, CmsHomePage homePage)
            where THeaderViewModel : HeaderViewModel, new()
        {
            var menuItems  = new List <MenuItemViewModel>();
            var menuCached = CacheManager.Get(homePage.ContentLink.ID + MenuCacheKey) as List <MenuItemViewModel>;

            if (menuCached != null)
            {
                menuItems = menuCached;
            }
            else
            {
                var menuItemBlocks = homePage.MainMenu?.FilteredItems.GetContentItems <MenuItemBlock>();
                menuItems = menuItemBlocks?
                            .Select(_ => new MenuItemViewModel
                {
                    Name       = _.Name,
                    ButtonText = _.ButtonText,
                    TeaserText = _.TeaserText,
                    Uri        = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                    {
                        ContextMode = ContextMode.Default
                    }),
                    ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                    ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                    ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                }).ToList() ?? new List <MenuItemViewModel>();

                var keyDependency = new List <string>();
                keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink)); // If The HomePage updates menu (remove MenuItems)

                foreach (var m in menuItemBlocks)
                {
                    keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey((m as IContent).ContentLink));
                }

                var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency);
                CacheManager.Insert(homePage.ContentLink.ID + MenuCacheKey, menuItems, eviction);
            }

            return(new THeaderViewModel
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                Name = PrincipalInfo.Current.Name,
                MenuItems = menuItems,
                MobileNavigation = homePage.MobileNavigationPages,
            });
        }
        private NewsCardDto Map(ContentAreaItem item)
        {
            if (!_contentLoader.TryGet(item.ContentLink, out IHasCardRendering cardRendering))
            {
                return(null);
            }

            return(new NewsCardDto
            {
                Title = cardRendering.Title,
                ImageUrl = _urlResolver.GetUrl(cardRendering.Image),
                Author = cardRendering.Author,
                LinkUrl = _urlResolver.GetUrl(cardRendering.ContentLink)
            });
        }
示例#9
0
        public void Add(Guid contentGuid)
        {
            var currentContact = CustomerContext.Current.CurrentContact;

            if (currentContact != null)
            {
                var contentReference = _permanentLinkMapper.Find(contentGuid).ContentReference;
                var contact          = new FoundationContact(currentContact);
                var bookmarkModel    = new BookmarkModel();
                if (_contentLoader.TryGet <IContent>(contentReference, out var content))
                {
                    bookmarkModel.ContentLink = contentReference;
                    bookmarkModel.ContentGuid = content.ContentGuid;
                    bookmarkModel.Name        = content.Name;
                    bookmarkModel.Url         = _urlResolver.GetUrl(content);
                }
                var contactBookmarks = contact.ContactBookmarks;
                if (contactBookmarks.FirstOrDefault(x => x.ContentGuid == bookmarkModel.ContentGuid) == null)
                {
                    contactBookmarks.Add(bookmarkModel);
                }
                contact.Bookmarks = JsonConvert.SerializeObject(contactBookmarks);
                contact.SaveChanges();
            }
        }
        public override ActionResult Index(ContentRecommendationsBlock currentBlock)
        {
            var request = new ContentRecommendationViewModel
            {
                ContentId  = CurrentPage.ContentGuid.ToString(),
                SiteId     = SiteDefinition.Current.Id.ToString(),
                LanguageId = CurrentPage.Language.Name,
                NumberOfRecommendations = currentBlock.NumberOfRecommendations
            };

            var model = new ContentRecommendationsBlockViewModel {
                ContentRecommendationItems = new List <ContentRecommendationItem>()
            };

            foreach (var item in Task.Run(async() => await _recommendationService.GetRecommendationContent(HttpContext, request)).Result)
            {
                var sitePageData = item.Content as FoundationPageData;
                if (sitePageData == null)
                {
                    continue;
                }
                model.ContentRecommendationItems.Add(new ContentRecommendationItem
                {
                    Content     = sitePageData,
                    ContentUrl  = _urlResolver.GetUrl(item.Content.ContentLink),
                    ContentType = _contentTypeRepository.Load(item.Content.ContentTypeID).Name
                }
                                                     );
            }

            return(PartialView("~/Features/Blocks/Views/ContentRecommendationsBlock.cshtml", model));
        }
 private string ResolveUrl(ContentReference contentLink, string language)
 {
     return(_urlResolver.GetUrl(contentLink, language, new UrlResolverArguments
     {
         ContextMode = GetContextMode()
     }));
 }
示例#12
0
        private string GetPathFromContentId(IUrlResolver contentUrlResolver, Uri request)
        {
            var contentReference = new ContentReference(RedirectRule.ContentId.Value);
            var newUrl           = contentUrlResolver.GetUrl(contentReference, null);

            return(Configuration.Configuration.PreserveQueryString ? newUrl + request.Query : newUrl);
        }
示例#13
0
        private string RewriteLinks(string content)
        {
            // Load the document.
            var document = new HtmlDocument();

            document.LoadHtml(content);

            // Find all links in the document.
            var linkQuery = document.DocumentNode.Descendants("a");

            foreach (var linkNode in linkQuery.ToList())
            {
                if (linkNode.HasAttributes)
                {
                    var url = linkNode.GetAttributeValue("href", "#");
                    if (!url.Equals("#", StringComparison.Ordinal))
                    {
                        var parts = url.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries);
                        if (parts.Length == 2)
                        {
                            var protocol = parts[0];
                            if (protocol != null)
                            {
                                if (protocol.Equals("api", StringComparison.OrdinalIgnoreCase))
                                {
                                    // Resolve the API member.
                                    var data = parts[1].TrimStart('/');

                                    // Update the link.
                                    linkNode.SetAttributeValue("href", _resolver.GetUrl(data) ?? url);
                                }
                                else if (protocol.Equals("dsl", StringComparison.OrdinalIgnoreCase))
                                {
                                    // Resolve the DSL member.
                                    var data = parts[1].TrimStart('/');

                                    // Update the link.
                                    // TODO: Centralize resolving of URL.
                                    var category = _dslModel.FindCategory(data);
                                    var link     = category != null?string.Concat("/dsl/", category.Slug) : url;

                                    linkNode.SetAttributeValue("href", link);
                                }
                                else if (protocol.Equals("docs", StringComparison.OrdinalIgnoreCase))
                                {
                                    // Resolve the documentation id.
                                    var data = parts[1].TrimStart('/');

                                    // Update the link.
                                    linkNode.SetAttributeValue("href", string.Concat("/docs/", data));
                                }
                            }
                        }
                    }
                }
            }

            return(document.DocumentNode.OuterHtml);
        }
示例#14
0
 private LinkModel FromPageData(PageData pageData, IEnumerable <IContent> ancestors, PageData currentPage)
 {
     return(new LinkModel()
     {
         Label = pageData.Name,
         Link = _urlResolver.GetUrl(pageData.ContentLink),
         Active = ancestors.Any(a => a.ContentGuid == pageData.ContentGuid) ||
                  (currentPage != null && pageData.ContentGuid == currentPage.ContentGuid)
     });
 }
        //Event handler for keeping 'OldUrl' in contentEventArgs
        public void OnPublishingContent(object sender, ContentEventArgs contentEventArgs)
        {
            if (contentEventArgs.Content is PageData == false)
            {
                return;
            }
            var oldUrl = _urlResolver.GetUrl(new ContentReference(contentEventArgs.Content.ContentLink.ID));

            if (string.IsNullOrEmpty(oldUrl) == false)
            {
                contentEventArgs.Items.Add(PageDocumentsProvider <T> .OldUrlKey, oldUrl);
            }
        }
示例#16
0
        public IReadOnlyCollection <T> GetDocuments(IContent page, ContentEventArgs contentEventArgs)
        {
            var oldUrl = contentEventArgs.Items[OldUrlKey]?.ToString();
            var newUrl = _urlResolver.GetUrl(contentEventArgs.ContentLink);

            var isUrlChanged     = oldUrl != newUrl;
            var isMasterLanguage = page.IsMasterLanguageBranch();

            var documents = isUrlChanged
                ? GetPageTreeDocuments(page, isMasterLanguage)
                : GetPageDocuments(page, isMasterLanguage);

            return(documents.ToList());
        }
示例#17
0
        /// <summary>
        /// Gets a type description for the specified type.
        /// </summary>
        /// <param name="type">The type reference.</param>
        /// <param name="resolver">The link resolver.</param>
        /// <returns>A type description for the specified type.</returns>
        public static TypeSignature GetTypeSignature(this TypeReference type, IUrlResolver resolver)
        {
            // Get the namespace of the type.
            var ns = new NamespaceSignature(type.Namespace);

            // Get the identity.
            var identity = CRefGenerator.GetTypeCRef(type);

            // Get the type name.
            var name  = type.Name;
            var index = name.IndexOf('`');

            if (index != -1)
            {
                name = name.Substring(0, index);
            }

            if (name.EndsWith("&"))
            {
                name = name.TrimEnd('&');
            }

            // Get generic parameters and arguments.
            var genericParameters = new List <string>();
            var genericArguments  = new List <TypeSignature>();

            if (type.IsGenericInstance)
            {
                // Generic arguments
                var genericInstanceType = type as GenericInstanceType;
                if (genericInstanceType != null)
                {
                    genericArguments.AddRange(
                        genericInstanceType.GenericArguments.Select(
                            reference => GetTypeSignature(reference, resolver)));
                }
            }
            else if (type.HasGenericParameters)
            {
                // Generic parameters
                genericParameters.AddRange(
                    type.GenericParameters.Select(
                        genericParameter => genericParameter.Name));
            }

            // Return the type description.
            var url = resolver == null ? null : resolver.GetUrl(identity);

            return(new TypeSignature(identity, name, url, ns, genericParameters, genericArguments));
        }
示例#18
0
        /// <summary>
        /// Gets the method signature.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="resolver">The link resolver.</param>
        /// <returns>The method signature.</returns>
        public static MethodSignature GetMethodSignature(this MethodReference method, IUrlResolver resolver)
        {
            // Get the method definition.
            var definition = method.Resolve();

            // Get the method Identity and name.
            var identity = CRefGenerator.GetMethodCRef(definition);
            var name     = GetMethodName(definition);

            // Get the declaring type and return type.
            var declaringType = definition.DeclaringType.GetTypeSignature(resolver);
            var returnType    = definition.ReturnType.GetTypeSignature(resolver);

            // Get generic parameters and arguments.
            var genericParameters = new List <string>();

            if (method.HasGenericParameters)
            {
                // Generic parameters
                genericParameters.AddRange(
                    method.GenericParameters.Select(
                        genericParameter => genericParameter.Name));
            }

            // Get all parameters.
            var parameters = definition.Parameters.Select(
                parameterDefinition => new ParameterSignature(
                    parameterDefinition.Name,
                    parameterDefinition.ParameterType.GetTypeSignature(resolver),
                    parameterDefinition.IsOut,
                    parameterDefinition.ParameterType is ByReferenceType))
                             .ToList();

            // Get the classifications.
            var classification         = MethodClassifier.GetMethodClassification(definition);
            var operatorClassification = MethodClassifier.GetOperatorClassification(definition);

            // Return the method signature.
            var url = resolver == null ? string.Empty : resolver.GetUrl(identity);

            return(new MethodSignature(identity, name, url, classification, operatorClassification,
                                       declaringType, returnType, genericParameters, parameters));
        }
示例#19
0
        public IList <SearchResult> Search(string query, string languageBranch, int maxResults)
        {
            var foundPages = _client.Search <IContent>()
                             .For(query)
                             .CustomFilterForVisitor()
                             .FilterForPagesAndMedia(languageBranch)
                             .Take(maxResults)
                             .Select(x =>
                                     new SearchResult
            {
                Name = x.Name,
                Url  = _urlResolver.GetUrl(x.ContentLink),
            })
                             .GetResult()
                             .Hits
                             .Select(x => x.Document)
                             .ToList();

            return(foundPages);
        }
        /// <summary>
        /// Gets the method signature.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="resolver">The link resolver.</param>
        /// <returns>The method signature.</returns>
        public static MethodSignature GetMethodSignature(this MethodReference method, IUrlResolver resolver)
        {
            // Get the method definition.
            var definition = method.Resolve();

            // Get the method Identity and name.
            var identity = CRefGenerator.GetMethodCRef(definition);
            var name = GetMethodName(definition);

            // Get the declaring type and return type.
            var declaringType = definition.DeclaringType.GetTypeSignature(resolver);
            var returnType = definition.ReturnType.GetTypeSignature(resolver);

            // Get generic parameters and arguments.
            var genericParameters = new List<string>();
            if (method.HasGenericParameters)
            {
                // Generic parameters
                genericParameters.AddRange(
                    method.GenericParameters.Select(
                        genericParameter => genericParameter.Name));
            }

            // Get all parameters.
            var parameters = definition.Parameters.Select(
                parameterDefinition => new ParameterSignature(
                    parameterDefinition.Name,
                    parameterDefinition.ParameterType.GetTypeSignature(resolver),
                    parameterDefinition.IsOut,
                    parameterDefinition.ParameterType is ByReferenceType))
                .ToList();

            // Get the classifications.
            var classification = MethodClassifier.GetMethodClassification(definition);
            var operatorClassification = MethodClassifier.GetOperatorClassification(definition);

            // Return the method signature.
            var url = resolver == null ? string.Empty : resolver.GetUrl(identity);
            return new MethodSignature(identity, name, url, classification, operatorClassification, 
                declaringType, returnType, genericParameters, parameters);
        }
示例#21
0
        private Uri GetAbsoluteUrl(ContentReference contentRef)
        {
            string url = _urlResolver.GetUrl(
                contentRef,
                string.Empty,
                new UrlResolverArguments {
                ForceCanonical = true
            });

            if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri absoluteUrl) &&
                !absoluteUrl.IsAbsoluteUri)
            {
                var siteDefinition = _siteDefinitionResolver.GetByContent(
                    contentRef,
                    true,
                    true);
                absoluteUrl = new Uri(siteDefinition.SiteUrl, absoluteUrl);
            }

            return(absoluteUrl);
        }
示例#22
0
        public object Convert(ContentReference target)
        {
            if (target == null)
            {
                return(null);
            }

            var content = _contentRepository.Get <IContent>(target, LanguageSelector.AutoDetect(true));
            var media   = content as MediaData;

            if (media != null)
            {
                return(new
                {
                    media.Name,
                    media.Thumbnail,
                    media.MimeType,
                    Url = _urlResolver.GetUrl(media)
                });
            }

            return(content);
        }
 /// <summary>
 /// Resolves the front-end's view URL to a specified page.
 /// </summary>
 /// <param name="content">The content instance.</param>
 /// <returns></returns>
 public static string ResolveViewUrl(IContent content)
 {
     return(UrlResolver.GetUrl(content.ContentLink));
 }
 public override object ParseValue(object value)
 {
     return(_urlResolver.GetUrl(((Url)value).ToString()));
 }
示例#25
0
 private string GetUrl(IndexResponseItem item)
 {
     return(_urlResolver.GetUrl(_contentSearchHandler.GetContent <IContent>(item).ContentLink));
 }
        public THeaderViewModel CreateHeaderViewModel <THeaderViewModel>(IContent currentContent, CmsHomePage homePage)
            where THeaderViewModel : HeaderViewModel, new()
        {
            var menuItems    = new List <MenuItemViewModel>();
            var homeLanguage = homePage.Language.DisplayName;

            menuItems = homePage.MainMenu?.FilteredItems.Select(x =>
            {
                var itemCached = CacheManager.Get(x.ContentLink.ID + homeLanguage + ":" + MenuCacheKey) as MenuItemViewModel;
                if (itemCached != null && !PageEditing.PageIsInEditMode)
                {
                    return(itemCached);
                }
                else
                {
                    var content = _contentLoader.Get <IContent>(x.ContentLink);
                    MenuItemBlock _;
                    MenuItemViewModel menuItem;
                    if (content is MenuItemBlock)
                    {
                        _        = content as MenuItemBlock;
                        menuItem = new MenuItemViewModel
                        {
                            Name       = _.Name,
                            ButtonText = _.ButtonText,
                            TeaserText = _.TeaserText,
                            Uri        = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                            {
                                ContextMode = ContextMode.Default
                            }),
                            ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                            ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                            ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                        };
                    }
                    else
                    {
                        menuItem = new MenuItemViewModel
                        {
                            Name       = content.Name,
                            Uri        = _urlResolver.GetUrl(content.ContentLink),
                            ChildLinks = new List <GroupLinkCollection>()
                        };
                    }

                    if (!PageEditing.PageIsInEditMode)
                    {
                        var keyDependency = new List <string>
                        {
                            _contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink), // If The HomePage updates menu (remove MenuItems)
                            _contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink)
                        };

                        var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency);
                        CacheManager.Insert(x.ContentLink.ID + homeLanguage + ":" + MenuCacheKey, menuItem, eviction);
                    }
                    return(menuItem);
                }
            }).ToList();

            return(new THeaderViewModel
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                Name = PrincipalInfo.Current.Name,
                MenuItems = menuItems,
                IsReadonlyMode = _databaseMode.DatabaseMode == DatabaseMode.ReadOnly
            });
        }
        public virtual void AddMyAccountMenu <THomePage, THeaderViewModel>(THomePage homePage,
                                                                           THeaderViewModel viewModel)
            where THeaderViewModel : HeaderViewModel, new()
            where THomePage : CmsHomePage
        {
            var commerceHomePage = homePage as CommerceHomePage;

            if (commerceHomePage == null)
            {
                return;
            }

            if (HttpContext.Current != null && !HttpContext.Current.Request.IsAuthenticated)
            {
                viewModel.UserLinks = new LinkItemCollection();
                return;
            }

            var menuItems = new LinkItemCollection();
            var filter    = new FilterContentForVisitor();
            var contact   = _customerService.GetCurrentContact();

            if (contact != null && contact.FoundationOrganization != null)
            {
                var orgLink = new LinkItem
                {
                    Href  = _urlResolver.GetUrl(commerceHomePage.OrganizationMainPage),
                    Text  = _localizationService.GetString("My Organization", "My Organization"),
                    Title = _localizationService.GetString("My Organization", "My Organization")
                };
                //orgLink.Attributes.Add("css", "fa-sign-out");
                menuItems.Add(orgLink);
            }

            foreach (var linkItem in commerceHomePage.MyAccountCommerceMenu ?? new LinkItemCollection())
            {
                if (!UrlResolver.Current.TryToPermanent(linkItem.Href, out var linkUrl))
                {
                    continue;
                }

                if (linkUrl.IsNullOrEmpty())
                {
                    continue;
                }

                var urlBuilder = new UrlBuilder(linkUrl);
                var content    = _urlResolver.Route(urlBuilder);
                if (content == null || filter.ShouldFilter(content))
                {
                    continue;
                }

                linkItem.Title = linkItem.Text;
                menuItems.Add(linkItem);
            }

            var signoutText = _localizationService.GetString("/Header/Account/SignOut", "Sign Out");
            var link        = new LinkItem
            {
                Href  = "/publicapi/signout",
                Text  = signoutText,
                Title = signoutText
            };

            link.Attributes.Add("css", "fa-sign-out");
            menuItems.Add(link);

            viewModel.UserLinks.AddRange(menuItems);
        }
示例#28
0
        protected virtual HeaderViewModel CreateViewModel(IContent currentContent, HomePage homePage)
        {
            var menuItems      = new List <MenuItemViewModel>();
            var homeLanguage   = homePage.Language.DisplayName;
            var layoutSettings = _settingsService.GetSiteSettings <LayoutSettings>();
            var filter         = new FilterContentForVisitor();

            menuItems = layoutSettings?.MainMenu?.FilteredItems.Where(x =>
            {
                var _menuItem = _contentLoader.Get <IContent>(x.ContentLink);
                MenuItemBlock _menuItemBlock;
                if (_menuItem is MenuItemBlock)
                {
                    _menuItemBlock = _menuItem as MenuItemBlock;
                    if (_menuItemBlock.Link == null)
                    {
                        return(true);
                    }
                    var linkedItem = UrlResolver.Current.Route(new UrlBuilder(_menuItemBlock.Link));
                    if (filter.ShouldFilter(linkedItem))
                    {
                        return(false);
                    }
                    return(true);
                }
                return(true);
            }).Select(x =>
            {
                var content = _contentLoader.Get <IContent>(x.ContentLink);
                MenuItemBlock _;
                MenuItemViewModel menuItem;
                if (content is MenuItemBlock)
                {
                    _        = content as MenuItemBlock;
                    menuItem = new MenuItemViewModel
                    {
                        Name       = _.Name,
                        ButtonText = _.ButtonText,
                        //TeaserText = _.TeaserText,
                        Uri = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                        {
                            ContextMode = ContextMode.Default
                        }),
                        ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                        ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                        ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                    };
                }
                else
                {
                    menuItem = new MenuItemViewModel
                    {
                        Name = content.Name,
                        Uri  = _urlResolver.GetUrl(content.ContentLink),
                        //ChildLinks = new List<GroupLinkCollection>()
                    };
                }

                if (!_contextModeResolver.CurrentMode.EditOrPreview())
                {
                    var keyDependency = new List <string>
                    {
                        _contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink), // If The HomePage updates menu (remove MenuItems)
                        _contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink)
                    };
                }

                return(menuItem);
            }).ToList();

            return(new HeaderViewModel
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                IsReadonlyMode = _databaseMode.DatabaseMode == DatabaseMode.ReadOnly,
                MenuItems = menuItems ?? new List <MenuItemViewModel>(),
                IsInEditMode = _contextModeResolver.CurrentMode.EditOrPreview()
            });
        }