public IEnumerable <IPublishedContent> ConvertSearchResultToPublishedContentWithTemplate(
            IEnumerable <SearchResult> rawSearchResults, IPublishedContentCache cache, UmbracoContext context)
        {
            //remove duplicated nodes/ids - fixed with hashset
            var nodesWithOutDuplicates  = new HashSet <IPublishedContent>();
            var excludedDocTypesAliases = new HashSet <string>(_configHelper.GetValue("SiteSearchExcludedDocTypes").Split(','));

            //I would know that it's under the correct Language because of the parent ID of the IndexSet
            var searchResults = rawSearchResults.ToList();

            foreach (var r in searchResults)
            {
                var content = cache.GetById(context, false, r.Id);
                if (content != null)
                {
                    IPublishedContent nodeToAdd = content;

                    if (content.TemplateId == 0)
                    {
                        nodeToAdd = _umbracoTree.GetFirstParentWithTemplate(content);
                    }

                    if (nodeToAdd != null && !excludedDocTypesAliases.Contains(nodeToAdd.DocumentTypeAlias))
                    {
                        nodesWithOutDuplicates.Add(nodeToAdd);
                    }
                }
            }

            return(nodesWithOutDuplicates.ToList());
        }
        protected override void Initialize()
        {
            base.Initialize();

            _httpContextFactory = new FakeHttpContextFactory("~/Home");

            var umbracoSettings = Factory.GetInstance <IUmbracoSettingsSection>();
            var globalSettings  = Factory.GetInstance <IGlobalSettings>();

            _xml = new XmlDocument();
            _xml.LoadXml(GetXml());
            var xmlStore          = new XmlStore(() => _xml, null, null, null);
            var cacheProvider     = new StaticCacheProvider();
            var domainCache       = new DomainCache(ServiceContext.DomainService, DefaultCultureAccessor);
            var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedSnapshot(
                new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null),
                new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, cacheProvider, ContentTypesCache),
                new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache),
                domainCache);
            var publishedSnapshotService = new Mock <IPublishedSnapshotService>();

            publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(publishedShapshot);

            _umbracoContext = new UmbracoContext(
                _httpContextFactory.HttpContext,
                publishedSnapshotService.Object,
                new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService, globalSettings),
                umbracoSettings,
                Enumerable.Empty <IUrlProvider>(),
                globalSettings,
                new TestVariationContextAccessor());

            _cache = _umbracoContext.ContentCache;
        }
    public async Task Lookup_By_Url_Alias(
        string relativeUrl,
        int nodeMatch,
        [Frozen] IPublishedContentCache publishedContentCache,
        [Frozen] IUmbracoContextAccessor umbracoContextAccessor,
        [Frozen] IUmbracoContext umbracoContext,
        [Frozen] IVariationContextAccessor variationContextAccessor,
        IFileService fileService,
        ContentFinderByUrlAlias sut,
        IPublishedContent[] rootContents,
        IPublishedProperty urlProperty)
    {
        // Arrange
        var absoluteUrl      = "http://localhost" + relativeUrl;
        var variationContext = new VariationContext();

        var contentItem = rootContents[0];

        Mock.Get(umbracoContextAccessor).Setup(x => x.TryGetUmbracoContext(out umbracoContext)).Returns(true);
        Mock.Get(umbracoContext).Setup(x => x.Content).Returns(publishedContentCache);
        Mock.Get(publishedContentCache).Setup(x => x.GetAtRoot(null)).Returns(rootContents);
        Mock.Get(contentItem).Setup(x => x.Id).Returns(nodeMatch);
        Mock.Get(contentItem).Setup(x => x.GetProperty(Constants.Conventions.Content.UrlAlias)).Returns(urlProperty);
        Mock.Get(urlProperty).Setup(x => x.GetValue(null, null)).Returns(relativeUrl);

        Mock.Get(variationContextAccessor).Setup(x => x.VariationContext).Returns(variationContext);
        var publishedRequestBuilder = new PublishedRequestBuilder(new Uri(absoluteUrl, UriKind.Absolute), fileService);

        // Act
        var result = await sut.TryFindContent(publishedRequestBuilder);

        Assert.IsTrue(result);
        Assert.AreEqual(publishedRequestBuilder.PublishedContent.Id, nodeMatch);
    }
Ejemplo n.º 4
0
        public SiteRoot GetSiteRoot(int currentNodeId)
        {
            IPublishedContent node;

            using (UmbracoContextReference umbContextRef = _umbracoContextFactory.EnsureUmbracoContext())
            {
                IPublishedContentCache contentCache = umbContextRef.UmbracoContext.Content;
                node = umbContextRef.UmbracoContext.Content.GetById(currentNodeId);
            }

            if (node == null)
            {
                _logger.Warn <CmsService>($"1.Node with id {currentNodeId} is null");
                return(null);
            }

            var siteNode = node.AncestorsOrSelf().SingleOrDefault(x => x.ContentType.Alias == SiteRoot.ModelTypeAlias) as SiteRoot;

            if (siteNode == null)
            {
                _logger.Warn <CmsService>("siteNode is null");
            }

            return(siteNode);
        }
Ejemplo n.º 5
0
 public DefaultUrlProvider(IPublishedContentCache contentCache)
 {
     if (contentCache == null)
     {
         throw new ArgumentNullException(nameof(contentCache));
     }
     _contentCache = contentCache;
 }
 //Complex constructor to be used in unit testing to allow mocking of componets
 protected BaseSiteSearchSurfaceController(ISiteSearchService siteSearchService, IUmbracoSpellChecker spellChecker,
                                           IUmbracoPhraseSuggester phraseSuggester, IPublishedContentCache contentCache, IInputSanitiser inputSanitiser)
 {
     _siteSearchService = siteSearchService;
     _spellChecker      = spellChecker;
     _phraseSuggester   = phraseSuggester;
     _contentCache      = contentCache;
     _inputSanitiser    = inputSanitiser;
 }
 public DocTypeGridEditorApiController(IUmbracoContextAccessor umbracoContext,
                                       IContentTypeService contentTypeService,
                                       IDataTypeService dataTypeService,
                                       IPublishedContentCache contentCache)
 {
     _umbracoContext     = umbracoContext;
     _contentTypeService = contentTypeService;
     _dataTypeService    = dataTypeService;
     _contentCache       = contentCache;
 }
        private IUmbracoContext GetUmbracoContext(bool hasContent)
        {
            IPublishedContentCache publishedContent = Mock.Of <IPublishedContentCache>(x => x.HasContent() == hasContent);
            var uri = new Uri("http://example.com");

            IUmbracoContext umbracoContext = Mock.Of <IUmbracoContext>(x =>
                                                                       x.Content == publishedContent &&
                                                                       x.OriginalRequestUrl == uri &&
                                                                       x.CleanedUmbracoUrl == uri);

            return(umbracoContext);
        }
        protected override void Initialize()
        {
            base.Initialize();

            _httpContextFactory = new FakeHttpContextFactory("~/Home");

            var globalSettings         = new GlobalSettings();
            var umbracoContextAccessor = Factory.GetRequiredService <IUmbracoContextAccessor>();

            _xml = new XmlDocument();
            _xml.LoadXml(GetXml());
            var xmlStore          = new XmlStore(() => _xml, null, null, null, HostingEnvironment);
            var appCache          = new DictionaryAppCache();
            var domainCache       = new DomainCache(Mock.Of <IDomainService>(), DefaultCultureAccessor);
            var publishedShapshot = new PublishedSnapshot(
                new PublishedContentCache(xmlStore, domainCache, appCache, globalSettings, ContentTypesCache, null, VariationContextAccessor, null),
                new PublishedMediaCache(xmlStore, Mock.Of <IMediaService>(), Mock.Of <IUserService>(), appCache, ContentTypesCache, Factory.GetRequiredService <IEntityXmlSerializer>(), umbracoContextAccessor, VariationContextAccessor),
                new PublishedMemberCache(ContentTypesCache, VariationContextAccessor),
                domainCache);
            var publishedSnapshotService = new Mock <IPublishedSnapshotService>();

            publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(publishedShapshot);

            var httpContext         = _httpContextFactory.HttpContext;
            var httpContextAccessor = TestHelper.GetHttpContextAccessor(httpContext);

            _umbracoContext = new UmbracoContext(
                httpContextAccessor,
                publishedSnapshotService.Object,
                Mock.Of <IBackOfficeSecurity>(),
                globalSettings,
                HostingEnvironment,
                new TestVariationContextAccessor(),
                UriUtility,
                new AspNetCookieManager(httpContextAccessor));

            _cache = _umbracoContext.Content;
        }
Ejemplo n.º 10
0
        private void StoreOldRoute(IContent entity, OldRoutesDictionary oldRoutes)
        {
            if (!_publishedSnapshotAccessor.TryGetPublishedSnapshot(out var publishedSnapshot))
            {
                return;
            }

            IPublishedContentCache contentCache  = publishedSnapshot.Content;
            IPublishedContent      entityContent = contentCache?.GetById(entity.Id);

            if (entityContent is null)
            {
                return;
            }

            // get the default affected cultures by going up the tree until we find the first culture variant entity (default to no cultures)
            var defaultCultures = entityContent.AncestorsOrSelf()?.FirstOrDefault(a => a.Cultures.Any())?.Cultures.Keys.ToArray()
                                  ?? new[] { (string)null };

            foreach (IPublishedContent publishedContent in entityContent.DescendantsOrSelf(_variationContextAccessor))
            {
                // if this entity defines specific cultures, use those instead of the default ones
                IEnumerable <string> cultures = publishedContent.Cultures.Any() ? publishedContent.Cultures.Keys : defaultCultures;

                foreach (var culture in cultures)
                {
                    var route = contentCache.GetRouteById(publishedContent.Id, culture);
                    if (IsNotRoute(route))
                    {
                        continue;
                    }

                    oldRoutes[new ContentIdAndCulture(publishedContent.Id, culture)] = new ContentKeyAndOldRoute(publishedContent.Key, route);
                }
            }
        }
        private static IPublishedContent FindContentByAlias(IPublishedContentCache cache, int rootNodeId, string culture, string alias)
        {
            if (alias == null)
            {
                throw new ArgumentNullException(nameof(alias));
            }

            // the alias may be "foo/bar" or "/foo/bar"
            // there may be spaces as in "/foo/bar,  /foo/nil"
            // these should probably be taken care of earlier on

            // TODO: can we normalize the values so that they contain no whitespaces, and no leading slashes?
            // and then the comparisons in IsMatch can be way faster - and allocate way less strings

            const string propertyAlias = Constants.Conventions.Content.UrlAlias;

            var test1 = alias.TrimStart('/') + ",";
            var test2 = ",/" + test1; // test2 is ",/alias,"

            test1 = "," + test1;      // test1 is ",alias,"

            bool IsMatch(IPublishedContent c, string a1, string a2)
            {
                // this basically implements the original XPath query ;-(
                //
                // "//* [@isDoc and (" +
                // "contains(concat(',',translate(umbracoUrlAlias, ' ', ''),','),',{0},')" +
                // " or contains(concat(',',translate(umbracoUrlAlias, ' ', ''),','),',/{0},')" +
                // ")]"

                if (!c.HasProperty(propertyAlias))
                {
                    return(false);
                }
                var    p      = c.GetProperty(propertyAlias);
                var    varies = p.PropertyType.VariesByCulture();
                string v;

                if (varies)
                {
                    if (!c.HasCulture(culture))
                    {
                        return(false);
                    }
                    v = c.Value <string>(propertyAlias, culture);
                }
                else
                {
                    v = c.Value <string>(propertyAlias);
                }
                if (string.IsNullOrWhiteSpace(v))
                {
                    return(false);
                }
                v = "," + v.Replace(" ", "") + ",";
                return(v.InvariantContains(a1) || v.InvariantContains(a2));
            }

            // TODO: even with Linq, what happens below has to be horribly slow
            // but the only solution is to entirely refactor url providers to stop being dynamic

            if (rootNodeId > 0)
            {
                var rootNode = cache.GetById(rootNodeId);
                return(rootNode?.Descendants().FirstOrDefault(x => IsMatch(x, test1, test2)));
            }

            foreach (var rootContent in cache.GetAtRoot())
            {
                var c = rootContent.DescendantsOrSelf().FirstOrDefault(x => IsMatch(x, test1, test2));
                if (c != null)
                {
                    return(c);
                }
            }

            return(null);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PublishedCaches"/> class with a content cache
 /// and a media cache.
 /// </summary>
 public PublishedCaches(IPublishedContentCache contentCache, IPublishedMediaCache mediaCache)
 {
     _contentCache = contentCache;
     _mediaCache = mediaCache;
 }
Ejemplo n.º 13
0
 public RedirectPublishedContentFinder(IPublishedContentCache publishedContentCache)
 {
     _publishedContentCache = publishedContentCache;
 }
Ejemplo n.º 14
0
 public FileSystemContentFinder(IPublishedContentCache contentCache)
 {
     _contentCache = contentCache;
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Constructor used to return results from the caches
 /// </summary>
 /// <param name="contentCache"></param>
 /// <param name="mediaCache"></param>
 /// <param name="variationContextAccessor"></param>
 public PublishedContentQuery(IPublishedContentCache contentCache, IPublishedMediaCache mediaCache, IVariationContextAccessor variationContextAccessor)
 {
     _contentCache             = contentCache ?? throw new ArgumentNullException(nameof(contentCache));
     _mediaCache               = mediaCache ?? throw new ArgumentNullException(nameof(mediaCache));
     _variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PublishedCaches"/> class with a content cache
 /// and a media cache.
 /// </summary>
 public PublishedCaches(IPublishedContentCache contentCache, IPublishedMediaCache mediaCache)
 {
     _contentCache = contentCache;
     _mediaCache   = mediaCache;
 }
 public FileSystemContentFinder(IPublishedContentCache contentCache)
 {
     _contentCache = contentCache;
 }
Ejemplo n.º 18
0
 public DefaultUrlProvider(IPublishedContentCache contentCache)
 {
     if (contentCache == null) throw new ArgumentNullException(nameof(contentCache));
     _contentCache = contentCache;
 }
 public EnSiteSearchSurfaceController(ISiteSearchService siteSearchService, IUmbracoSpellChecker spellChecker, IUmbracoPhraseSuggester phraseSuggester,  IPublishedContentCache contentCache, IInputSanitiser inputSanitiser) : base(siteSearchService, spellChecker, phraseSuggester, contentCache, inputSanitiser)
 {
 }