From fbf60fbac47eb0fe19074bab6e96c87330f6f220 Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Mon, 22 Oct 2018 09:39:22 +0200 Subject: [PATCH 01/41] Don't add the "Notification" tree menu item if Umbraco can't send emails --- src/Umbraco.Web/Trees/ContentTreeController.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web/Trees/ContentTreeController.cs b/src/Umbraco.Web/Trees/ContentTreeController.cs index 293cc3d36a..54adb24b74 100644 --- a/src/Umbraco.Web/Trees/ContentTreeController.cs +++ b/src/Umbraco.Web/Trees/ContentTreeController.cs @@ -238,7 +238,10 @@ namespace Umbraco.Web.Trees menu.Items.Add(ui.Text("actions", ActionRights.Instance.Alias), true); menu.Items.Add(ui.Text("actions", ActionProtect.Instance.Alias), true).ConvertLegacyMenuItem(item, "content", "content"); - menu.Items.Add(ui.Text("actions", ActionNotify.Instance.Alias), true); + if (EmailSender.CanSendRequiredEmail) + { + menu.Items.Add(ui.Text("actions", ActionNotify.Instance.Alias), true); + } menu.Items.Add(ui.Text("actions", ActionSendToTranslate.Instance.Alias)).ConvertLegacyMenuItem(item, "content", "content"); menu.Items.Add(ui.Text("actions", ActionRefresh.Instance.Alias), true); From b08e9226001f59d144fca943c59c5486964569b0 Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Wed, 7 Nov 2018 12:27:50 +0100 Subject: [PATCH 02/41] Only allow setting up scheduled publishing if the user has the correct permissions to do so --- .../components/content/umbcontentnodeinfo.directive.js | 3 +++ .../src/views/components/content/umb-content-node-info.html | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbcontentnodeinfo.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbcontentnodeinfo.directive.js index 8f613469a3..c753ac67d2 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbcontentnodeinfo.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbcontentnodeinfo.directive.js @@ -53,6 +53,9 @@ if (scope.documentType !== null) { scope.previewOpenUrl = '#/settings/documenttypes/edit/' + scope.documentType.id; } + + // only allow configuring scheduled publishing if the user has publish ("U") and unpublish ("Z") permissions on this node + scope.allowScheduledPublishing = _.contains(scope.node.allowedActions, "U") && _.contains(scope.node.allowedActions, "Z"); } scope.auditTrailPageChange = function (pageNumber) { diff --git a/src/Umbraco.Web.UI.Client/src/views/components/content/umb-content-node-info.html b/src/Umbraco.Web.UI.Client/src/views/components/content/umb-content-node-info.html index 7085babf59..0ed3986fe3 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/content/umb-content-node-info.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/content/umb-content-node-info.html @@ -107,7 +107,7 @@
- + From 05f1a24caff54e2ae9b6ec3f5289b9eb95410df9 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Mon, 14 Jan 2019 08:28:58 +0100 Subject: [PATCH 03/41] Fix duplicate IIS Express settings --- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 81ca9c5a37..fc24d2b40f 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -1041,9 +1041,6 @@ xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" 7140 / http://localhost:7140 - 7131 - / - http://localhost:7131 False False From db8954e0a5d532943e9885581ef154cb21872cc4 Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Mon, 14 Jan 2019 08:52:02 +0100 Subject: [PATCH 04/41] Verify that the current member is approved and not locked out (#3588) --- .../Routing/PublishedContentRequestEngine.cs | 853 +++++++++--------- 1 file changed, 438 insertions(+), 415 deletions(-) diff --git a/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs b/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs index 217f407f02..0341c083f9 100644 --- a/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs +++ b/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs @@ -26,61 +26,61 @@ using RenderingEngine = Umbraco.Core.RenderingEngine; namespace Umbraco.Web.Routing { internal class PublishedContentRequestEngine - { - private readonly PublishedContentRequest _pcr; - private readonly RoutingContext _routingContext; - private readonly IWebRoutingSection _webRoutingSection; + { + private readonly PublishedContentRequest _pcr; + private readonly RoutingContext _routingContext; + private readonly IWebRoutingSection _webRoutingSection; - /// - /// Initializes a new instance of the class with a content request. - /// - /// - /// The content request. - public PublishedContentRequestEngine( + /// + /// Initializes a new instance of the class with a content request. + /// + /// + /// The content request. + public PublishedContentRequestEngine( IWebRoutingSection webRoutingSection, PublishedContentRequest pcr) - { - if (pcr == null) throw new ArgumentException("pcr is null."); - if (webRoutingSection == null) throw new ArgumentNullException("webRoutingSection"); - - _pcr = pcr; - _webRoutingSection = webRoutingSection; + { + if (pcr == null) throw new ArgumentException("pcr is null."); + if (webRoutingSection == null) throw new ArgumentNullException("webRoutingSection"); - _routingContext = pcr.RoutingContext; - if (_routingContext == null) throw new ArgumentException("pcr.RoutingContext is null."); - - var umbracoContext = _routingContext.UmbracoContext; - if (umbracoContext == null) throw new ArgumentException("pcr.RoutingContext.UmbracoContext is null."); - if (umbracoContext.RoutingContext != _routingContext) throw new ArgumentException("RoutingContext confusion."); - // no! not set yet. - //if (umbracoContext.PublishedContentRequest != _pcr) throw new ArgumentException("PublishedContentRequest confusion."); - } + _pcr = pcr; + _webRoutingSection = webRoutingSection; + + _routingContext = pcr.RoutingContext; + if (_routingContext == null) throw new ArgumentException("pcr.RoutingContext is null."); + + var umbracoContext = _routingContext.UmbracoContext; + if (umbracoContext == null) throw new ArgumentException("pcr.RoutingContext.UmbracoContext is null."); + if (umbracoContext.RoutingContext != _routingContext) throw new ArgumentException("RoutingContext confusion."); + // no! not set yet. + //if (umbracoContext.PublishedContentRequest != _pcr) throw new ArgumentException("PublishedContentRequest confusion."); + } protected ProfilingLogger ProfilingLogger - { + { get { return _routingContext.UmbracoContext.Application.ProfilingLogger; } - } + } - protected ServiceContext Services - { + protected ServiceContext Services + { get { return _routingContext.UmbracoContext.Application.Services; } - } + } - #region Public + #region Public /// /// Tries to route the request. /// - internal bool TryRouteRequest() - { + internal bool TryRouteRequest() + { // disabled - is it going to change the routing? //_pcr.OnPreparing(); FindDomain(); - if (_pcr.IsRedirect) return false; - if (_pcr.HasPublishedContent) return true; - FindPublishedContent(); + if (_pcr.IsRedirect) return false; + if (_pcr.HasPublishedContent) return true; + FindPublishedContent(); if (_pcr.IsRedirect) return false; // don't handle anything - we just want to ensure that we find the content @@ -93,51 +93,51 @@ namespace Umbraco.Web.Routing //_pcr.OnPrepared(); return _pcr.HasPublishedContent; - } + } - /// - /// Prepares the request. - /// - /// - /// Returns false if the request was not successfully prepared - /// - public bool PrepareRequest() - { - // note - at that point the original legacy module did something do handle IIS custom 404 errors - // ie pages looking like /anything.aspx?404;/path/to/document - I guess the reason was to support - // "directory urls" without having to do wildcard mapping to ASP.NET on old IIS. This is a pain - // to maintain and probably not used anymore - removed as of 06/2012. @zpqrtbnk. - // - // to trigger Umbraco's not-found, one should configure IIS and/or ASP.NET custom 404 errors - // so that they point to a non-existing page eg /redirect-404.aspx - // TODO: SD: We need more information on this for when we release 4.10.0 as I'm not sure what this means. + /// + /// Prepares the request. + /// + /// + /// Returns false if the request was not successfully prepared + /// + public bool PrepareRequest() + { + // note - at that point the original legacy module did something do handle IIS custom 404 errors + // ie pages looking like /anything.aspx?404;/path/to/document - I guess the reason was to support + // "directory urls" without having to do wildcard mapping to ASP.NET on old IIS. This is a pain + // to maintain and probably not used anymore - removed as of 06/2012. @zpqrtbnk. + // + // to trigger Umbraco's not-found, one should configure IIS and/or ASP.NET custom 404 errors + // so that they point to a non-existing page eg /redirect-404.aspx + // TODO: SD: We need more information on this for when we release 4.10.0 as I'm not sure what this means. // trigger the Preparing event - at that point anything can still be changed // the idea is that it is possible to change the uri // - _pcr.OnPreparing(); + _pcr.OnPreparing(); - //find domain - FindDomain(); + //find domain + FindDomain(); - // if request has been flagged to redirect then return - // whoever called us is in charge of actually redirecting - if (_pcr.IsRedirect) - { - return false; - } + // if request has been flagged to redirect then return + // whoever called us is in charge of actually redirecting + if (_pcr.IsRedirect) + { + return false; + } - // set the culture on the thread - once, so it's set when running document lookups - Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = _pcr.Culture; + // set the culture on the thread - once, so it's set when running document lookups + Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = _pcr.Culture; //find the published content if it's not assigned. This could be manually assigned with a custom route handler, or // with something like EnsurePublishedContentRequestAttribute or UmbracoVirtualNodeRouteHandler. Those in turn call this method // to setup the rest of the pipeline but we don't want to run the finders since there's one assigned. - if (_pcr.PublishedContent == null) - { + if (_pcr.PublishedContent == null) + { // find the document & template FindPublishedContentAndTemplate(); - } + } // handle wildcard domains HandleWildcardDomains(); @@ -145,19 +145,19 @@ namespace Umbraco.Web.Routing // set the culture on the thread -- again, 'cos it might have changed due to a finder or wildcard domain Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = _pcr.Culture; - // trigger the Prepared event - at that point it is still possible to change about anything + // trigger the Prepared event - at that point it is still possible to change about anything // even though the request might be flagged for redirection - we'll redirect _after_ the event // // also, OnPrepared() will make the PublishedContentRequest readonly, so nothing can change // - _pcr.OnPrepared(); + _pcr.OnPrepared(); // we don't take care of anything so if the content has changed, it's up to the user // to find out the appropriate template //complete the PCR and assign the remaining values - return ConfigureRequest(); - } + return ConfigureRequest(); + } /// /// Called by PrepareRequest once everything has been discovered, resolved and assigned to the PCR. This method @@ -210,73 +210,73 @@ namespace Umbraco.Web.Routing return true; } - /// - /// Updates the request when there is no template to render the content. - /// - /// This is called from Mvc when there's a document to render but no template. - public void UpdateRequestOnMissingTemplate() - { - // clear content - var content = _pcr.PublishedContent; - _pcr.PublishedContent = null; + /// + /// Updates the request when there is no template to render the content. + /// + /// This is called from Mvc when there's a document to render but no template. + public void UpdateRequestOnMissingTemplate() + { + // clear content + var content = _pcr.PublishedContent; + _pcr.PublishedContent = null; - HandlePublishedContent(); // will go 404 - FindTemplate(); + HandlePublishedContent(); // will go 404 + FindTemplate(); - // if request has been flagged to redirect then return - // whoever called us is in charge of redirecting - if (_pcr.IsRedirect) - return; + // if request has been flagged to redirect then return + // whoever called us is in charge of redirecting + if (_pcr.IsRedirect) + return; - if (_pcr.HasPublishedContent == false) - { - // means the engine could not find a proper document to handle 404 - // restore the saved content so we know it exists - _pcr.PublishedContent = content; - return; - } + if (_pcr.HasPublishedContent == false) + { + // means the engine could not find a proper document to handle 404 + // restore the saved content so we know it exists + _pcr.PublishedContent = content; + return; + } - if (_pcr.HasTemplate == false) - { - // means we may have a document, but we have no template - // at that point there isn't much we can do and there is no point returning - // to Mvc since Mvc can't do much either - return; - } + if (_pcr.HasTemplate == false) + { + // means we may have a document, but we have no template + // at that point there isn't much we can do and there is no point returning + // to Mvc since Mvc can't do much either + return; + } // see note in PrepareRequest() - // assign the legacy page back to the docrequest - // handlers like default.aspx will want it and most macros currently need it - _pcr.UmbracoPage = new page(_pcr); + // assign the legacy page back to the docrequest + // handlers like default.aspx will want it and most macros currently need it + _pcr.UmbracoPage = new page(_pcr); - // these two are used by many legacy objects - _routingContext.UmbracoContext.HttpContext.Items["pageID"] = _pcr.PublishedContent.Id; - _routingContext.UmbracoContext.HttpContext.Items["pageElements"] = _pcr.UmbracoPage.Elements; - } + // these two are used by many legacy objects + _routingContext.UmbracoContext.HttpContext.Items["pageID"] = _pcr.PublishedContent.Id; + _routingContext.UmbracoContext.HttpContext.Items["pageElements"] = _pcr.UmbracoPage.Elements; + } - #endregion + #endregion - #region Domain + #region Domain - /// - /// Finds the site root (if any) matching the http request, and updates the PublishedContentRequest accordingly. - /// - /// A value indicating whether a domain was found. - internal bool FindDomain() - { - const string tracePrefix = "FindDomain: "; + /// + /// Finds the site root (if any) matching the http request, and updates the PublishedContentRequest accordingly. + /// + /// A value indicating whether a domain was found. + internal bool FindDomain() + { + const string tracePrefix = "FindDomain: "; - // note - we are not handling schemes nor ports here. + // note - we are not handling schemes nor ports here. - ProfilingLogger.Logger.Debug("{0}Uri=\"{1}\"", () => tracePrefix, () => _pcr.Uri); + ProfilingLogger.Logger.Debug("{0}Uri=\"{1}\"", () => tracePrefix, () => _pcr.Uri); - // try to find a domain matching the current request + // try to find a domain matching the current request var domainAndUri = DomainHelper.DomainForUri(Services.DomainService.GetAll(false), _pcr.Uri); - // handle domain - if (domainAndUri != null && domainAndUri.UmbracoDomain.LanguageIsoCode.IsNullOrWhiteSpace() == false) - { + // handle domain + if (domainAndUri != null && domainAndUri.UmbracoDomain.LanguageIsoCode.IsNullOrWhiteSpace() == false) + { // matching an existing domain ProfilingLogger.Logger.Debug("{0}Matches domain=\"{1}\", rootId={2}, culture=\"{3}\"", () => tracePrefix, @@ -296,49 +296,49 @@ namespace Umbraco.Web.Routing // } } else - { - // not matching any existing domain - ProfilingLogger.Logger.Debug("{0}Matches no domain", () => tracePrefix); + { + // not matching any existing domain + ProfilingLogger.Logger.Debug("{0}Matches no domain", () => tracePrefix); var defaultLanguage = Services.LocalizationService.GetAllLanguages().FirstOrDefault(); - _pcr.Culture = defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.IsoCode); - } + _pcr.Culture = defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.IsoCode); + } - ProfilingLogger.Logger.Debug("{0}Culture=\"{1}\"", () => tracePrefix, () => _pcr.Culture.Name); + ProfilingLogger.Logger.Debug("{0}Culture=\"{1}\"", () => tracePrefix, () => _pcr.Culture.Name); - return _pcr.UmbracoDomain != null; - } + return _pcr.UmbracoDomain != null; + } - /// - /// Looks for wildcard domains in the path and updates Culture accordingly. - /// - internal void HandleWildcardDomains() - { - const string tracePrefix = "HandleWildcardDomains: "; + /// + /// Looks for wildcard domains in the path and updates Culture accordingly. + /// + internal void HandleWildcardDomains() + { + const string tracePrefix = "HandleWildcardDomains: "; - if (_pcr.HasPublishedContent == false) - return; + if (_pcr.HasPublishedContent == false) + return; - var nodePath = _pcr.PublishedContent.Path; - ProfilingLogger.Logger.Debug("{0}Path=\"{1}\"", () => tracePrefix, () => nodePath); + var nodePath = _pcr.PublishedContent.Path; + ProfilingLogger.Logger.Debug("{0}Path=\"{1}\"", () => tracePrefix, () => nodePath); var rootNodeId = _pcr.HasDomain ? _pcr.UmbracoDomain.RootContentId : (int?)null; var domain = DomainHelper.FindWildcardDomainInPath(Services.DomainService.GetAll(true), nodePath, rootNodeId); - if (domain != null && domain.LanguageIsoCode.IsNullOrWhiteSpace() == false) - { + if (domain != null && domain.LanguageIsoCode.IsNullOrWhiteSpace() == false) + { _pcr.Culture = new CultureInfo(domain.LanguageIsoCode); ProfilingLogger.Logger.Debug("{0}Got domain on node {1}, set culture to \"{2}\".", () => tracePrefix, () => domain.RootContentId, () => _pcr.Culture.Name); } - else - { - ProfilingLogger.Logger.Debug("{0}No match.", () => tracePrefix); - } - } + else + { + ProfilingLogger.Logger.Debug("{0}No match.", () => tracePrefix); + } + } - #endregion + #endregion - #region Rendering engine + #region Rendering engine /// /// Finds the rendering engine to use to render a template specified by its alias. @@ -383,264 +383,287 @@ namespace Umbraco.Web.Routing return directory.GetFiles().Any(f => extensions.Any(e => f.Name.InvariantEquals(alias + e))); } - #endregion + #endregion - #region Document and template + #region Document and template - /// - /// Finds the Umbraco document (if any) matching the request, and updates the PublishedContentRequest accordingly. - /// - /// A value indicating whether a document and template were found. - private void FindPublishedContentAndTemplate() - { - const string tracePrefix = "FindPublishedContentAndTemplate: "; - ProfilingLogger.Logger.Debug("{0}Path=\"{1}\"", () => tracePrefix, () => _pcr.Uri.AbsolutePath); + /// + /// Finds the Umbraco document (if any) matching the request, and updates the PublishedContentRequest accordingly. + /// + /// A value indicating whether a document and template were found. + private void FindPublishedContentAndTemplate() + { + const string tracePrefix = "FindPublishedContentAndTemplate: "; + ProfilingLogger.Logger.Debug("{0}Path=\"{1}\"", () => tracePrefix, () => _pcr.Uri.AbsolutePath); - // run the document finders - FindPublishedContent(); + // run the document finders + FindPublishedContent(); // if request has been flagged to redirect then return // whoever called us is in charge of actually redirecting // -- do not process anything any further -- if (_pcr.IsRedirect) - return; + return; - // not handling umbracoRedirect here but after LookupDocument2 - // so internal redirect, 404, etc has precedence over redirect + // not handling umbracoRedirect here but after LookupDocument2 + // so internal redirect, 404, etc has precedence over redirect - // handle not-found, redirects, access... - HandlePublishedContent(); + // handle not-found, redirects, access... + HandlePublishedContent(); - // find a template - FindTemplate(); + // find a template + FindTemplate(); - // handle umbracoRedirect - FollowExternalRedirect(); - } + // handle umbracoRedirect + FollowExternalRedirect(); + } - /// - /// Tries to find the document matching the request, by running the IPublishedContentFinder instances. - /// + /// + /// Tries to find the document matching the request, by running the IPublishedContentFinder instances. + /// /// There is no finder collection. - internal void FindPublishedContent() - { - const string tracePrefix = "FindPublishedContent: "; + internal void FindPublishedContent() + { + const string tracePrefix = "FindPublishedContent: "; - // look for the document - // the first successful finder, if any, will set this.PublishedContent, and may also set this.Template - // some finders may implement caching + // look for the document + // the first successful finder, if any, will set this.PublishedContent, and may also set this.Template + // some finders may implement caching using (ProfilingLogger.DebugDuration( - string.Format("{0}Begin finders", tracePrefix), - string.Format("{0}End finders, {1}", tracePrefix, (_pcr.HasPublishedContent ? "a document was found" : "no document was found")))) - { - if (_routingContext.PublishedContentFinders == null) + string.Format("{0}Begin finders", tracePrefix), + string.Format("{0}End finders, {1}", tracePrefix, (_pcr.HasPublishedContent ? "a document was found" : "no document was found")))) + { + if (_routingContext.PublishedContentFinders == null) throw new InvalidOperationException("There is no finder collection."); //iterate but return on first one that finds it - var found = _routingContext.PublishedContentFinders.Any(finder => finder.TryFindContent(_pcr)); - } + var found = _routingContext.PublishedContentFinders.Any(finder => finder.TryFindContent(_pcr)); + } - // indicate that the published content (if any) we have at the moment is the - // one that was found by the standard finders before anything else took place. - _pcr.SetIsInitialPublishedContent(); - } + // indicate that the published content (if any) we have at the moment is the + // one that was found by the standard finders before anything else took place. + _pcr.SetIsInitialPublishedContent(); + } - /// - /// Handles the published content (if any). - /// - /// - /// Handles "not found", internal redirects, access validation... - /// things that must be handled in one place because they can create loops - /// - private void HandlePublishedContent() - { - const string tracePrefix = "HandlePublishedContent: "; + /// + /// Handles the published content (if any). + /// + /// + /// Handles "not found", internal redirects, access validation... + /// things that must be handled in one place because they can create loops + /// + private void HandlePublishedContent() + { + const string tracePrefix = "HandlePublishedContent: "; - // because these might loop, we have to have some sort of infinite loop detection - int i = 0, j = 0; - const int maxLoop = 8; - do - { - ProfilingLogger.Logger.Debug("{0}{1}", () => tracePrefix, () => (i == 0 ? "Begin" : "Loop")); + // because these might loop, we have to have some sort of infinite loop detection + int i = 0, j = 0; + const int maxLoop = 8; + do + { + ProfilingLogger.Logger.Debug("{0}{1}", () => tracePrefix, () => (i == 0 ? "Begin" : "Loop")); - // handle not found - if (_pcr.HasPublishedContent == false) - { - _pcr.Is404 = true; - ProfilingLogger.Logger.Debug("{0}No document, try last chance lookup", () => tracePrefix); + // handle not found + if (_pcr.HasPublishedContent == false) + { + _pcr.Is404 = true; + ProfilingLogger.Logger.Debug("{0}No document, try last chance lookup", () => tracePrefix); - // if it fails then give up, there isn't much more that we can do - var lastChance = _routingContext.PublishedContentLastChanceFinder; - if (lastChance == null || lastChance.TryFindContent(_pcr) == false) - { - ProfilingLogger.Logger.Debug("{0}Failed to find a document, give up", () => tracePrefix); - break; - } + // if it fails then give up, there isn't much more that we can do + var lastChance = _routingContext.PublishedContentLastChanceFinder; + if (lastChance == null || lastChance.TryFindContent(_pcr) == false) + { + ProfilingLogger.Logger.Debug("{0}Failed to find a document, give up", () => tracePrefix); + break; + } - ProfilingLogger.Logger.Debug("{0}Found a document", () => tracePrefix); - } + ProfilingLogger.Logger.Debug("{0}Found a document", () => tracePrefix); + } - // follow internal redirects as long as it's not running out of control ie infinite loop of some sort - j = 0; - while (FollowInternalRedirects() && j++ < maxLoop) - { } - if (j == maxLoop) // we're running out of control - break; + // follow internal redirects as long as it's not running out of control ie infinite loop of some sort + j = 0; + while (FollowInternalRedirects() && j++ < maxLoop) + { } + if (j == maxLoop) // we're running out of control + break; - // ensure access - if (_pcr.HasPublishedContent) - EnsurePublishedContentAccess(); + // ensure access + if (_pcr.HasPublishedContent) + EnsurePublishedContentAccess(); - // loop while we don't have page, ie the redirect or access - // got us to nowhere and now we need to run the notFoundLookup again - // as long as it's not running out of control ie infinite loop of some sort + // loop while we don't have page, ie the redirect or access + // got us to nowhere and now we need to run the notFoundLookup again + // as long as it's not running out of control ie infinite loop of some sort - } while (_pcr.HasPublishedContent == false && i++ < maxLoop); + } while (_pcr.HasPublishedContent == false && i++ < maxLoop); - if (i == maxLoop || j == maxLoop) - { - ProfilingLogger.Logger.Debug("{0}Looks like we're running into an infinite loop, abort", () => tracePrefix); - _pcr.PublishedContent = null; - } + if (i == maxLoop || j == maxLoop) + { + ProfilingLogger.Logger.Debug("{0}Looks like we're running into an infinite loop, abort", () => tracePrefix); + _pcr.PublishedContent = null; + } - ProfilingLogger.Logger.Debug("{0}End", () => tracePrefix); - } + ProfilingLogger.Logger.Debug("{0}End", () => tracePrefix); + } - /// - /// Follows internal redirections through the umbracoInternalRedirectId document property. - /// - /// A value indicating whether redirection took place and led to a new published document. - /// - /// Redirecting to a different site root and/or culture will not pick the new site root nor the new culture. - /// As per legacy, if the redirect does not work, we just ignore it. - /// - private bool FollowInternalRedirects() - { - const string tracePrefix = "FollowInternalRedirects: "; + /// + /// Follows internal redirections through the umbracoInternalRedirectId document property. + /// + /// A value indicating whether redirection took place and led to a new published document. + /// + /// Redirecting to a different site root and/or culture will not pick the new site root nor the new culture. + /// As per legacy, if the redirect does not work, we just ignore it. + /// + private bool FollowInternalRedirects() + { + const string tracePrefix = "FollowInternalRedirects: "; + + if (_pcr.PublishedContent == null) + throw new InvalidOperationException("There is no PublishedContent."); - if (_pcr.PublishedContent == null) - throw new InvalidOperationException("There is no PublishedContent."); - // don't try to find a redirect if the property doesn't exist - if (_pcr.PublishedContent.HasProperty(Constants.Conventions.Content.InternalRedirectId) == false) - return false; + if (_pcr.PublishedContent.HasProperty(Constants.Conventions.Content.InternalRedirectId) == false) + return false; var redirect = false; - IPublishedContent internalRedirectNode = null; - var internalRedirectId = - _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.InternalRedirectId, -1); - var valueValid = false; - if (internalRedirectId > 0) - { - valueValid = true; - // Try and get the redirect node from a legacy integer ID - internalRedirectNode = _routingContext.UmbracoContext.ContentCache.GetById(internalRedirectId); - } - else - { - var udiInternalRedirectId = - _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.InternalRedirectId); + IPublishedContent internalRedirectNode = null; + var internalRedirectId = + _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.InternalRedirectId, -1); + var valueValid = false; + if (internalRedirectId > 0) + { + valueValid = true; + // Try and get the redirect node from a legacy integer ID + internalRedirectNode = _routingContext.UmbracoContext.ContentCache.GetById(internalRedirectId); + } + else + { + var udiInternalRedirectId = + _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.InternalRedirectId); if (udiInternalRedirectId != null) - { - valueValid = true; - // Try and get the redirect node from a UDI Guid - internalRedirectNode = - _routingContext.UmbracoContext.ContentCache.GetById(udiInternalRedirectId.Guid); - } - } + { + valueValid = true; + // Try and get the redirect node from a UDI Guid + internalRedirectNode = + _routingContext.UmbracoContext.ContentCache.GetById(udiInternalRedirectId.Guid); + } + } if (valueValid == false) - { + { // bad redirect - log and display the current page (legacy behavior) ProfilingLogger - .Logger.Debug( - "{0}Failed to redirect, value of '{1}' is not an int nor a GuidUdi", - () => tracePrefix, () => Constants.Conventions.Content.InternalRedirectId); - } + .Logger.Debug( + "{0}Failed to redirect, value of '{1}' is not an int nor a GuidUdi", + () => tracePrefix, () => Constants.Conventions.Content.InternalRedirectId); + } - if (internalRedirectNode == null) - { - ProfilingLogger.Logger.Debug( - "{0}Failed to redirect, value of '{1}' does not lead to a published document", () => tracePrefix, - () => Constants.Conventions.Content.InternalRedirectId); - } - else if (internalRedirectNode.Id == _pcr.PublishedContent.Id) - { - // redirect to self - ProfilingLogger.Logger.Debug("{0}Redirecting to self, ignore", - () => tracePrefix); - } - else - { - // Redirect to another page - _pcr.SetInternalRedirectPublishedContent(internalRedirectNode); - redirect = true; - ProfilingLogger.Logger.Debug("{0}Redirecting to id={1}", () => tracePrefix, - () => internalRedirectNode.Id); - } + if (internalRedirectNode == null) + { + ProfilingLogger.Logger.Debug( + "{0}Failed to redirect, value of '{1}' does not lead to a published document", () => tracePrefix, + () => Constants.Conventions.Content.InternalRedirectId); + } + else if (internalRedirectNode.Id == _pcr.PublishedContent.Id) + { + // redirect to self + ProfilingLogger.Logger.Debug("{0}Redirecting to self, ignore", + () => tracePrefix); + } + else + { + // Redirect to another page + _pcr.SetInternalRedirectPublishedContent(internalRedirectNode); + redirect = true; + ProfilingLogger.Logger.Debug("{0}Redirecting to id={1}", () => tracePrefix, + () => internalRedirectNode.Id); + } - return redirect; - } + return redirect; + } - /// - /// Ensures that access to current node is permitted. - /// - /// Redirecting to a different site root and/or culture will not pick the new site root nor the new culture. - private void EnsurePublishedContentAccess() - { - const string tracePrefix = "EnsurePublishedContentAccess: "; + /// + /// Ensures that access to current node is permitted. + /// + /// Redirecting to a different site root and/or culture will not pick the new site root nor the new culture. + private void EnsurePublishedContentAccess() + { + const string tracePrefix = "EnsurePublishedContentAccess: "; - if (_pcr.PublishedContent == null) - throw new InvalidOperationException("There is no PublishedContent."); + if (_pcr.PublishedContent == null) + throw new InvalidOperationException("There is no PublishedContent."); - var path = _pcr.PublishedContent.Path; + var path = _pcr.PublishedContent.Path; - var publicAccessAttempt = Services.PublicAccessService.IsProtected(path); + var publicAccessAttempt = Services.PublicAccessService.IsProtected(path); if (publicAccessAttempt) - { - ProfilingLogger.Logger.Debug("{0}Page is protected, check for access", () => tracePrefix); + { + ProfilingLogger.Logger.Debug("{0}Page is protected, check for access", () => tracePrefix); - var membershipHelper = new MembershipHelper(_routingContext.UmbracoContext); + var membershipHelper = new MembershipHelper(_routingContext.UmbracoContext); - if (membershipHelper.IsLoggedIn() == false) - { - ProfilingLogger.Logger.Debug("{0}Not logged in, redirect to login page", () => tracePrefix); + if (membershipHelper.IsLoggedIn() == false) + { + ProfilingLogger.Logger.Debug("{0}Not logged in, redirect to login page", () => tracePrefix); var loginPageId = publicAccessAttempt.Result.LoginNodeId; - if (loginPageId != _pcr.PublishedContent.Id) + if (loginPageId != _pcr.PublishedContent.Id) _pcr.PublishedContent = _routingContext.UmbracoContext.ContentCache.GetById(loginPageId); - } + } else if (Services.PublicAccessService.HasAccess(_pcr.PublishedContent.Id, Services.ContentService, _pcr.GetRolesForLogin(membershipHelper.CurrentUserName)) == false) - { - ProfilingLogger.Logger.Debug("{0}Current member has not access, redirect to error page", () => tracePrefix); - var errorPageId = publicAccessAttempt.Result.NoAccessNodeId; - if (errorPageId != _pcr.PublishedContent.Id) + { + ProfilingLogger.Logger.Debug("{0}Current member has not access, redirect to error page", () => tracePrefix); + var errorPageId = publicAccessAttempt.Result.NoAccessNodeId; + if (errorPageId != _pcr.PublishedContent.Id) _pcr.PublishedContent = _routingContext.UmbracoContext.ContentCache.GetById(errorPageId); - } - else - { - ProfilingLogger.Logger.Debug("{0}Current member has access", () => tracePrefix); - } - } - else - { - ProfilingLogger.Logger.Debug("{0}Page is not protected", () => tracePrefix); - } - } + } + else + { + // grab the current member + var member = membershipHelper.GetCurrentMember(); + // if the member has the "approved" and/or "locked out" properties, make sure they're correctly set before allowing access + var memberIsActive = true; + if (member != null) + { + if (member.HasProperty(Constants.Conventions.Member.IsApproved) == false) + memberIsActive = member.GetPropertyValue(Constants.Conventions.Member.IsApproved); - /// - /// Finds a template for the current node, if any. - /// - private void FindTemplate() - { - // NOTE: at the moment there is only 1 way to find a template, and then ppl must - // use the Prepared event to change the template if they wish. Should we also - // implement an ITemplateFinder logic? + if (member.HasProperty(Constants.Conventions.Member.IsLockedOut) == false) + memberIsActive = member.GetPropertyValue(Constants.Conventions.Member.IsLockedOut) == false; + } - const string tracePrefix = "FindTemplate: "; + if (memberIsActive == false) + { + ProfilingLogger.Logger.Debug("{0}Current member is either unapproved or locked out, redirect to error page", () => tracePrefix); + var errorPageId = publicAccessAttempt.Result.NoAccessNodeId; + if (errorPageId != _pcr.PublishedContent.Id) + _pcr.PublishedContent = _routingContext.UmbracoContext.ContentCache.GetById(errorPageId); + } + else + { + ProfilingLogger.Logger.Debug("{0}Current member has access", () => tracePrefix); + } + } + } + else + { + ProfilingLogger.Logger.Debug("{0}Page is not protected", () => tracePrefix); + } + } + + /// + /// Finds a template for the current node, if any. + /// + private void FindTemplate() + { + // NOTE: at the moment there is only 1 way to find a template, and then ppl must + // use the Prepared event to change the template if they wish. Should we also + // implement an ITemplateFinder logic? + + const string tracePrefix = "FindTemplate: "; if (_pcr.PublishedContent == null) { @@ -648,49 +671,49 @@ namespace Umbraco.Web.Routing return; } - // read the alternate template alias, from querystring, form, cookie or server vars, - // only if the published content is the initial once, else the alternate template - // does not apply + // read the alternate template alias, from querystring, form, cookie or server vars, + // only if the published content is the initial once, else the alternate template + // does not apply // + optionnally, apply the alternate template on internal redirects var useAltTemplate = _pcr.IsInitialPublishedContent || (_webRoutingSection.InternalRedirectPreservesTemplate && _pcr.IsInternalRedirectPublishedContent); string altTemplate = useAltTemplate ? _routingContext.UmbracoContext.HttpContext.Request[Constants.Conventions.Url.AltTemplate] - : null; + : null; - if (string.IsNullOrWhiteSpace(altTemplate)) - { - // we don't have an alternate template specified. use the current one if there's one already, - // which can happen if a content lookup also set the template (LookupByNiceUrlAndTemplate...), - // else lookup the template id on the document then lookup the template with that id. + if (string.IsNullOrWhiteSpace(altTemplate)) + { + // we don't have an alternate template specified. use the current one if there's one already, + // which can happen if a content lookup also set the template (LookupByNiceUrlAndTemplate...), + // else lookup the template id on the document then lookup the template with that id. - if (_pcr.HasTemplate) - { - ProfilingLogger.Logger.Debug("{0}Has a template already, and no alternate template.", () => tracePrefix); - return; - } + if (_pcr.HasTemplate) + { + ProfilingLogger.Logger.Debug("{0}Has a template already, and no alternate template.", () => tracePrefix); + return; + } - // TODO: When we remove the need for a database for templates, then this id should be irrelavent, - // not sure how were going to do this nicely. + // TODO: When we remove the need for a database for templates, then this id should be irrelavent, + // not sure how were going to do this nicely. - var templateId = _pcr.PublishedContent.TemplateId; + var templateId = _pcr.PublishedContent.TemplateId; // This code was moved to GetTemplateModel to allow the same functionality on a failed altTemplate (U4-8550) // The only change is a diffent logger prefix and null will be set to _pcr.TemplateModel if the templateId is <= 0 // rather than no set taking place _pcr.TemplateModel = GetTemplateModel(_pcr.PublishedContent.TemplateId); } - else - { - // we have an alternate template specified. lookup the template with that alias - // this means the we override any template that a content lookup might have set - // so /path/to/page/template1?altTemplate=template2 will use template2 + else + { + // we have an alternate template specified. lookup the template with that alias + // this means the we override any template that a content lookup might have set + // so /path/to/page/template1?altTemplate=template2 will use template2 - // ignore if the alias does not match - just trace + // ignore if the alias does not match - just trace - if (_pcr.HasTemplate) - ProfilingLogger.Logger.Debug("{0}Has a template already, but also an alternate template.", () => tracePrefix); - ProfilingLogger.Logger.Debug("{0}Look for alternate template alias=\"{1}\"", () => tracePrefix, () => altTemplate); + if (_pcr.HasTemplate) + ProfilingLogger.Logger.Debug("{0}Has a template already, but also an alternate template.", () => tracePrefix); + ProfilingLogger.Logger.Debug("{0}Look for alternate template alias=\"{1}\"", () => tracePrefix, () => altTemplate); if (_pcr.PublishedContent.IsAllowedTemplate(altTemplate)) { @@ -705,26 +728,26 @@ namespace Umbraco.Web.Routing LogHelper.Warn("{0}Configuration settings prevent template \"{1}\" from showing for node \"{2}\"", () => tracePrefix, () => altTemplate, () => _pcr.PublishedContent.Id); _pcr.TemplateModel = GetTemplateModel(_pcr.PublishedContent.TemplateId); } - } + } - if (_pcr.HasTemplate == false) - { - ProfilingLogger.Logger.Debug("{0}No template was found.", () => tracePrefix); + if (_pcr.HasTemplate == false) + { + ProfilingLogger.Logger.Debug("{0}No template was found.", () => tracePrefix); - // initial idea was: if we're not already 404 and UmbracoSettings.HandleMissingTemplateAs404 is true - // then reset _pcr.Document to null to force a 404. - // - // but: because we want to let MVC hijack routes even though no template is defined, we decide that - // a missing template is OK but the request will then be forwarded to MVC, which will need to take - // care of everything. - // - // so, don't set _pcr.Document to null here - } - else - { - ProfilingLogger.Logger.Debug("{0}Running with template id={1} alias=\"{2}\"", () => tracePrefix, () => _pcr.TemplateModel.Id, () => _pcr.TemplateModel.Alias); - } - } + // initial idea was: if we're not already 404 and UmbracoSettings.HandleMissingTemplateAs404 is true + // then reset _pcr.Document to null to force a 404. + // + // but: because we want to let MVC hijack routes even though no template is defined, we decide that + // a missing template is OK but the request will then be forwarded to MVC, which will need to take + // care of everything. + // + // so, don't set _pcr.Document to null here + } + else + { + ProfilingLogger.Logger.Debug("{0}Running with template id={1} alias=\"{2}\"", () => tracePrefix, () => _pcr.TemplateModel.Id, () => _pcr.TemplateModel.Alias); + } + } private ITemplate GetTemplateModel(int templateId) { @@ -751,32 +774,32 @@ namespace Umbraco.Web.Routing /// /// As per legacy, if the redirect does not work, we just ignore it. private void FollowExternalRedirect() - { - if (_pcr.HasPublishedContent == false) return; + { + if (_pcr.HasPublishedContent == false) return; - // don't try to find a redirect if the property doesn't exist + // don't try to find a redirect if the property doesn't exist if (_pcr.PublishedContent.HasProperty(Constants.Conventions.Content.Redirect) == false) - return; - - var redirectId = _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.Redirect, -1); + return; - var redirectUrl = "#"; - if (redirectId > 0) - { - redirectUrl = _routingContext.UrlProvider.GetUrl(redirectId); - } - else - { + var redirectId = _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.Redirect, -1); + + var redirectUrl = "#"; + if (redirectId > 0) + { + redirectUrl = _routingContext.UrlProvider.GetUrl(redirectId); + } + else + { // might be a UDI instead of an int Id - var redirectUdi = _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.Redirect); - if (redirectUdi != null) - redirectUrl = _routingContext.UrlProvider.GetUrl(redirectUdi.Guid); - } - if (redirectUrl != "#") - { - _pcr.SetRedirect(redirectUrl); - } - } - #endregion - } + var redirectUdi = _pcr.PublishedContent.GetPropertyValue(Constants.Conventions.Content.Redirect); + if (redirectUdi != null) + redirectUrl = _routingContext.UrlProvider.GetUrl(redirectUdi.Guid); + } + if (redirectUrl != "#") + { + _pcr.SetRedirect(redirectUrl); + } + } + #endregion + } } From b9430158cedb0bf5b1c0b93f543ec5383d8bec41 Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Mon, 14 Jan 2019 09:25:59 +0100 Subject: [PATCH 05/41] Move member group picker property data store from NVarchar to NText (#3712) --- .../UpdateMemberGroupPickerData.cs | 36 +++++++++++++++++++ src/Umbraco.Core/Umbraco.Core.csproj | 1 + .../MemberGroupPickerPropertyEditor.cs | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs diff --git a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs new file mode 100644 index 0000000000..2dbc69e58a --- /dev/null +++ b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs @@ -0,0 +1,36 @@ +using Umbraco.Core.Logging; +using Umbraco.Core.Persistence.SqlSyntax; + +namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenFourteenZero +{ + /// + /// Migrates member group picker properties from NVarchar to NText. See https://github.com/umbraco/Umbraco-CMS/issues/3268. + /// + [Migration("7.14.0", 1, Constants.System.UmbracoMigrationName)] + public class UpdateMemberGroupPickerData : MigrationBase + { + public UpdateMemberGroupPickerData(ISqlSyntaxProvider sqlSyntax, ILogger logger) : base(sqlSyntax, logger) + { + } + + public override void Up() + { + // move the data for all member group properties from the NVarchar to the NText column and clear the NVarchar column + Execute.Sql(@"UPDATE cmsPropertyData SET dataNtext = dataNvarchar, dataNvarchar = NULL + WHERE dataNtext IS NULL AND id IN ( + SELECT id FROM cmsPropertyData WHERE propertyTypeId in ( + SELECT id from cmsPropertyType where dataTypeID IN ( + SELECT nodeId FROM cmsDataType WHERE propertyEditorAlias = 'Umbraco.MemberGroupPicker' + ) + ) + )"); + + // ensure that all exising member group properties are defined as NText + Execute.Sql("UPDATE cmsDataType SET dbType = 'Ntext' WHERE propertyEditorAlias = 'Umbraco.MemberGroupPicker'"); + } + + public override void Down() + { + } + } +} diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index c7393e524f..8ee29e777f 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -572,6 +572,7 @@ + diff --git a/src/Umbraco.Web/PropertyEditors/MemberGroupPickerPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MemberGroupPickerPropertyEditor.cs index 433199c536..6d7dd9e344 100644 --- a/src/Umbraco.Web/PropertyEditors/MemberGroupPickerPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MemberGroupPickerPropertyEditor.cs @@ -8,7 +8,7 @@ using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { - [PropertyEditor(Constants.PropertyEditors.MemberGroupPickerAlias, "Member Group Picker", "membergrouppicker", Group="People", Icon="icon-users")] + [PropertyEditor(Constants.PropertyEditors.MemberGroupPickerAlias, "Member Group Picker", PropertyEditorValueTypes.Text, "membergrouppicker", Group="People", Icon="icon-users")] public class MemberGroupPickerPropertyEditor : PropertyEditor { } From f7671ec9a7653082d432352a7801e5bedb621c5c Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Tue, 15 Jan 2019 08:39:43 +0100 Subject: [PATCH 06/41] Fixes #4071 - Error executing scheduled task - This instance has already started one or more requests. --- src/Umbraco.Web/Scheduling/ScheduledTasks.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Umbraco.Web/Scheduling/ScheduledTasks.cs b/src/Umbraco.Web/Scheduling/ScheduledTasks.cs index 4278b82c34..7387bca000 100644 --- a/src/Umbraco.Web/Scheduling/ScheduledTasks.cs +++ b/src/Umbraco.Web/Scheduling/ScheduledTasks.cs @@ -63,10 +63,11 @@ namespace Umbraco.Web.Scheduling private async Task GetTaskByHttpAync(string url, CancellationToken token) { if (_httpClient == null) - _httpClient = new HttpClient(); - - if (Uri.TryCreate(_appContext.UmbracoApplicationUrl, UriKind.Absolute, out var baseUri)) - _httpClient.BaseAddress = baseUri; + { + _httpClient = Uri.TryCreate(_appContext.UmbracoApplicationUrl, UriKind.Absolute, out var baseUri) + ? new HttpClient { BaseAddress = baseUri } + : new HttpClient(); + } var request = new HttpRequestMessage(HttpMethod.Get, url); From 64469fcb5c72074cb9f410687ca90329db63d6b1 Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Tue, 15 Jan 2019 10:03:10 +0100 Subject: [PATCH 07/41] Force select the content app for both views when opening split view --- .../content/umbvariantcontenteditors.directive.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js index 1987c897f0..e413701a26 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js @@ -215,9 +215,15 @@ * @param {any} selectedVariant */ function openSplitView(selectedVariant) { - var selectedCulture = selectedVariant.language.culture; + //Find the whole variant model based on the culture that was chosen + var variant = _.find(vm.content.variants, function (v) { + return v.language.culture === selectedCulture; + }); + + insertVariantEditor(vm.editors.length, initVariant(variant, vm.editors.length)); + //only the content app can be selected since no other apps are shown, and because we copy all of these apps //to the "editors" we need to update this across all editors for (var e = 0; e < vm.editors.length; e++) { @@ -233,13 +239,6 @@ } } - //Find the whole variant model based on the culture that was chosen - var variant = _.find(vm.content.variants, function (v) { - return v.language.culture === selectedCulture; - }); - - insertVariantEditor(vm.editors.length, initVariant(variant, vm.editors.length)); - //TODO: hacking animation states - these should hopefully be easier to do when we upgrade angular editor.collapsed = true; editor.loading = true; From 16eae7c4fc894d31b4510f6953ad9f545101d713 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Tue, 15 Jan 2019 14:54:34 +0100 Subject: [PATCH 08/41] #3305 Added optional culture parameter to Children and Descendants extension methods --- .../PublishedContentDataTableTests.cs | 496 ++--- .../PublishedContent/PublishedContentTests.cs | 1756 ++++++++--------- .../PublishedContent/PublishedMediaTests.cs | 1016 +++++----- src/Umbraco.Web/PublishedContentExtensions.cs | 115 +- 4 files changed, 1700 insertions(+), 1683 deletions(-) diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs index 3af930c4c3..4e3c17403b 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs @@ -1,248 +1,248 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using Moq; -using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.PropertyEditors; -using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; -using Umbraco.Web; - -namespace Umbraco.Tests.PublishedContent -{ - /// - /// Unit tests for IPublishedContent and extensions - /// - [TestFixture] - public class PublishedContentDataTableTests : BaseWebTest - { - public override void SetUp() - { - base.SetUp(); - - // need to specify a different callback for testing - PublishedContentExtensions.GetPropertyAliasesAndNames = (services, alias) => - { - var userFields = new Dictionary() - { - {"property1", "Property 1"}, - {"property2", "Property 2"} - }; - if (alias == "Child") - { - userFields.Add("property4", "Property 4"); - } - else - { - userFields.Add("property3", "Property 3"); - } - - //ensure the standard fields are there - var allFields = new Dictionary() - { - {"Id", "Id"}, - {"NodeName", "NodeName"}, - {"NodeTypeAlias", "NodeTypeAlias"}, - {"CreateDate", "CreateDate"}, - {"UpdateDate", "UpdateDate"}, - {"CreatorName", "CreatorName"}, - {"WriterName", "WriterName"}, - {"Url", "Url"} - }; - foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key))) - { - allFields.Add(f.Key, f.Value); - } - return allFields; - }; - var umbracoContext = GetUmbracoContext("/test"); - - //set the UmbracoContext.Current since the extension methods rely on it - Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; - } - - public override void TearDown() - { - base.TearDown(); - Umbraco.Web.PublishedContentExtensions.GetPropertyAliasesAndNames = null; - } - - [Test] - public void To_DataTable() - { - var doc = GetContent(true, 1); - var dt = doc.ChildrenAsTable(Current.Services); - - Assert.AreEqual(11, dt.Columns.Count); - Assert.AreEqual(3, dt.Rows.Count); - Assert.AreEqual("value4", dt.Rows[0]["Property 1"]); - Assert.AreEqual("value5", dt.Rows[0]["Property 2"]); - Assert.AreEqual("value6", dt.Rows[0]["Property 4"]); - Assert.AreEqual("value7", dt.Rows[1]["Property 1"]); - Assert.AreEqual("value8", dt.Rows[1]["Property 2"]); - Assert.AreEqual("value9", dt.Rows[1]["Property 4"]); - Assert.AreEqual("value10", dt.Rows[2]["Property 1"]); - Assert.AreEqual("value11", dt.Rows[2]["Property 2"]); - Assert.AreEqual("value12", dt.Rows[2]["Property 4"]); - } - - [Test] - public void To_DataTable_With_Filter() - { - var doc = GetContent(true, 1); - //change a doc type alias - var c = (TestPublishedContent) doc.Children.ElementAt(0); - c.ContentType = new PublishedContentType(22, "DontMatch", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); - - var dt = doc.ChildrenAsTable(Current.Services, "Child"); - - Assert.AreEqual(11, dt.Columns.Count); - Assert.AreEqual(2, dt.Rows.Count); - Assert.AreEqual("value7", dt.Rows[0]["Property 1"]); - Assert.AreEqual("value8", dt.Rows[0]["Property 2"]); - Assert.AreEqual("value9", dt.Rows[0]["Property 4"]); - Assert.AreEqual("value10", dt.Rows[1]["Property 1"]); - Assert.AreEqual("value11", dt.Rows[1]["Property 2"]); - Assert.AreEqual("value12", dt.Rows[1]["Property 4"]); - } - - [Test] - public void To_DataTable_No_Rows() - { - var doc = GetContent(false, 1); - var dt = doc.ChildrenAsTable(Current.Services); - //will return an empty data table - Assert.AreEqual(0, dt.Columns.Count); - Assert.AreEqual(0, dt.Rows.Count); - } - - private IPublishedContent GetContent(bool createChildren, int indexVals) - { - var dataTypeService = new TestObjects.TestDataTypeService( - new DataType(new VoidEditor(Mock.Of())) { Id = 1 }); - - var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); - var contentTypeAlias = createChildren ? "Parent" : "Child"; - var d = new TestPublishedContent - { - CreateDate = DateTime.Now, - CreatorId = 1, - CreatorName = "Shannon", - Id = 3, - SortOrder = 4, - TemplateId = 5, - UpdateDate = DateTime.Now, - Path = "-1,3", - UrlSegment = "home-page", - Name = "Page" + Guid.NewGuid().ToString(), - Version = Guid.NewGuid(), - WriterId = 1, - WriterName = "Shannon", - Parent = null, - Level = 1, - Children = new List() - }; - d.Properties = new Collection(new List - { - new RawValueProperty(factory.CreatePropertyType("property1", 1), d, "value" + indexVals), - new RawValueProperty(factory.CreatePropertyType("property2", 1), d, "value" + (indexVals + 1)) - }); - if (createChildren) - { - d.Children = new List() - { - GetContent(false, indexVals + 3), - GetContent(false, indexVals + 6), - GetContent(false, indexVals + 9) - }; - } - - if (!createChildren) - { - //create additional columns, used to test the different columns for child nodes - ((Collection) d.Properties).Add( - new RawValueProperty(factory.CreatePropertyType("property4",1), d, "value" + (indexVals + 2))); - } - else - { - ((Collection) d.Properties).Add( - new RawValueProperty(factory.CreatePropertyType("property3", 1), d, "value" + (indexVals + 2))); - } - - d.ContentType = new PublishedContentType(22, contentTypeAlias, PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); - return d; - } - - // note - could probably rewrite those tests using SolidPublishedContentCache - // l8tr... - private class TestPublishedContent : IPublishedContent - { - public string Url { get; set; } - public string GetUrl(string culture = null) => throw new NotSupportedException(); - - public PublishedItemType ItemType { get; set; } - - IPublishedContent IPublishedContent.Parent - { - get { return Parent; } - } - - IEnumerable IPublishedContent.Children - { - get { return Children; } - } - - public IPublishedContent Parent { get; set; } - public int Id { get; set; } - public Guid Key { get; set; } - public int? TemplateId { get; set; } - public int SortOrder { get; set; } - public string Name { get; set; } - public PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); - public IReadOnlyDictionary Cultures => throw new NotSupportedException(); - public string UrlSegment { get; set; } - public string WriterName { get; set; } - public string CreatorName { get; set; } - public int WriterId { get; set; } - public int CreatorId { get; set; } - public string Path { get; set; } - public DateTime CreateDate { get; set; } - public DateTime UpdateDate { get; set; } - public Guid Version { get; set; } - public int Level { get; set; } - public bool IsDraft(string culture = null) => false; - - public IEnumerable Properties { get; set; } - - public IEnumerable Children { get; set; } - - public IPublishedProperty GetProperty(string alias) - { - return Properties.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); - } - - public IPublishedProperty GetProperty(string alias, bool recurse) - { - var property = GetProperty(alias); - if (recurse == false) return property; - - IPublishedContent content = this; - while (content != null && (property == null || property.HasValue() == false)) - { - content = content.Parent; - property = content == null ? null : content.GetProperty(alias); - } - - return property; - } - - public PublishedContentType ContentType { get; set; } - } - } -} +//using System; +//using System.Collections.Generic; +//using System.Collections.ObjectModel; +//using System.Linq; +//using Moq; +//using NUnit.Framework; +//using Umbraco.Core; +//using Umbraco.Core.Composing; +//using Umbraco.Core.Logging; +//using Umbraco.Core.Models; +//using Umbraco.Core.Models.PublishedContent; +//using Umbraco.Core.PropertyEditors; +//using Umbraco.Core.Services; +//using Umbraco.Tests.TestHelpers; +//using Umbraco.Web; +// +//namespace Umbraco.Tests.PublishedContent +//{ +// /// +// /// Unit tests for IPublishedContent and extensions +// /// +// [TestFixture] +// public class PublishedContentDataTableTests : BaseWebTest +// { +// public override void SetUp() +// { +// base.SetUp(); +// +// // need to specify a different callback for testing +// PublishedContentExtensions.GetPropertyAliasesAndNames = (services, alias) => +// { +// var userFields = new Dictionary() +// { +// {"property1", "Property 1"}, +// {"property2", "Property 2"} +// }; +// if (alias == "Child") +// { +// userFields.Add("property4", "Property 4"); +// } +// else +// { +// userFields.Add("property3", "Property 3"); +// } +// +// //ensure the standard fields are there +// var allFields = new Dictionary() +// { +// {"Id", "Id"}, +// {"NodeName", "NodeName"}, +// {"NodeTypeAlias", "NodeTypeAlias"}, +// {"CreateDate", "CreateDate"}, +// {"UpdateDate", "UpdateDate"}, +// {"CreatorName", "CreatorName"}, +// {"WriterName", "WriterName"}, +// {"Url", "Url"} +// }; +// foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key))) +// { +// allFields.Add(f.Key, f.Value); +// } +// return allFields; +// }; +// var umbracoContext = GetUmbracoContext("/test"); +// +// //set the UmbracoContext.Current since the extension methods rely on it +// Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; +// } +// +// public override void TearDown() +// { +// base.TearDown(); +// Umbraco.Web.PublishedContentExtensions.GetPropertyAliasesAndNames = null; +// } +// +// [Test] +// public void To_DataTable() +// { +// var doc = GetContent(true, 1); +// var dt = doc.ChildrenAsTable(Current.Services); +// +// Assert.AreEqual(11, dt.Columns.Count); +// Assert.AreEqual(3, dt.Rows.Count); +// Assert.AreEqual("value4", dt.Rows[0]["Property 1"]); +// Assert.AreEqual("value5", dt.Rows[0]["Property 2"]); +// Assert.AreEqual("value6", dt.Rows[0]["Property 4"]); +// Assert.AreEqual("value7", dt.Rows[1]["Property 1"]); +// Assert.AreEqual("value8", dt.Rows[1]["Property 2"]); +// Assert.AreEqual("value9", dt.Rows[1]["Property 4"]); +// Assert.AreEqual("value10", dt.Rows[2]["Property 1"]); +// Assert.AreEqual("value11", dt.Rows[2]["Property 2"]); +// Assert.AreEqual("value12", dt.Rows[2]["Property 4"]); +// } +// +// [Test] +// public void To_DataTable_With_Filter() +// { +// var doc = GetContent(true, 1); +// //change a doc type alias +// var c = (TestPublishedContent) doc.Children.ElementAt(0); +// c.ContentType = new PublishedContentType(22, "DontMatch", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); +// +// var dt = doc.ChildrenAsTable(Current.Services, "Child"); +// +// Assert.AreEqual(11, dt.Columns.Count); +// Assert.AreEqual(2, dt.Rows.Count); +// Assert.AreEqual("value7", dt.Rows[0]["Property 1"]); +// Assert.AreEqual("value8", dt.Rows[0]["Property 2"]); +// Assert.AreEqual("value9", dt.Rows[0]["Property 4"]); +// Assert.AreEqual("value10", dt.Rows[1]["Property 1"]); +// Assert.AreEqual("value11", dt.Rows[1]["Property 2"]); +// Assert.AreEqual("value12", dt.Rows[1]["Property 4"]); +// } +// +// [Test] +// public void To_DataTable_No_Rows() +// { +// var doc = GetContent(false, 1); +// var dt = doc.ChildrenAsTable(Current.Services); +// //will return an empty data table +// Assert.AreEqual(0, dt.Columns.Count); +// Assert.AreEqual(0, dt.Rows.Count); +// } +// +// private IPublishedContent GetContent(bool createChildren, int indexVals) +// { +// var dataTypeService = new TestObjects.TestDataTypeService( +// new DataType(new VoidEditor(Mock.Of())) { Id = 1 }); +// +// var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); +// var contentTypeAlias = createChildren ? "Parent" : "Child"; +// var d = new TestPublishedContent +// { +// CreateDate = DateTime.Now, +// CreatorId = 1, +// CreatorName = "Shannon", +// Id = 3, +// SortOrder = 4, +// TemplateId = 5, +// UpdateDate = DateTime.Now, +// Path = "-1,3", +// UrlSegment = "home-page", +// Name = "Page" + Guid.NewGuid().ToString(), +// Version = Guid.NewGuid(), +// WriterId = 1, +// WriterName = "Shannon", +// Parent = null, +// Level = 1, +// Children = new List() +// }; +// d.Properties = new Collection(new List +// { +// new RawValueProperty(factory.CreatePropertyType("property1", 1), d, "value" + indexVals), +// new RawValueProperty(factory.CreatePropertyType("property2", 1), d, "value" + (indexVals + 1)) +// }); +// if (createChildren) +// { +// d.Children = new List() +// { +// GetContent(false, indexVals + 3), +// GetContent(false, indexVals + 6), +// GetContent(false, indexVals + 9) +// }; +// } +// +// if (!createChildren) +// { +// //create additional columns, used to test the different columns for child nodes +// ((Collection) d.Properties).Add( +// new RawValueProperty(factory.CreatePropertyType("property4",1), d, "value" + (indexVals + 2))); +// } +// else +// { +// ((Collection) d.Properties).Add( +// new RawValueProperty(factory.CreatePropertyType("property3", 1), d, "value" + (indexVals + 2))); +// } +// +// d.ContentType = new PublishedContentType(22, contentTypeAlias, PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); +// return d; +// } +// +// // note - could probably rewrite those tests using SolidPublishedContentCache +// // l8tr... +// private class TestPublishedContent : IPublishedContent +// { +// public string Url { get; set; } +// public string GetUrl(string culture = null) => throw new NotSupportedException(); +// +// public PublishedItemType ItemType { get; set; } +// +// IPublishedContent IPublishedContent.Parent +// { +// get { return Parent; } +// } +// +// IEnumerable IPublishedContent.Children +// { +// get { return Children; } +// } +// +// public IPublishedContent Parent { get; set; } +// public int Id { get; set; } +// public Guid Key { get; set; } +// public int? TemplateId { get; set; } +// public int SortOrder { get; set; } +// public string Name { get; set; } +// public PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); +// public IReadOnlyDictionary Cultures => throw new NotSupportedException(); +// public string UrlSegment { get; set; } +// public string WriterName { get; set; } +// public string CreatorName { get; set; } +// public int WriterId { get; set; } +// public int CreatorId { get; set; } +// public string Path { get; set; } +// public DateTime CreateDate { get; set; } +// public DateTime UpdateDate { get; set; } +// public Guid Version { get; set; } +// public int Level { get; set; } +// public bool IsDraft(string culture = null) => false; +// +// public IEnumerable Properties { get; set; } +// +// public IEnumerable Children { get; set; } +// +// public IPublishedProperty GetProperty(string alias) +// { +// return Properties.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); +// } +// +// public IPublishedProperty GetProperty(string alias, bool recurse) +// { +// var property = GetProperty(alias); +// if (recurse == false) return property; +// +// IPublishedContent content = this; +// while (content != null && (property == null || property.HasValue() == false)) +// { +// content = content.Parent; +// property = content == null ? null : content.GetProperty(alias); +// } +// +// return property; +// } +// +// public PublishedContentType ContentType { get; set; } +// } +// } +//} diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index 914956dce1..6e652fdc68 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -1,878 +1,878 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.PropertyEditors; -using Umbraco.Web; -using Umbraco.Web.PublishedCache; -using Umbraco.Core.Composing; -using Moq; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; -using Umbraco.Web.Models.PublishedContent; -using Umbraco.Web.PropertyEditors; - -namespace Umbraco.Tests.PublishedContent -{ - /// - /// Tests the methods on IPublishedContent using the DefaultPublishedContentStore - /// - [TestFixture] - [UmbracoTest(TypeLoader = UmbracoTestOptions.TypeLoader.PerFixture)] - public class PublishedContentTests : PublishedContentTestBase - { - protected override void Compose() - { - base.Compose(); - - Composition.RegisterUnique(f => new PublishedModelFactory(f.GetInstance().GetTypes())); - Composition.RegisterUnique(); - Composition.RegisterUnique(); - - var logger = Mock.Of(); - var dataTypeService = new TestObjects.TestDataTypeService( - new DataType(new VoidEditor(logger)) { Id = 1 }, - new DataType(new TrueFalsePropertyEditor(logger)) { Id = 1001 }, - new DataType(new RichTextPropertyEditor(logger)) { Id = 1002 }, - new DataType(new IntegerPropertyEditor(logger)) { Id = 1003 }, - new DataType(new TextboxPropertyEditor(logger)) { Id = 1004 }, - new DataType(new MediaPickerPropertyEditor(logger)) { Id = 1005 }); - Composition.RegisterUnique(f => dataTypeService); - } - - protected override void Initialize() - { - base.Initialize(); - - var factory = Factory.GetInstance() as PublishedContentTypeFactory; - - // need to specify a custom callback for unit tests - // AutoPublishedContentTypes generates properties automatically - // when they are requested, but we must declare those that we - // explicitely want to be here... - - var propertyTypes = new[] - { - // AutoPublishedContentType will auto-generate other properties - factory.CreatePropertyType("umbracoNaviHide", 1001), - factory.CreatePropertyType("selectedNodes", 1), - factory.CreatePropertyType("umbracoUrlAlias", 1), - factory.CreatePropertyType("content", 1002), - factory.CreatePropertyType("testRecursive", 1), - }; - var compositionAliases = new[] { "MyCompositionAlias" }; - var type = new AutoPublishedContentType(0, "anything", compositionAliases, propertyTypes); - ContentTypesCache.GetPublishedContentTypeByAlias = alias => type; - } - - protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) - { - var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); - - // this is so the model factory looks into the test assembly - pluginManager.AssembliesToScan = pluginManager.AssembliesToScan - .Union(new[] { typeof(PublishedContentTests).Assembly }) - .ToList(); - - return pluginManager; - } - - private readonly Guid _node1173Guid = Guid.NewGuid(); - - protected override string GetXmlContent(int templateId) - { - return @" - - - - -]> - - - - - 1 - - - This is some content
]]> - - - - - - - - - - - - - - - - 1 - - - - - - - - - -"; - } - - internal IPublishedContent GetNode(int id) - { - var ctx = GetUmbracoContext("/test"); - var doc = ctx.ContentCache.GetById(id); - Assert.IsNotNull(doc); - return doc; - } - - [Test] - public void GetNodeByIds() - { - var ctx = GetUmbracoContext("/test"); - var contentById = ctx.ContentCache.GetById(1173); - Assert.IsNotNull(contentById); - var contentByGuid = ctx.ContentCache.GetById(_node1173Guid); - Assert.IsNotNull(contentByGuid); - Assert.AreEqual(contentById.Id, contentByGuid.Id); - Assert.AreEqual(contentById.Key, contentByGuid.Key); - - contentById = ctx.ContentCache.GetById(666); - Assert.IsNull(contentById); - contentByGuid = ctx.ContentCache.GetById(Guid.NewGuid()); - Assert.IsNull(contentByGuid); - } - - [Test] - public void Is_Last_From_Where_Filter_Dynamic_Linq() - { - var doc = GetNode(1173); - - var items = doc.Children.Where(x => x.IsVisible()).ToIndexedArray(); - - foreach (var item in items) - { - if (item.Content.Id != 1178) - { - Assert.IsFalse(item.IsLast()); - } - else - { - Assert.IsTrue(item.IsLast()); - } - } - } - - [Test] - public void Is_Last_From_Where_Filter() - { - var doc = GetNode(1173); - - var items = doc - .Children - .Where(x => x.IsVisible()) - .ToIndexedArray(); - - Assert.AreEqual(4, items.Length); - - foreach (var d in items) - { - switch (d.Content.Id) - { - case 1174: - Assert.IsTrue(d.IsFirst()); - Assert.IsFalse(d.IsLast()); - break; - case 117: - Assert.IsFalse(d.IsFirst()); - Assert.IsFalse(d.IsLast()); - break; - case 1177: - Assert.IsFalse(d.IsFirst()); - Assert.IsFalse(d.IsLast()); - break; - case 1178: - Assert.IsFalse(d.IsFirst()); - Assert.IsTrue(d.IsLast()); - break; - default: - Assert.Fail("Invalid id."); - break; - } - } - } - - [PublishedModel("Home")] - internal class Home : PublishedContentModel - { - public Home(IPublishedContent content) - : base(content) - {} - } - - [PublishedModel("anything")] - internal class Anything : PublishedContentModel - { - public Anything(IPublishedContent content) - : base(content) - { } - } - - [Test] - [Ignore("Fails as long as PublishedContentModel is internal.")] // fixme - public void Is_Last_From_Where_Filter2() - { - var doc = GetNode(1173); - - var items = doc.Children - .Select(x => x.CreateModel()) // linq, returns IEnumerable - - // only way around this is to make sure every IEnumerable extension - // explicitely returns a PublishedContentSet, not an IEnumerable - - .OfType() // ours, return IEnumerable (actually a PublishedContentSet) - .Where(x => x.IsVisible()) // so, here it's linq again :-( - .ToIndexedArray(); // so, we need that one for the test to pass - - Assert.AreEqual(1, items.Length); - - foreach (var d in items) - { - switch (d.Content.Id) - { - case 1174: - Assert.IsTrue(d.IsFirst()); - Assert.IsTrue(d.IsLast()); - break; - default: - Assert.Fail("Invalid id."); - break; - } - } - } - - [Test] - public void Is_Last_From_Take() - { - var doc = GetNode(1173); - - var items = doc.Children.Take(4).ToIndexedArray(); - - foreach (var item in items) - { - if (item.Content.Id != 1178) - { - Assert.IsFalse(item.IsLast()); - } - else - { - Assert.IsTrue(item.IsLast()); - } - } - } - - [Test] - public void Is_Last_From_Skip() - { - var doc = GetNode(1173); - - foreach (var d in doc.Children.Skip(1).ToIndexedArray()) - { - if (d.Content.Id != 1176) - { - Assert.IsFalse(d.IsLast()); - } - else - { - Assert.IsTrue(d.IsLast()); - } - } - } - - [Test] - public void Is_Last_From_Concat() - { - var doc = GetNode(1173); - - var items = doc.Children - .Concat(new[] { GetNode(1175), GetNode(4444) }) - .ToIndexedArray(); - - foreach (var item in items) - { - if (item.Content.Id != 4444) - { - Assert.IsFalse(item.IsLast()); - } - else - { - Assert.IsTrue(item.IsLast()); - } - } - } - - [Test] - public void Descendants_Ordered_Properly() - { - var doc = GetNode(1046); - - var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; - var exindex = 0; - - // must respect the XPath descendants-or-self axis! - foreach (var d in doc.DescendantsOrSelf()) - Assert.AreEqual(expected[exindex++], d.Id); - } - - [Test] - public void Get_Property_Value_Recursive() - { - var doc = GetNode(1174); - var rVal = doc.Value("testRecursive", fallback: Fallback.ToAncestors); - var nullVal = doc.Value("DoNotFindThis", fallback: Fallback.ToAncestors); - Assert.AreEqual("This is the recursive val", rVal); - Assert.AreEqual(null, nullVal); - } - - [Test] - public void Get_Property_Value_Uses_Converter() - { - var doc = GetNode(1173); - - var propVal = doc.Value("content"); - Assert.IsInstanceOf(typeof(IHtmlString), propVal); - Assert.AreEqual("
This is some content
", propVal.ToString()); - - var propVal2 = doc.Value("content"); - Assert.IsInstanceOf(typeof(IHtmlString), propVal2); - Assert.AreEqual("
This is some content
", propVal2.ToString()); - - var propVal3 = doc.Value("Content"); - Assert.IsInstanceOf(typeof(IHtmlString), propVal3); - Assert.AreEqual("
This is some content
", propVal3.ToString()); - } - - [Test] - public void Complex_Linq() - { - var doc = GetNode(1173); - - var result = doc.Ancestors().OrderBy(x => x.Level) - .Single() - .Descendants() - .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); - - Assert.IsNotNull(result); - } - - [Test] - public void Children_GroupBy_DocumentTypeAlias() - { - var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); - var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); - var contentTypes = new Dictionary - { - { home.Alias, home }, - { custom.Alias, custom } - }; - ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; - - var doc = GetNode(1046); - - var found1 = doc.Children.GroupBy(x => x.ContentType.Alias).ToArray(); - - Assert.AreEqual(2, found1.Length); - Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count()); - Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count()); - } - - [Test] - public void Children_Where_DocumentTypeAlias() - { - var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); - var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); - var contentTypes = new Dictionary - { - { home.Alias, home }, - { custom.Alias, custom } - }; - ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; - - var doc = GetNode(1046); - - var found1 = doc.Children.Where(x => x.ContentType.Alias == "CustomDocument"); - var found2 = doc.Children.Where(x => x.ContentType.Alias == "Home"); - - Assert.AreEqual(1, found1.Count()); - Assert.AreEqual(2, found2.Count()); - } - - [Test] - public void Children_Order_By_Update_Date() - { - var doc = GetNode(1173); - - var ordered = doc.Children.OrderBy(x => x.UpdateDate); - - var correctOrder = new[] { 1178, 1177, 1174, 1176 }; - for (var i = 0; i < correctOrder.Length; i++) - { - Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id); - } - - } - - [Test] - public void FirstChild() - { - var doc = GetNode(1173); // has child nodes - Assert.IsNotNull(doc.FirstChild()); - Assert.IsNotNull(doc.FirstChild(x => true)); - Assert.IsNotNull(doc.FirstChild()); - - doc = GetNode(1175); // does not have child nodes - Assert.IsNull(doc.FirstChild()); - Assert.IsNull(doc.FirstChild(x => true)); - Assert.IsNull(doc.FirstChild()); - } - - [Test] - public void FirstChildAsT() - { - var doc = GetNode(1046); // has child nodes - - var model = doc.FirstChild(x => true); // predicate - - Assert.IsNotNull(model); - Assert.IsTrue(model.Id == 1173); - Assert.IsInstanceOf(model); - Assert.IsInstanceOf(model); - - doc = GetNode(1175); // does not have child nodes - Assert.IsNull(doc.FirstChild()); - Assert.IsNull(doc.FirstChild(x => true)); - } - - [Test] - public void IsComposedOf() - { - var doc = GetNode(1173); - - var isComposedOf = doc.IsComposedOf("MyCompositionAlias"); - - Assert.IsTrue(isComposedOf); - } - - [Test] - public void HasProperty() - { - var doc = GetNode(1173); - - var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias); - - Assert.IsTrue(hasProp); - } - - [Test] - public void HasValue() - { - var doc = GetNode(1173); - - var hasValue = doc.HasValue(Constants.Conventions.Content.UrlAlias); - var noValue = doc.HasValue("blahblahblah"); - - Assert.IsTrue(hasValue); - Assert.IsFalse(noValue); - } - - [Test] - public void Ancestors_Where_Visible() - { - var doc = GetNode(1174); - - var whereVisible = doc.Ancestors().Where(x => x.IsVisible()); - Assert.AreEqual(1, whereVisible.Count()); - - } - - [Test] - public void Visible() - { - var hidden = GetNode(1046); - var visible = GetNode(1173); - - Assert.IsFalse(hidden.IsVisible()); - Assert.IsTrue(visible.IsVisible()); - } - - [Test] - public void Ancestor_Or_Self() - { - var doc = GetNode(1173); - - var result = doc.AncestorOrSelf(); - - Assert.IsNotNull(result); - - // ancestor-or-self has to be self! - Assert.AreEqual(1173, result.Id); - } - - [Test] - public void U4_4559() - { - var doc = GetNode(1174); - var result = doc.AncestorOrSelf(1); - Assert.IsNotNull(result); - Assert.AreEqual(1046, result.Id); - } - - [Test] - public void Ancestors_Or_Self() - { - var doc = GetNode(1174); - - var result = doc.AncestorsOrSelf().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(3, result.Length); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 })); - } - - [Test] - public void Ancestors() - { - var doc = GetNode(1174); - - var result = doc.Ancestors().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(2, result.Length); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 })); - } - - [Test] - public void IsAncestor() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsTrue(root.IsAncestor(customDoc4)); - Assert.IsFalse(root.IsAncestor(customDoc3)); - Assert.IsTrue(root.IsAncestor(customDoc2)); - Assert.IsTrue(root.IsAncestor(customDoc)); - Assert.IsTrue(root.IsAncestor(home)); - Assert.IsFalse(root.IsAncestor(root)); - - Assert.IsTrue(home.IsAncestor(customDoc4)); - Assert.IsFalse(home.IsAncestor(customDoc3)); - Assert.IsTrue(home.IsAncestor(customDoc2)); - Assert.IsTrue(home.IsAncestor(customDoc)); - Assert.IsFalse(home.IsAncestor(home)); - Assert.IsFalse(home.IsAncestor(root)); - - Assert.IsFalse(customDoc.IsAncestor(customDoc4)); - Assert.IsFalse(customDoc.IsAncestor(customDoc3)); - Assert.IsTrue(customDoc.IsAncestor(customDoc2)); - Assert.IsFalse(customDoc.IsAncestor(customDoc)); - Assert.IsFalse(customDoc.IsAncestor(home)); - Assert.IsFalse(customDoc.IsAncestor(root)); - - Assert.IsFalse(customDoc2.IsAncestor(customDoc4)); - Assert.IsFalse(customDoc2.IsAncestor(customDoc3)); - Assert.IsFalse(customDoc2.IsAncestor(customDoc2)); - Assert.IsFalse(customDoc2.IsAncestor(customDoc)); - Assert.IsFalse(customDoc2.IsAncestor(home)); - Assert.IsFalse(customDoc2.IsAncestor(root)); - - Assert.IsFalse(customDoc3.IsAncestor(customDoc3)); - } - - [Test] - public void IsAncestorOrSelf() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsTrue(root.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(root.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(root.IsAncestorOrSelf(customDoc2)); - Assert.IsTrue(root.IsAncestorOrSelf(customDoc)); - Assert.IsTrue(root.IsAncestorOrSelf(home)); - Assert.IsTrue(root.IsAncestorOrSelf(root)); - - Assert.IsTrue(home.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(home.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(home.IsAncestorOrSelf(customDoc2)); - Assert.IsTrue(home.IsAncestorOrSelf(customDoc)); - Assert.IsTrue(home.IsAncestorOrSelf(home)); - Assert.IsFalse(home.IsAncestorOrSelf(root)); - - Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc2)); - Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc)); - Assert.IsFalse(customDoc.IsAncestorOrSelf(home)); - Assert.IsFalse(customDoc.IsAncestorOrSelf(root)); - - Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(customDoc2.IsAncestorOrSelf(customDoc2)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(home)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(root)); - - Assert.IsTrue(customDoc4.IsAncestorOrSelf(customDoc4)); - Assert.IsTrue(customDoc3.IsAncestorOrSelf(customDoc3)); - } - - - [Test] - public void Descendants_Or_Self() - { - var doc = GetNode(1046); - - var result = doc.DescendantsOrSelf().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(10, result.Count()); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); - } - - [Test] - public void Descendants() - { - var doc = GetNode(1046); - - var result = doc.Descendants().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(9, result.Count()); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); - } - - [Test] - public void IsDescendant() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsFalse(root.IsDescendant(root)); - Assert.IsFalse(root.IsDescendant(home)); - Assert.IsFalse(root.IsDescendant(customDoc)); - Assert.IsFalse(root.IsDescendant(customDoc2)); - Assert.IsFalse(root.IsDescendant(customDoc3)); - Assert.IsFalse(root.IsDescendant(customDoc4)); - - Assert.IsTrue(home.IsDescendant(root)); - Assert.IsFalse(home.IsDescendant(home)); - Assert.IsFalse(home.IsDescendant(customDoc)); - Assert.IsFalse(home.IsDescendant(customDoc2)); - Assert.IsFalse(home.IsDescendant(customDoc3)); - Assert.IsFalse(home.IsDescendant(customDoc4)); - - Assert.IsTrue(customDoc.IsDescendant(root)); - Assert.IsTrue(customDoc.IsDescendant(home)); - Assert.IsFalse(customDoc.IsDescendant(customDoc)); - Assert.IsFalse(customDoc.IsDescendant(customDoc2)); - Assert.IsFalse(customDoc.IsDescendant(customDoc3)); - Assert.IsFalse(customDoc.IsDescendant(customDoc4)); - - Assert.IsTrue(customDoc2.IsDescendant(root)); - Assert.IsTrue(customDoc2.IsDescendant(home)); - Assert.IsTrue(customDoc2.IsDescendant(customDoc)); - Assert.IsFalse(customDoc2.IsDescendant(customDoc2)); - Assert.IsFalse(customDoc2.IsDescendant(customDoc3)); - Assert.IsFalse(customDoc2.IsDescendant(customDoc4)); - - Assert.IsFalse(customDoc3.IsDescendant(customDoc3)); - } - - [Test] - public void IsDescendantOrSelf() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsTrue(root.IsDescendantOrSelf(root)); - Assert.IsFalse(root.IsDescendantOrSelf(home)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(home.IsDescendantOrSelf(root)); - Assert.IsTrue(home.IsDescendantOrSelf(home)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(customDoc.IsDescendantOrSelf(root)); - Assert.IsTrue(customDoc.IsDescendantOrSelf(home)); - Assert.IsTrue(customDoc.IsDescendantOrSelf(customDoc)); - Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(customDoc2.IsDescendantOrSelf(root)); - Assert.IsTrue(customDoc2.IsDescendantOrSelf(home)); - Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc)); - Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(customDoc3.IsDescendantOrSelf(customDoc3)); - } - - [Test] - public void Up() - { - var doc = GetNode(1173); - - var result = doc.Up(); - - Assert.IsNotNull(result); - - Assert.AreEqual(1046, result.Id); - } - - [Test] - public void Down() - { - var doc = GetNode(1173); - - var result = doc.Down(); - - Assert.IsNotNull(result); - - Assert.AreEqual(1174, result.Id); - } - - [Test] - public void FragmentProperty() - { - var factory = Factory.GetInstance() as PublishedContentTypeFactory; - - var pt = factory.CreatePropertyType("detached", 1003); - var ct = factory.CreateContentType(0, "alias", new[] { pt }); - var prop = new PublishedElementPropertyBase(pt, null, false, PropertyCacheLevel.None, 5548); - Assert.IsInstanceOf(prop.GetValue()); - Assert.AreEqual(5548, prop.GetValue()); - } - - public void Fragment1() - { - var type = ContentTypesCache.Get(PublishedItemType.Content, "detachedSomething"); - var values = new Dictionary(); - var f = new PublishedElement(type, Guid.NewGuid(), values, false); - } - - [Test] - public void Fragment2() - { - var factory = Factory.GetInstance() as PublishedContentTypeFactory; - - var pt1 = factory.CreatePropertyType("legend", 1004); - var pt2 = factory.CreatePropertyType("image", 1005); - var pt3 = factory.CreatePropertyType("size", 1003); - const string val1 = "boom bam"; - const int val2 = 0; - const int val3 = 666; - - var guid = Guid.NewGuid(); - - var ct = factory.CreateContentType(0, "alias", new[] { pt1, pt2, pt3 }); - - var c = new ImageWithLegendModel(ct, guid, new Dictionary - { - { "legend", val1 }, - { "image", val2 }, - { "size", val3 }, - }, false); - - Assert.AreEqual(val1, c.Legend); - Assert.AreEqual(val3, c.Size); - } - - class ImageWithLegendModel : PublishedElement - { - public ImageWithLegendModel(PublishedContentType contentType, Guid fragmentKey, Dictionary values, bool previewing) - : base(contentType, fragmentKey, values, previewing) - { } - - - public string Legend => this.Value("legend"); - - public IPublishedContent Image => this.Value("image"); - - public int Size => this.Value("size"); - } - } -} +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Web; +//using NUnit.Framework; +//using Umbraco.Core; +//using Umbraco.Core.Models.PublishedContent; +//using Umbraco.Core.PropertyEditors; +//using Umbraco.Web; +//using Umbraco.Web.PublishedCache; +//using Umbraco.Core.Composing; +//using Moq; +//using Umbraco.Core.Cache; +//using Umbraco.Core.Configuration; +//using Umbraco.Core.Logging; +//using Umbraco.Core.Models; +//using Umbraco.Core.Services; +//using Umbraco.Tests.TestHelpers; +//using Umbraco.Tests.Testing; +//using Umbraco.Web.Models.PublishedContent; +//using Umbraco.Web.PropertyEditors; +// +//namespace Umbraco.Tests.PublishedContent +//{ +// /// +// /// Tests the methods on IPublishedContent using the DefaultPublishedContentStore +// /// +// [TestFixture] +// [UmbracoTest(TypeLoader = UmbracoTestOptions.TypeLoader.PerFixture)] +// public class PublishedContentTests : PublishedContentTestBase +// { +// protected override void Compose() +// { +// base.Compose(); +// +// Composition.RegisterUnique(f => new PublishedModelFactory(f.GetInstance().GetTypes())); +// Composition.RegisterUnique(); +// Composition.RegisterUnique(); +// +// var logger = Mock.Of(); +// var dataTypeService = new TestObjects.TestDataTypeService( +// new DataType(new VoidEditor(logger)) { Id = 1 }, +// new DataType(new TrueFalsePropertyEditor(logger)) { Id = 1001 }, +// new DataType(new RichTextPropertyEditor(logger)) { Id = 1002 }, +// new DataType(new IntegerPropertyEditor(logger)) { Id = 1003 }, +// new DataType(new TextboxPropertyEditor(logger)) { Id = 1004 }, +// new DataType(new MediaPickerPropertyEditor(logger)) { Id = 1005 }); +// Composition.RegisterUnique(f => dataTypeService); +// } +// +// protected override void Initialize() +// { +// base.Initialize(); +// +// var factory = Factory.GetInstance() as PublishedContentTypeFactory; +// +// // need to specify a custom callback for unit tests +// // AutoPublishedContentTypes generates properties automatically +// // when they are requested, but we must declare those that we +// // explicitely want to be here... +// +// var propertyTypes = new[] +// { +// // AutoPublishedContentType will auto-generate other properties +// factory.CreatePropertyType("umbracoNaviHide", 1001), +// factory.CreatePropertyType("selectedNodes", 1), +// factory.CreatePropertyType("umbracoUrlAlias", 1), +// factory.CreatePropertyType("content", 1002), +// factory.CreatePropertyType("testRecursive", 1), +// }; +// var compositionAliases = new[] { "MyCompositionAlias" }; +// var type = new AutoPublishedContentType(0, "anything", compositionAliases, propertyTypes); +// ContentTypesCache.GetPublishedContentTypeByAlias = alias => type; +// } +// +// protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) +// { +// var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); +// +// // this is so the model factory looks into the test assembly +// pluginManager.AssembliesToScan = pluginManager.AssembliesToScan +// .Union(new[] { typeof(PublishedContentTests).Assembly }) +// .ToList(); +// +// return pluginManager; +// } +// +// private readonly Guid _node1173Guid = Guid.NewGuid(); +// +// protected override string GetXmlContent(int templateId) +// { +// return @" +// +// +// +// +//]> +// +// +// +// +// 1 +// +// +// This is some content]]> +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// 1 +// +// +// +// +// +// +// +// +// +//"; +// } +// +// internal IPublishedContent GetNode(int id) +// { +// var ctx = GetUmbracoContext("/test"); +// var doc = ctx.ContentCache.GetById(id); +// Assert.IsNotNull(doc); +// return doc; +// } +// +// [Test] +// public void GetNodeByIds() +// { +// var ctx = GetUmbracoContext("/test"); +// var contentById = ctx.ContentCache.GetById(1173); +// Assert.IsNotNull(contentById); +// var contentByGuid = ctx.ContentCache.GetById(_node1173Guid); +// Assert.IsNotNull(contentByGuid); +// Assert.AreEqual(contentById.Id, contentByGuid.Id); +// Assert.AreEqual(contentById.Key, contentByGuid.Key); +// +// contentById = ctx.ContentCache.GetById(666); +// Assert.IsNull(contentById); +// contentByGuid = ctx.ContentCache.GetById(Guid.NewGuid()); +// Assert.IsNull(contentByGuid); +// } +// +// [Test] +// public void Is_Last_From_Where_Filter_Dynamic_Linq() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children.Where(x => x.IsVisible()).ToIndexedArray(); +// +// foreach (var item in items) +// { +// if (item.Content.Id != 1178) +// { +// Assert.IsFalse(item.IsLast()); +// } +// else +// { +// Assert.IsTrue(item.IsLast()); +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Where_Filter() +// { +// var doc = GetNode(1173); +// +// var items = doc +// .Children +// .Where(x => x.IsVisible()) +// .ToIndexedArray(); +// +// Assert.AreEqual(4, items.Length); +// +// foreach (var d in items) +// { +// switch (d.Content.Id) +// { +// case 1174: +// Assert.IsTrue(d.IsFirst()); +// Assert.IsFalse(d.IsLast()); +// break; +// case 117: +// Assert.IsFalse(d.IsFirst()); +// Assert.IsFalse(d.IsLast()); +// break; +// case 1177: +// Assert.IsFalse(d.IsFirst()); +// Assert.IsFalse(d.IsLast()); +// break; +// case 1178: +// Assert.IsFalse(d.IsFirst()); +// Assert.IsTrue(d.IsLast()); +// break; +// default: +// Assert.Fail("Invalid id."); +// break; +// } +// } +// } +// +// [PublishedModel("Home")] +// internal class Home : PublishedContentModel +// { +// public Home(IPublishedContent content) +// : base(content) +// {} +// } +// +// [PublishedModel("anything")] +// internal class Anything : PublishedContentModel +// { +// public Anything(IPublishedContent content) +// : base(content) +// { } +// } +// +// [Test] +// [Ignore("Fails as long as PublishedContentModel is internal.")] // fixme +// public void Is_Last_From_Where_Filter2() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children +// .Select(x => x.CreateModel()) // linq, returns IEnumerable +// +// // only way around this is to make sure every IEnumerable extension +// // explicitely returns a PublishedContentSet, not an IEnumerable +// +// .OfType() // ours, return IEnumerable (actually a PublishedContentSet) +// .Where(x => x.IsVisible()) // so, here it's linq again :-( +// .ToIndexedArray(); // so, we need that one for the test to pass +// +// Assert.AreEqual(1, items.Length); +// +// foreach (var d in items) +// { +// switch (d.Content.Id) +// { +// case 1174: +// Assert.IsTrue(d.IsFirst()); +// Assert.IsTrue(d.IsLast()); +// break; +// default: +// Assert.Fail("Invalid id."); +// break; +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Take() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children.Take(4).ToIndexedArray(); +// +// foreach (var item in items) +// { +// if (item.Content.Id != 1178) +// { +// Assert.IsFalse(item.IsLast()); +// } +// else +// { +// Assert.IsTrue(item.IsLast()); +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Skip() +// { +// var doc = GetNode(1173); +// +// foreach (var d in doc.Children.Skip(1).ToIndexedArray()) +// { +// if (d.Content.Id != 1176) +// { +// Assert.IsFalse(d.IsLast()); +// } +// else +// { +// Assert.IsTrue(d.IsLast()); +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Concat() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children +// .Concat(new[] { GetNode(1175), GetNode(4444) }) +// .ToIndexedArray(); +// +// foreach (var item in items) +// { +// if (item.Content.Id != 4444) +// { +// Assert.IsFalse(item.IsLast()); +// } +// else +// { +// Assert.IsTrue(item.IsLast()); +// } +// } +// } +// +// [Test] +// public void Descendants_Ordered_Properly() +// { +// var doc = GetNode(1046); +// +// var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; +// var exindex = 0; +// +// // must respect the XPath descendants-or-self axis! +// foreach (var d in doc.DescendantsOrSelf()) +// Assert.AreEqual(expected[exindex++], d.Id); +// } +// +// [Test] +// public void Get_Property_Value_Recursive() +// { +// var doc = GetNode(1174); +// var rVal = doc.Value("testRecursive", fallback: Fallback.ToAncestors); +// var nullVal = doc.Value("DoNotFindThis", fallback: Fallback.ToAncestors); +// Assert.AreEqual("This is the recursive val", rVal); +// Assert.AreEqual(null, nullVal); +// } +// +// [Test] +// public void Get_Property_Value_Uses_Converter() +// { +// var doc = GetNode(1173); +// +// var propVal = doc.Value("content"); +// Assert.IsInstanceOf(typeof(IHtmlString), propVal); +// Assert.AreEqual("
This is some content
", propVal.ToString()); +// +// var propVal2 = doc.Value("content"); +// Assert.IsInstanceOf(typeof(IHtmlString), propVal2); +// Assert.AreEqual("
This is some content
", propVal2.ToString()); +// +// var propVal3 = doc.Value("Content"); +// Assert.IsInstanceOf(typeof(IHtmlString), propVal3); +// Assert.AreEqual("
This is some content
", propVal3.ToString()); +// } +// +// [Test] +// public void Complex_Linq() +// { +// var doc = GetNode(1173); +// +// var result = doc.Ancestors().OrderBy(x => x.Level) +// .Single() +// .Descendants() +// .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); +// +// Assert.IsNotNull(result); +// } +// +// [Test] +// public void Children_GroupBy_DocumentTypeAlias() +// { +// var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); +// var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); +// var contentTypes = new Dictionary +// { +// { home.Alias, home }, +// { custom.Alias, custom } +// }; +// ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; +// +// var doc = GetNode(1046); +// +// var found1 = doc.Children.GroupBy(x => x.ContentType.Alias).ToArray(); +// +// Assert.AreEqual(2, found1.Length); +// Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count()); +// Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count()); +// } +// +// [Test] +// public void Children_Where_DocumentTypeAlias() +// { +// var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); +// var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); +// var contentTypes = new Dictionary +// { +// { home.Alias, home }, +// { custom.Alias, custom } +// }; +// ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; +// +// var doc = GetNode(1046); +// +// var found1 = doc.Children.Where(x => x.ContentType.Alias == "CustomDocument"); +// var found2 = doc.Children.Where(x => x.ContentType.Alias == "Home"); +// +// Assert.AreEqual(1, found1.Count()); +// Assert.AreEqual(2, found2.Count()); +// } +// +// [Test] +// public void Children_Order_By_Update_Date() +// { +// var doc = GetNode(1173); +// +// var ordered = doc.Children.OrderBy(x => x.UpdateDate); +// +// var correctOrder = new[] { 1178, 1177, 1174, 1176 }; +// for (var i = 0; i < correctOrder.Length; i++) +// { +// Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id); +// } +// +// } +// +// [Test] +// public void FirstChild() +// { +// var doc = GetNode(1173); // has child nodes +// Assert.IsNotNull(doc.FirstChild()); +// Assert.IsNotNull(doc.FirstChild(x => true)); +// Assert.IsNotNull(doc.FirstChild()); +// +// doc = GetNode(1175); // does not have child nodes +// Assert.IsNull(doc.FirstChild()); +// Assert.IsNull(doc.FirstChild(x => true)); +// Assert.IsNull(doc.FirstChild()); +// } +// +// [Test] +// public void FirstChildAsT() +// { +// var doc = GetNode(1046); // has child nodes +// +// var model = doc.FirstChild(x => true); // predicate +// +// Assert.IsNotNull(model); +// Assert.IsTrue(model.Id == 1173); +// Assert.IsInstanceOf(model); +// Assert.IsInstanceOf(model); +// +// doc = GetNode(1175); // does not have child nodes +// Assert.IsNull(doc.FirstChild()); +// Assert.IsNull(doc.FirstChild(x => true)); +// } +// +// [Test] +// public void IsComposedOf() +// { +// var doc = GetNode(1173); +// +// var isComposedOf = doc.IsComposedOf("MyCompositionAlias"); +// +// Assert.IsTrue(isComposedOf); +// } +// +// [Test] +// public void HasProperty() +// { +// var doc = GetNode(1173); +// +// var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias); +// +// Assert.IsTrue(hasProp); +// } +// +// [Test] +// public void HasValue() +// { +// var doc = GetNode(1173); +// +// var hasValue = doc.HasValue(Constants.Conventions.Content.UrlAlias); +// var noValue = doc.HasValue("blahblahblah"); +// +// Assert.IsTrue(hasValue); +// Assert.IsFalse(noValue); +// } +// +// [Test] +// public void Ancestors_Where_Visible() +// { +// var doc = GetNode(1174); +// +// var whereVisible = doc.Ancestors().Where(x => x.IsVisible()); +// Assert.AreEqual(1, whereVisible.Count()); +// +// } +// +// [Test] +// public void Visible() +// { +// var hidden = GetNode(1046); +// var visible = GetNode(1173); +// +// Assert.IsFalse(hidden.IsVisible()); +// Assert.IsTrue(visible.IsVisible()); +// } +// +// [Test] +// public void Ancestor_Or_Self() +// { +// var doc = GetNode(1173); +// +// var result = doc.AncestorOrSelf(); +// +// Assert.IsNotNull(result); +// +// // ancestor-or-self has to be self! +// Assert.AreEqual(1173, result.Id); +// } +// +// [Test] +// public void U4_4559() +// { +// var doc = GetNode(1174); +// var result = doc.AncestorOrSelf(1); +// Assert.IsNotNull(result); +// Assert.AreEqual(1046, result.Id); +// } +// +// [Test] +// public void Ancestors_Or_Self() +// { +// var doc = GetNode(1174); +// +// var result = doc.AncestorsOrSelf().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(3, result.Length); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 })); +// } +// +// [Test] +// public void Ancestors() +// { +// var doc = GetNode(1174); +// +// var result = doc.Ancestors().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(2, result.Length); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 })); +// } +// +// [Test] +// public void IsAncestor() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsTrue(root.IsAncestor(customDoc4)); +// Assert.IsFalse(root.IsAncestor(customDoc3)); +// Assert.IsTrue(root.IsAncestor(customDoc2)); +// Assert.IsTrue(root.IsAncestor(customDoc)); +// Assert.IsTrue(root.IsAncestor(home)); +// Assert.IsFalse(root.IsAncestor(root)); +// +// Assert.IsTrue(home.IsAncestor(customDoc4)); +// Assert.IsFalse(home.IsAncestor(customDoc3)); +// Assert.IsTrue(home.IsAncestor(customDoc2)); +// Assert.IsTrue(home.IsAncestor(customDoc)); +// Assert.IsFalse(home.IsAncestor(home)); +// Assert.IsFalse(home.IsAncestor(root)); +// +// Assert.IsFalse(customDoc.IsAncestor(customDoc4)); +// Assert.IsFalse(customDoc.IsAncestor(customDoc3)); +// Assert.IsTrue(customDoc.IsAncestor(customDoc2)); +// Assert.IsFalse(customDoc.IsAncestor(customDoc)); +// Assert.IsFalse(customDoc.IsAncestor(home)); +// Assert.IsFalse(customDoc.IsAncestor(root)); +// +// Assert.IsFalse(customDoc2.IsAncestor(customDoc4)); +// Assert.IsFalse(customDoc2.IsAncestor(customDoc3)); +// Assert.IsFalse(customDoc2.IsAncestor(customDoc2)); +// Assert.IsFalse(customDoc2.IsAncestor(customDoc)); +// Assert.IsFalse(customDoc2.IsAncestor(home)); +// Assert.IsFalse(customDoc2.IsAncestor(root)); +// +// Assert.IsFalse(customDoc3.IsAncestor(customDoc3)); +// } +// +// [Test] +// public void IsAncestorOrSelf() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsTrue(root.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(root.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(root.IsAncestorOrSelf(customDoc2)); +// Assert.IsTrue(root.IsAncestorOrSelf(customDoc)); +// Assert.IsTrue(root.IsAncestorOrSelf(home)); +// Assert.IsTrue(root.IsAncestorOrSelf(root)); +// +// Assert.IsTrue(home.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(home.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(home.IsAncestorOrSelf(customDoc2)); +// Assert.IsTrue(home.IsAncestorOrSelf(customDoc)); +// Assert.IsTrue(home.IsAncestorOrSelf(home)); +// Assert.IsFalse(home.IsAncestorOrSelf(root)); +// +// Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc2)); +// Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc)); +// Assert.IsFalse(customDoc.IsAncestorOrSelf(home)); +// Assert.IsFalse(customDoc.IsAncestorOrSelf(root)); +// +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(customDoc2.IsAncestorOrSelf(customDoc2)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(home)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(root)); +// +// Assert.IsTrue(customDoc4.IsAncestorOrSelf(customDoc4)); +// Assert.IsTrue(customDoc3.IsAncestorOrSelf(customDoc3)); +// } +// +// +// [Test] +// public void Descendants_Or_Self() +// { +// var doc = GetNode(1046); +// +// var result = doc.DescendantsOrSelf().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(10, result.Count()); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); +// } +// +// [Test] +// public void Descendants() +// { +// var doc = GetNode(1046); +// +// var result = doc.Descendants().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(9, result.Count()); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); +// } +// +// [Test] +// public void IsDescendant() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsFalse(root.IsDescendant(root)); +// Assert.IsFalse(root.IsDescendant(home)); +// Assert.IsFalse(root.IsDescendant(customDoc)); +// Assert.IsFalse(root.IsDescendant(customDoc2)); +// Assert.IsFalse(root.IsDescendant(customDoc3)); +// Assert.IsFalse(root.IsDescendant(customDoc4)); +// +// Assert.IsTrue(home.IsDescendant(root)); +// Assert.IsFalse(home.IsDescendant(home)); +// Assert.IsFalse(home.IsDescendant(customDoc)); +// Assert.IsFalse(home.IsDescendant(customDoc2)); +// Assert.IsFalse(home.IsDescendant(customDoc3)); +// Assert.IsFalse(home.IsDescendant(customDoc4)); +// +// Assert.IsTrue(customDoc.IsDescendant(root)); +// Assert.IsTrue(customDoc.IsDescendant(home)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc2)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc3)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc4)); +// +// Assert.IsTrue(customDoc2.IsDescendant(root)); +// Assert.IsTrue(customDoc2.IsDescendant(home)); +// Assert.IsTrue(customDoc2.IsDescendant(customDoc)); +// Assert.IsFalse(customDoc2.IsDescendant(customDoc2)); +// Assert.IsFalse(customDoc2.IsDescendant(customDoc3)); +// Assert.IsFalse(customDoc2.IsDescendant(customDoc4)); +// +// Assert.IsFalse(customDoc3.IsDescendant(customDoc3)); +// } +// +// [Test] +// public void IsDescendantOrSelf() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsTrue(root.IsDescendantOrSelf(root)); +// Assert.IsFalse(root.IsDescendantOrSelf(home)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(home.IsDescendantOrSelf(root)); +// Assert.IsTrue(home.IsDescendantOrSelf(home)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(customDoc.IsDescendantOrSelf(root)); +// Assert.IsTrue(customDoc.IsDescendantOrSelf(home)); +// Assert.IsTrue(customDoc.IsDescendantOrSelf(customDoc)); +// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(root)); +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(home)); +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc)); +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(customDoc3.IsDescendantOrSelf(customDoc3)); +// } +// +// [Test] +// public void Up() +// { +// var doc = GetNode(1173); +// +// var result = doc.Up(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(1046, result.Id); +// } +// +// [Test] +// public void Down() +// { +// var doc = GetNode(1173); +// +// var result = doc.Down(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(1174, result.Id); +// } +// +// [Test] +// public void FragmentProperty() +// { +// var factory = Factory.GetInstance() as PublishedContentTypeFactory; +// +// var pt = factory.CreatePropertyType("detached", 1003); +// var ct = factory.CreateContentType(0, "alias", new[] { pt }); +// var prop = new PublishedElementPropertyBase(pt, null, false, PropertyCacheLevel.None, 5548); +// Assert.IsInstanceOf(prop.GetValue()); +// Assert.AreEqual(5548, prop.GetValue()); +// } +// +// public void Fragment1() +// { +// var type = ContentTypesCache.Get(PublishedItemType.Content, "detachedSomething"); +// var values = new Dictionary(); +// var f = new PublishedElement(type, Guid.NewGuid(), values, false); +// } +// +// [Test] +// public void Fragment2() +// { +// var factory = Factory.GetInstance() as PublishedContentTypeFactory; +// +// var pt1 = factory.CreatePropertyType("legend", 1004); +// var pt2 = factory.CreatePropertyType("image", 1005); +// var pt3 = factory.CreatePropertyType("size", 1003); +// const string val1 = "boom bam"; +// const int val2 = 0; +// const int val3 = 666; +// +// var guid = Guid.NewGuid(); +// +// var ct = factory.CreateContentType(0, "alias", new[] { pt1, pt2, pt3 }); +// +// var c = new ImageWithLegendModel(ct, guid, new Dictionary +// { +// { "legend", val1 }, +// { "image", val2 }, +// { "size", val3 }, +// }, false); +// +// Assert.AreEqual(val1, c.Legend); +// Assert.AreEqual(val3, c.Size); +// } +// +// class ImageWithLegendModel : PublishedElement +// { +// public ImageWithLegendModel(PublishedContentType contentType, Guid fragmentKey, Dictionary values, bool previewing) +// : base(contentType, fragmentKey, values, previewing) +// { } +// +// +// public string Legend => this.Value("legend"); +// +// public IPublishedContent Image => this.Value("image"); +// +// public int Size => this.Value("size"); +// } +// } +//} diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index 88b211d0ee..f88f37a972 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -1,508 +1,508 @@ -using System.Web; -using System.Xml.Linq; -using System.Xml.XPath; -using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Models; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Entities; -using Umbraco.Tests.UmbracoExamine; -using Umbraco.Web; -using Umbraco.Web.PublishedCache.XmlPublishedCache; -using System.Linq; -using System.Threading; -using System.Xml; -using Examine; -using Umbraco.Core.Cache; -using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.Strings; -using Umbraco.Examine; -using Current = Umbraco.Web.Composing.Current; -using Umbraco.Tests.Testing; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.PropertyEditors; - -namespace Umbraco.Tests.PublishedContent -{ - /// - /// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore - /// - [TestFixture] - [Apartment(ApartmentState.STA)] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, WithApplication = true)] - public class PublishedMediaTests : PublishedContentTestBase - { - /// - /// sets up resolvers before resolution is frozen - /// - protected override void Compose() - { - base.Compose(); - - Composition.WithCollectionBuilder() - .Clear() - .Append(); - } - - private IMediaType MakeNewMediaType(IUser user, string text, int parentId = -1) - { - var mt = new MediaType(parentId) { Name = text, Alias = text, Thumbnail = "icon-folder", Icon = "icon-folder" }; - ServiceContext.MediaTypeService.Save(mt); - return mt; - } - - private IMedia MakeNewMedia(string name, IMediaType mediaType, IUser user, int parentId) - { - var m = ServiceContext.MediaService.CreateMediaWithIdentity(name, parentId, mediaType.Alias); - return m; - } - - /// - /// Shared with PublishMediaStoreTests - /// - /// - /// - /// - internal IPublishedContent GetNode(int id, UmbracoContext umbracoContext) - { - var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new StaticCacheProvider(), ContentTypesCache); - var doc = cache.GetById(id); - Assert.IsNotNull(doc); - return doc; - } - - private IPublishedContent GetNode(int id) - { - return GetNode(id, GetUmbracoContext("/test")); - } - - [Test] - public void Get_Property_Value_Uses_Converter() - { - var mType = MockedContentTypes.CreateImageMediaType("image2"); - //lets add an RTE to this - mType.PropertyGroups.First().PropertyTypes.Add( - new PropertyType("test", ValueStorageType.Nvarchar, "content") - { - Name = "Rich Text", - DataTypeId = -87 //tiny mce - }); - ServiceContext.MediaTypeService.Save(mType); - var media = MockedMedia.CreateMediaImage(mType, -1); - media.Properties["content"].SetValue("
This is some content
"); - ServiceContext.MediaService.Save(media); - - var publishedMedia = GetNode(media.Id); - - var propVal = publishedMedia.Value("content"); - Assert.IsInstanceOf(propVal); - Assert.AreEqual("
This is some content
", propVal.ToString()); - - var propVal2 = publishedMedia.Value("content"); - Assert.IsInstanceOf(propVal2); - Assert.AreEqual("
This is some content
", propVal2.ToString()); - - var propVal3 = publishedMedia.Value("Content"); - Assert.IsInstanceOf(propVal3); - Assert.AreEqual("
This is some content
", propVal3.ToString()); - } - - [Test] - public void Ensure_Children_Sorted_With_Examine() - { - var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); - - using (var luceneDir = new RandomIdRamDirectory()) - using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, - validator: new ContentValueSetValidator(true))) - using (indexer.ProcessNonAsync()) - { - rebuilder.RegisterIndex(indexer.Name); - rebuilder.Populate(indexer); - - var searcher = indexer.GetSearcher(); - var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); - - //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace - var publishedMedia = cache.GetById(1111); - var rootChildren = publishedMedia.Children().ToArray(); - var currSort = 0; - for (var i = 0; i < rootChildren.Count(); i++) - { - Assert.GreaterOrEqual(rootChildren[i].SortOrder, currSort); - currSort = rootChildren[i].SortOrder; - } - } - } - - [Test] - public void Do_Not_Find_In_Recycle_Bin() - { - var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); - - using (var luceneDir = new RandomIdRamDirectory()) - using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, - //include unpublished content since this uses the 'internal' indexer, it's up to the media cache to filter - validator: new ContentValueSetValidator(false))) - using (indexer.ProcessNonAsync()) - { - rebuilder.RegisterIndex(indexer.Name); - rebuilder.Populate(indexer); - - var searcher = indexer.GetSearcher(); - var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); - - //ensure it is found - var publishedMedia = cache.GetById(3113); - Assert.IsNotNull(publishedMedia); - - //move item to recycle bin - var newXml = XElement.Parse(@" - - 115 - 268 - 10726 - jpg - "); - indexer.IndexItems(new[]{ newXml.ConvertToValueSet("media") }); - - - //ensure it still exists in the index (raw examine search) - var criteria = searcher.CreateQuery(); - var filter = criteria.Id(3113); - var found = filter.Execute(); - Assert.IsNotNull(found); - Assert.AreEqual(1, found.TotalItemCount); - - //ensure it does not show up in the published media store - var recycledMedia = cache.GetById(3113); - Assert.IsNull(recycledMedia); - - } - - } - - [Test] - public void Children_With_Examine() - { - var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); - - using (var luceneDir = new RandomIdRamDirectory()) - using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, - validator: new ContentValueSetValidator(true))) - using (indexer.ProcessNonAsync()) - { - rebuilder.RegisterIndex(indexer.Name); - rebuilder.Populate(indexer); - - var searcher = indexer.GetSearcher(); - var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); - - //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace - var publishedMedia = cache.GetById(1111); - var rootChildren = publishedMedia.Children(); - Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { 2222, 1113, 1114, 1115, 1116 })); - - var publishedChild1 = cache.GetById(2222); - var subChildren = publishedChild1.Children(); - Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { 2112 })); - } - } - - [Test] - public void Descendants_With_Examine() - { - var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); - - using (var luceneDir = new RandomIdRamDirectory()) - using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, - validator: new ContentValueSetValidator(true))) - using (indexer.ProcessNonAsync()) - { - rebuilder.RegisterIndex(indexer.Name); - rebuilder.Populate(indexer); - - var searcher = indexer.GetSearcher(); - var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); - - //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace - var publishedMedia = cache.GetById(1111); - var rootDescendants = publishedMedia.Descendants(); - Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1113, 1114, 1115, 1116 })); - - var publishedChild1 = cache.GetById(2222); - var subDescendants = publishedChild1.Descendants(); - Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 3113 })); - } - } - - [Test] - public void DescendantsOrSelf_With_Examine() - { - var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); - - using (var luceneDir = new RandomIdRamDirectory()) - using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, - validator: new ContentValueSetValidator(true))) - using (indexer.ProcessNonAsync()) - { - rebuilder.RegisterIndex(indexer.Name); - rebuilder.Populate(indexer); - - var searcher = indexer.GetSearcher(); - var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); - - //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace - var publishedMedia = cache.GetById(1111); - var rootDescendants = publishedMedia.DescendantsOrSelf(); - Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 1111, 2112, 2222, 1113, 1114, 1115, 1116 })); - - var publishedChild1 = cache.GetById(2222); - var subDescendants = publishedChild1.DescendantsOrSelf(); - Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2222, 2112, 3113 })); - } - } - - [Test] - public void Ancestors_With_Examine() - { - var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); - - - using (var luceneDir = new RandomIdRamDirectory()) - using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, - validator: new ContentValueSetValidator(true))) - using (indexer.ProcessNonAsync()) - { - rebuilder.RegisterIndex(indexer.Name); - rebuilder.Populate(indexer); - - var ctx = GetUmbracoContext("/test"); - var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); - - //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace - var publishedMedia = cache.GetById(3113); - var ancestors = publishedMedia.Ancestors(); - Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1111 })); - } - - } - - [Test] - public void AncestorsOrSelf_With_Examine() - { - var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); - - using (var luceneDir = new RandomIdRamDirectory()) - using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, - validator: new ContentValueSetValidator(true))) - using (indexer.ProcessNonAsync()) - { - rebuilder.RegisterIndex(indexer.Name); - rebuilder.Populate(indexer); - - - var ctx = GetUmbracoContext("/test"); - var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); - - //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace - var publishedMedia = cache.GetById(3113); - var ancestors = publishedMedia.AncestorsOrSelf(); - Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 3113, 2112, 2222, 1111 })); - } - } - - [Test] - public void Children_Without_Examine() - { - var user = ServiceContext.UserService.GetUserById(0); - var mType = MakeNewMediaType(user, "TestMediaType"); - var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - - var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); - var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); - var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - - var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); - - var publishedMedia = GetNode(mRoot.Id); - var rootChildren = publishedMedia.Children(); - Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id })); - - var publishedChild1 = GetNode(mChild1.Id); - var subChildren = publishedChild1.Children(); - Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); - } - - [Test] - public void Descendants_Without_Examine() - { - var user = ServiceContext.UserService.GetUserById(0); - var mType = MakeNewMediaType(user, "TestMediaType"); - var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - - var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); - var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); - var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - - var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); - - var publishedMedia = GetNode(mRoot.Id); - var rootDescendants = publishedMedia.Descendants(); - Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); - - var publishedChild1 = GetNode(mChild1.Id); - var subDescendants = publishedChild1.Descendants(); - Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); - } - - [Test] - public void DescendantsOrSelf_Without_Examine() - { - var user = ServiceContext.UserService.GetUserById(0); - var mType = MakeNewMediaType(user, "TestMediaType"); - var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - - var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); - var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); - var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - - var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); - - var publishedMedia = GetNode(mRoot.Id); - var rootDescendantsOrSelf = publishedMedia.DescendantsOrSelf(); - Assert.IsTrue(rootDescendantsOrSelf.Select(x => x.Id).ContainsAll( - new[] { mRoot.Id, mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); - - var publishedChild1 = GetNode(mChild1.Id); - var subDescendantsOrSelf = publishedChild1.DescendantsOrSelf(); - Assert.IsTrue(subDescendantsOrSelf.Select(x => x.Id).ContainsAll( - new[] { mChild1.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); - } - - [Test] - public void Parent_Without_Examine() - { - var user = ServiceContext.UserService.GetUserById(0); - var mType = MakeNewMediaType(user, "TestMediaType"); - var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - - var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); - var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); - var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - - var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); - - var publishedRoot = GetNode(mRoot.Id); - Assert.AreEqual(null, publishedRoot.Parent); - - var publishedChild1 = GetNode(mChild1.Id); - Assert.AreEqual(mRoot.Id, publishedChild1.Parent.Id); - - var publishedSubChild1 = GetNode(mSubChild1.Id); - Assert.AreEqual(mChild1.Id, publishedSubChild1.Parent.Id); - } - - [Test] - public void Ancestors_Without_Examine() - { - var user = ServiceContext.UserService.GetUserById(0); - var mType = MakeNewMediaType(user, "TestMediaType"); - var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - - var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); - var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); - var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - - var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); - - var publishedSubChild1 = GetNode(mSubChild1.Id); - Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mRoot.Id })); - } - - [Test] - public void AncestorsOrSelf_Without_Examine() - { - var user = ServiceContext.UserService.GetUserById(0); - var mType = MakeNewMediaType(user, "TestMediaType"); - var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); - - var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); - var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); - var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); - - var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); - var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); - var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); - - var publishedSubChild1 = GetNode(mSubChild1.Id); - Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id).ContainsAll( - new[] { mSubChild1.Id, mChild1.Id, mRoot.Id })); - } - - [Test] - public void Convert_From_Standard_Xml() - { - var nodeId = 2112; - - var xml = XElement.Parse(@" - - 115 - 268 - 10726 - jpg - - - 115 - 268 - 10726 - jpg - - "); - var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); - - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); - - var nav = node.CreateNavigator(); - - var converted = publishedMedia.CreateFromCacheValues( - publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/Image"), nodeId)); - - Assert.AreEqual(nodeId, converted.Id); - Assert.AreEqual(3, converted.Level); - Assert.AreEqual(1, converted.SortOrder); - Assert.AreEqual("Sam's Umbraco Image", converted.Name); - Assert.AreEqual("-1,1111,2222,2112", converted.Path); - } - - [Test] - public void Detects_Error_In_Xml() - { - var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); - var nav = errorXml.CreateNavigator(); - - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); - var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); - - Assert.IsNull(converted); - } - } -} +//using System.Web; +//using System.Xml.Linq; +//using System.Xml.XPath; +//using NUnit.Framework; +//using Umbraco.Core; +//using Umbraco.Core.Models; +//using Umbraco.Tests.TestHelpers; +//using Umbraco.Tests.TestHelpers.Entities; +//using Umbraco.Tests.UmbracoExamine; +//using Umbraco.Web; +//using Umbraco.Web.PublishedCache.XmlPublishedCache; +//using System.Linq; +//using System.Threading; +//using System.Xml; +//using Examine; +//using Umbraco.Core.Cache; +//using Umbraco.Core.Models.PublishedContent; +//using Umbraco.Core.Strings; +//using Umbraco.Examine; +//using Current = Umbraco.Web.Composing.Current; +//using Umbraco.Tests.Testing; +//using Umbraco.Core.Composing; +//using Umbraco.Core.Models.Membership; +//using Umbraco.Core.PropertyEditors; +// +//namespace Umbraco.Tests.PublishedContent +//{ +// /// +// /// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore +// /// +// [TestFixture] +// [Apartment(ApartmentState.STA)] +// [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, WithApplication = true)] +// public class PublishedMediaTests : PublishedContentTestBase +// { +// /// +// /// sets up resolvers before resolution is frozen +// /// +// protected override void Compose() +// { +// base.Compose(); +// +// Composition.WithCollectionBuilder() +// .Clear() +// .Append(); +// } +// +// private IMediaType MakeNewMediaType(IUser user, string text, int parentId = -1) +// { +// var mt = new MediaType(parentId) { Name = text, Alias = text, Thumbnail = "icon-folder", Icon = "icon-folder" }; +// ServiceContext.MediaTypeService.Save(mt); +// return mt; +// } +// +// private IMedia MakeNewMedia(string name, IMediaType mediaType, IUser user, int parentId) +// { +// var m = ServiceContext.MediaService.CreateMediaWithIdentity(name, parentId, mediaType.Alias); +// return m; +// } +// +// /// +// /// Shared with PublishMediaStoreTests +// /// +// /// +// /// +// /// +// internal IPublishedContent GetNode(int id, UmbracoContext umbracoContext) +// { +// var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new StaticCacheProvider(), ContentTypesCache); +// var doc = cache.GetById(id); +// Assert.IsNotNull(doc); +// return doc; +// } +// +// private IPublishedContent GetNode(int id) +// { +// return GetNode(id, GetUmbracoContext("/test")); +// } +// +// [Test] +// public void Get_Property_Value_Uses_Converter() +// { +// var mType = MockedContentTypes.CreateImageMediaType("image2"); +// //lets add an RTE to this +// mType.PropertyGroups.First().PropertyTypes.Add( +// new PropertyType("test", ValueStorageType.Nvarchar, "content") +// { +// Name = "Rich Text", +// DataTypeId = -87 //tiny mce +// }); +// ServiceContext.MediaTypeService.Save(mType); +// var media = MockedMedia.CreateMediaImage(mType, -1); +// media.Properties["content"].SetValue("
This is some content
"); +// ServiceContext.MediaService.Save(media); +// +// var publishedMedia = GetNode(media.Id); +// +// var propVal = publishedMedia.Value("content"); +// Assert.IsInstanceOf(propVal); +// Assert.AreEqual("
This is some content
", propVal.ToString()); +// +// var propVal2 = publishedMedia.Value("content"); +// Assert.IsInstanceOf(propVal2); +// Assert.AreEqual("
This is some content
", propVal2.ToString()); +// +// var propVal3 = publishedMedia.Value("Content"); +// Assert.IsInstanceOf(propVal3); +// Assert.AreEqual("
This is some content
", propVal3.ToString()); +// } +// +// [Test] +// public void Ensure_Children_Sorted_With_Examine() +// { +// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); +// +// using (var luceneDir = new RandomIdRamDirectory()) +// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, +// validator: new ContentValueSetValidator(true))) +// using (indexer.ProcessNonAsync()) +// { +// rebuilder.RegisterIndex(indexer.Name); +// rebuilder.Populate(indexer); +// +// var searcher = indexer.GetSearcher(); +// var ctx = GetUmbracoContext("/test"); +// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); +// +// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace +// var publishedMedia = cache.GetById(1111); +// var rootChildren = publishedMedia.Children().ToArray(); +// var currSort = 0; +// for (var i = 0; i < rootChildren.Count(); i++) +// { +// Assert.GreaterOrEqual(rootChildren[i].SortOrder, currSort); +// currSort = rootChildren[i].SortOrder; +// } +// } +// } +// +// [Test] +// public void Do_Not_Find_In_Recycle_Bin() +// { +// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); +// +// using (var luceneDir = new RandomIdRamDirectory()) +// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, +// //include unpublished content since this uses the 'internal' indexer, it's up to the media cache to filter +// validator: new ContentValueSetValidator(false))) +// using (indexer.ProcessNonAsync()) +// { +// rebuilder.RegisterIndex(indexer.Name); +// rebuilder.Populate(indexer); +// +// var searcher = indexer.GetSearcher(); +// var ctx = GetUmbracoContext("/test"); +// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); +// +// //ensure it is found +// var publishedMedia = cache.GetById(3113); +// Assert.IsNotNull(publishedMedia); +// +// //move item to recycle bin +// var newXml = XElement.Parse(@" +// +// 115 +// 268 +// 10726 +// jpg +// "); +// indexer.IndexItems(new[]{ newXml.ConvertToValueSet("media") }); +// +// +// //ensure it still exists in the index (raw examine search) +// var criteria = searcher.CreateQuery(); +// var filter = criteria.Id(3113); +// var found = filter.Execute(); +// Assert.IsNotNull(found); +// Assert.AreEqual(1, found.TotalItemCount); +// +// //ensure it does not show up in the published media store +// var recycledMedia = cache.GetById(3113); +// Assert.IsNull(recycledMedia); +// +// } +// +// } +// +// [Test] +// public void Children_With_Examine() +// { +// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); +// +// using (var luceneDir = new RandomIdRamDirectory()) +// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, +// validator: new ContentValueSetValidator(true))) +// using (indexer.ProcessNonAsync()) +// { +// rebuilder.RegisterIndex(indexer.Name); +// rebuilder.Populate(indexer); +// +// var searcher = indexer.GetSearcher(); +// var ctx = GetUmbracoContext("/test"); +// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); +// +// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace +// var publishedMedia = cache.GetById(1111); +// var rootChildren = publishedMedia.Children(); +// Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { 2222, 1113, 1114, 1115, 1116 })); +// +// var publishedChild1 = cache.GetById(2222); +// var subChildren = publishedChild1.Children(); +// Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { 2112 })); +// } +// } +// +// [Test] +// public void Descendants_With_Examine() +// { +// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); +// +// using (var luceneDir = new RandomIdRamDirectory()) +// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, +// validator: new ContentValueSetValidator(true))) +// using (indexer.ProcessNonAsync()) +// { +// rebuilder.RegisterIndex(indexer.Name); +// rebuilder.Populate(indexer); +// +// var searcher = indexer.GetSearcher(); +// var ctx = GetUmbracoContext("/test"); +// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); +// +// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace +// var publishedMedia = cache.GetById(1111); +// var rootDescendants = publishedMedia.Descendants(); +// Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1113, 1114, 1115, 1116 })); +// +// var publishedChild1 = cache.GetById(2222); +// var subDescendants = publishedChild1.Descendants(); +// Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 3113 })); +// } +// } +// +// [Test] +// public void DescendantsOrSelf_With_Examine() +// { +// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); +// +// using (var luceneDir = new RandomIdRamDirectory()) +// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, +// validator: new ContentValueSetValidator(true))) +// using (indexer.ProcessNonAsync()) +// { +// rebuilder.RegisterIndex(indexer.Name); +// rebuilder.Populate(indexer); +// +// var searcher = indexer.GetSearcher(); +// var ctx = GetUmbracoContext("/test"); +// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); +// +// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace +// var publishedMedia = cache.GetById(1111); +// var rootDescendants = publishedMedia.DescendantsOrSelf(); +// Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 1111, 2112, 2222, 1113, 1114, 1115, 1116 })); +// +// var publishedChild1 = cache.GetById(2222); +// var subDescendants = publishedChild1.DescendantsOrSelf(); +// Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2222, 2112, 3113 })); +// } +// } +// +// [Test] +// public void Ancestors_With_Examine() +// { +// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); +// +// +// using (var luceneDir = new RandomIdRamDirectory()) +// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, +// validator: new ContentValueSetValidator(true))) +// using (indexer.ProcessNonAsync()) +// { +// rebuilder.RegisterIndex(indexer.Name); +// rebuilder.Populate(indexer); +// +// var ctx = GetUmbracoContext("/test"); +// var searcher = indexer.GetSearcher(); +// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); +// +// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace +// var publishedMedia = cache.GetById(3113); +// var ancestors = publishedMedia.Ancestors(); +// Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1111 })); +// } +// +// } +// +// [Test] +// public void AncestorsOrSelf_With_Examine() +// { +// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); +// +// using (var luceneDir = new RandomIdRamDirectory()) +// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, +// validator: new ContentValueSetValidator(true))) +// using (indexer.ProcessNonAsync()) +// { +// rebuilder.RegisterIndex(indexer.Name); +// rebuilder.Populate(indexer); +// +// +// var ctx = GetUmbracoContext("/test"); +// var searcher = indexer.GetSearcher(); +// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); +// +// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace +// var publishedMedia = cache.GetById(3113); +// var ancestors = publishedMedia.AncestorsOrSelf(); +// Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 3113, 2112, 2222, 1111 })); +// } +// } +// +// [Test] +// public void Children_Without_Examine() +// { +// var user = ServiceContext.UserService.GetUserById(0); +// var mType = MakeNewMediaType(user, "TestMediaType"); +// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); +// +// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); +// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); +// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); +// +// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); +// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); +// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); +// +// var publishedMedia = GetNode(mRoot.Id); +// var rootChildren = publishedMedia.Children(); +// Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id })); +// +// var publishedChild1 = GetNode(mChild1.Id); +// var subChildren = publishedChild1.Children(); +// Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); +// } +// +// [Test] +// public void Descendants_Without_Examine() +// { +// var user = ServiceContext.UserService.GetUserById(0); +// var mType = MakeNewMediaType(user, "TestMediaType"); +// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); +// +// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); +// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); +// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); +// +// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); +// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); +// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); +// +// var publishedMedia = GetNode(mRoot.Id); +// var rootDescendants = publishedMedia.Descendants(); +// Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); +// +// var publishedChild1 = GetNode(mChild1.Id); +// var subDescendants = publishedChild1.Descendants(); +// Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); +// } +// +// [Test] +// public void DescendantsOrSelf_Without_Examine() +// { +// var user = ServiceContext.UserService.GetUserById(0); +// var mType = MakeNewMediaType(user, "TestMediaType"); +// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); +// +// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); +// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); +// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); +// +// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); +// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); +// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); +// +// var publishedMedia = GetNode(mRoot.Id); +// var rootDescendantsOrSelf = publishedMedia.DescendantsOrSelf(); +// Assert.IsTrue(rootDescendantsOrSelf.Select(x => x.Id).ContainsAll( +// new[] { mRoot.Id, mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); +// +// var publishedChild1 = GetNode(mChild1.Id); +// var subDescendantsOrSelf = publishedChild1.DescendantsOrSelf(); +// Assert.IsTrue(subDescendantsOrSelf.Select(x => x.Id).ContainsAll( +// new[] { mChild1.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); +// } +// +// [Test] +// public void Parent_Without_Examine() +// { +// var user = ServiceContext.UserService.GetUserById(0); +// var mType = MakeNewMediaType(user, "TestMediaType"); +// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); +// +// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); +// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); +// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); +// +// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); +// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); +// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); +// +// var publishedRoot = GetNode(mRoot.Id); +// Assert.AreEqual(null, publishedRoot.Parent); +// +// var publishedChild1 = GetNode(mChild1.Id); +// Assert.AreEqual(mRoot.Id, publishedChild1.Parent.Id); +// +// var publishedSubChild1 = GetNode(mSubChild1.Id); +// Assert.AreEqual(mChild1.Id, publishedSubChild1.Parent.Id); +// } +// +// [Test] +// public void Ancestors_Without_Examine() +// { +// var user = ServiceContext.UserService.GetUserById(0); +// var mType = MakeNewMediaType(user, "TestMediaType"); +// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); +// +// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); +// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); +// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); +// +// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); +// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); +// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); +// +// var publishedSubChild1 = GetNode(mSubChild1.Id); +// Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mRoot.Id })); +// } +// +// [Test] +// public void AncestorsOrSelf_Without_Examine() +// { +// var user = ServiceContext.UserService.GetUserById(0); +// var mType = MakeNewMediaType(user, "TestMediaType"); +// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); +// +// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); +// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); +// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); +// +// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); +// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); +// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); +// +// var publishedSubChild1 = GetNode(mSubChild1.Id); +// Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id).ContainsAll( +// new[] { mSubChild1.Id, mChild1.Id, mRoot.Id })); +// } +// +// [Test] +// public void Convert_From_Standard_Xml() +// { +// var nodeId = 2112; +// +// var xml = XElement.Parse(@" +// +// 115 +// 268 +// 10726 +// jpg +// +// +// 115 +// 268 +// 10726 +// jpg +// +// "); +// var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); +// +// var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); +// +// var nav = node.CreateNavigator(); +// +// var converted = publishedMedia.CreateFromCacheValues( +// publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/Image"), nodeId)); +// +// Assert.AreEqual(nodeId, converted.Id); +// Assert.AreEqual(3, converted.Level); +// Assert.AreEqual(1, converted.SortOrder); +// Assert.AreEqual("Sam's Umbraco Image", converted.Name); +// Assert.AreEqual("-1,1111,2222,2112", converted.Path); +// } +// +// [Test] +// public void Detects_Error_In_Xml() +// { +// var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); +// var nav = errorXml.CreateNavigator(); +// +// var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); +// var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); +// +// Assert.IsNull(converted); +// } +// } +//} diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index d4494c5f91..21353049d8 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -864,79 +864,79 @@ namespace Umbraco.Web return content.DescendantsOrSelf(level).OfType(); } - public static IPublishedContent Descendant(this IPublishedContent content) + public static IPublishedContent Descendant(this IPublishedContent content, string culture = null) { - return content.Children.FirstOrDefault(); + return content.Children(culture).FirstOrDefault(); } - public static IPublishedContent Descendant(this IPublishedContent content, int level) + public static IPublishedContent Descendant(this IPublishedContent content, int level, string culture = null) { - return content.EnumerateDescendants(false).FirstOrDefault(x => x.Level == level); + return content.EnumerateDescendants(false, culture).FirstOrDefault(x => x.Level == level); } - public static IPublishedContent Descendant(this IPublishedContent content, string contentTypeAlias) + public static IPublishedContent Descendant(this IPublishedContent content, string contentTypeAlias, string culture = null) { - return content.EnumerateDescendants(false).FirstOrDefault(x => x.ContentType.Alias == contentTypeAlias); + return content.EnumerateDescendants(false, culture).FirstOrDefault(x => x.ContentType.Alias == contentTypeAlias); } - public static T Descendant(this IPublishedContent content) + public static T Descendant(this IPublishedContent content, string culture = null) where T : class, IPublishedContent { - return content.EnumerateDescendants(false).FirstOrDefault(x => x is T) as T; + return content.EnumerateDescendants(false, culture).FirstOrDefault(x => x is T) as T; } - public static T Descendant(this IPublishedContent content, int level) + public static T Descendant(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent { - return content.Descendant(level) as T; + return content.Descendant(level, culture) as T; } - public static IPublishedContent DescendantOrSelf(this IPublishedContent content) + public static IPublishedContent DescendantOrSelf(this IPublishedContent content, string culture = null) { return content; } - public static IPublishedContent DescendantOrSelf(this IPublishedContent content, int level) + public static IPublishedContent DescendantOrSelf(this IPublishedContent content, int level, string culture = null) { - return content.EnumerateDescendants(true).FirstOrDefault(x => x.Level == level); + return content.EnumerateDescendants(true, culture).FirstOrDefault(x => x.Level == level); } - public static IPublishedContent DescendantOrSelf(this IPublishedContent content, string contentTypeAlias) + public static IPublishedContent DescendantOrSelf(this IPublishedContent content, string contentTypeAlias, string culture = null) { - return content.EnumerateDescendants(true).FirstOrDefault(x => x.ContentType.Alias == contentTypeAlias); + return content.EnumerateDescendants(true, culture).FirstOrDefault(x => x.ContentType.Alias == contentTypeAlias); } - public static T DescendantOrSelf(this IPublishedContent content) + public static T DescendantOrSelf(this IPublishedContent content, string culture = null) where T : class, IPublishedContent { - return content.EnumerateDescendants(true).FirstOrDefault(x => x is T) as T; + return content.EnumerateDescendants(true, culture).FirstOrDefault(x => x is T) as T; } - public static T DescendantOrSelf(this IPublishedContent content, int level) + public static T DescendantOrSelf(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent { - return content.DescendantOrSelf(level) as T; + return content.DescendantOrSelf(level, culture) as T; } - internal static IEnumerable DescendantsOrSelf(this IPublishedContent content, bool orSelf, Func func) + internal static IEnumerable DescendantsOrSelf(this IPublishedContent content, bool orSelf, Func func, string culture = null) { - return content.EnumerateDescendants(orSelf).Where(x => func == null || func(x)); + return content.EnumerateDescendants(orSelf, culture).Where(x => func == null || func(x)); } - internal static IEnumerable EnumerateDescendants(this IPublishedContent content, bool orSelf) + internal static IEnumerable EnumerateDescendants(this IPublishedContent content, bool orSelf, string culture = null) { if (content == null) throw new ArgumentNullException(nameof(content)); if (orSelf) yield return content; - foreach (var desc in content.Children.SelectMany(x => x.EnumerateDescendants())) + foreach (var desc in content.Children(culture).SelectMany(x => x.EnumerateDescendants())) yield return desc; } - internal static IEnumerable EnumerateDescendants(this IPublishedContent content) + internal static IEnumerable EnumerateDescendants(this IPublishedContent content, string culture = null) { yield return content; - foreach (var desc in content.Children.SelectMany(x => x.EnumerateDescendants())) + foreach (var desc in content.Children(culture).SelectMany(x => x.EnumerateDescendants())) yield return desc; } @@ -1022,6 +1022,23 @@ namespace Umbraco.Web #region Axes: children + + private static IEnumerable WhereHasCulture(this IEnumerable contents, string culture = null) + { + if (contents == null) throw new ArgumentNullException(nameof(contents)); + + var actualCulture = culture ?? GetCurrentCulture(); + + return contents.Where(x=>x.HasCulture(actualCulture) ||x.HasCulture(null)); + } + + private static string GetCurrentCulture() + { + + //Review: is this the correct way to get the current culture? + return System.Threading.Thread.CurrentThread.CurrentUICulture.Name; + } + /// /// Gets the children of the content. /// @@ -1031,10 +1048,10 @@ namespace Umbraco.Web /// Children are sorted by their sortOrder. /// This method exists for consistency, it is the same as calling content.Children as a property. /// - public static IEnumerable Children(this IPublishedContent content) + public static IEnumerable Children(this IPublishedContent content, string culture = null) { if (content == null) throw new ArgumentNullException(nameof(content)); - return content.Children; + return content.Children.WhereHasCulture(culture); } /// @@ -1046,9 +1063,9 @@ namespace Umbraco.Web /// /// Children are sorted by their sortOrder. /// - public static IEnumerable Children(this IPublishedContent content, Func predicate) + public static IEnumerable Children(this IPublishedContent content, Func predicate, string culture = null) { - return content.Children().Where(predicate); + return content.Children(culture).Where(predicate); } /// @@ -1057,9 +1074,9 @@ namespace Umbraco.Web /// The content. /// One or more content type alias. /// The children of the content, of any of the specified types. - public static IEnumerable Children(this IPublishedContent content, params string[] alias) + public static IEnumerable Children(this IPublishedContent content, string culture = null, params string[] alias) { - return content.Children(x => alias.InvariantContains(x.ContentType.Alias)); + return content.Children(x => alias.InvariantContains(x.ContentType.Alias), culture); } /// @@ -1071,15 +1088,15 @@ namespace Umbraco.Web /// /// Children are sorted by their sortOrder. /// - public static IEnumerable Children(this IPublishedContent content) + public static IEnumerable Children(this IPublishedContent content, string culture = null) where T : class, IPublishedContent { - return content.Children().OfType(); + return content.Children(culture).OfType(); } - public static IPublishedContent FirstChild(this IPublishedContent content) + public static IPublishedContent FirstChild(this IPublishedContent content, string culture = null) { - return content.Children().FirstOrDefault(); + return content.Children(culture).FirstOrDefault(); } /// @@ -1088,26 +1105,26 @@ namespace Umbraco.Web /// The content. /// The content type alias. /// The first child of content, of the given content type. - public static IPublishedContent FirstChild(this IPublishedContent content, string alias) + public static IPublishedContent FirstChild(this IPublishedContent content, string alias, string culture = null) { - return content.Children(alias).FirstOrDefault(); + return content.Children(culture,alias).FirstOrDefault(); } - public static IPublishedContent FirstChild(this IPublishedContent content, Func predicate) + public static IPublishedContent FirstChild(this IPublishedContent content, Func predicate, string culture = null) { - return content.Children(predicate).FirstOrDefault(); + return content.Children(predicate, culture).FirstOrDefault(); } - public static T FirstChild(this IPublishedContent content) + public static T FirstChild(this IPublishedContent content, string culture = null) where T : class, IPublishedContent { - return content.Children().FirstOrDefault(); + return content.Children(culture).FirstOrDefault(); } - public static T FirstChild(this IPublishedContent content, Func predicate) + public static T FirstChild(this IPublishedContent content, Func predicate, string culture = null) where T : class, IPublishedContent { - return content.Children().FirstOrDefault(predicate); + return content.Children(culture).FirstOrDefault(predicate); } /// @@ -1117,9 +1134,9 @@ namespace Umbraco.Web /// A service context. /// An optional content type alias. /// The children of the content. - public static DataTable ChildrenAsTable(this IPublishedContent content, ServiceContext services, string contentTypeAliasFilter = "") + public static DataTable ChildrenAsTable(this IPublishedContent content, ServiceContext services, string contentTypeAliasFilter = "", string culture = null) { - return GenerateDataTable(content, services, contentTypeAliasFilter); + return GenerateDataTable(content, services, contentTypeAliasFilter, culture); } /// @@ -1129,13 +1146,13 @@ namespace Umbraco.Web /// A service context. /// An optional content type alias. /// The children of the content. - private static DataTable GenerateDataTable(IPublishedContent content, ServiceContext services, string contentTypeAliasFilter = "") + private static DataTable GenerateDataTable(IPublishedContent content, ServiceContext services, string contentTypeAliasFilter = "", string culture = null) { var firstNode = contentTypeAliasFilter.IsNullOrWhiteSpace() - ? content.Children.Any() - ? content.Children.ElementAt(0) + ? content.Children(culture).Any() + ? content.Children(culture).ElementAt(0) : null - : content.Children.FirstOrDefault(x => x.ContentType.Alias == contentTypeAliasFilter); + : content.Children(culture).FirstOrDefault(x => x.ContentType.Alias == contentTypeAliasFilter); if (firstNode == null) return new DataTable(); //no children found From a27577c17dd9d83c6055be07aafa154ac82b5f48 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 16 Jan 2019 07:46:10 +0100 Subject: [PATCH 09/41] #3305 - Handle invariants --- .../PublishedContent/PublishedContentTests.cs | 1754 ++++++++--------- src/Umbraco.Web/PublishedContentExtensions.cs | 14 +- 2 files changed, 881 insertions(+), 887 deletions(-) diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index ab65ac82b1..26e0196478 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -1,877 +1,877 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.PropertyEditors; -using Umbraco.Web; -using Umbraco.Web.PublishedCache; -using Umbraco.Core.Composing; -using Moq; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; -using Umbraco.Web.Models.PublishedContent; -using Umbraco.Web.PropertyEditors; - -namespace Umbraco.Tests.PublishedContent -{ - /// - /// Tests the methods on IPublishedContent using the DefaultPublishedContentStore - /// - [TestFixture] - [UmbracoTest(TypeLoader = UmbracoTestOptions.TypeLoader.PerFixture)] - public class PublishedContentTests : PublishedContentTestBase - { - protected override void Compose() - { - base.Compose(); - - Composition.RegisterUnique(f => new PublishedModelFactory(f.GetInstance().GetTypes())); - Composition.RegisterUnique(); - Composition.RegisterUnique(); - - var logger = Mock.Of(); - var dataTypeService = new TestObjects.TestDataTypeService( - new DataType(new VoidEditor(logger)) { Id = 1 }, - new DataType(new TrueFalsePropertyEditor(logger)) { Id = 1001 }, - new DataType(new RichTextPropertyEditor(logger)) { Id = 1002 }, - new DataType(new IntegerPropertyEditor(logger)) { Id = 1003 }, - new DataType(new TextboxPropertyEditor(logger)) { Id = 1004 }, - new DataType(new MediaPickerPropertyEditor(logger)) { Id = 1005 }); - Composition.RegisterUnique(f => dataTypeService); - } - - protected override void Initialize() - { - base.Initialize(); - - var factory = Factory.GetInstance() as PublishedContentTypeFactory; - - // need to specify a custom callback for unit tests - // AutoPublishedContentTypes generates properties automatically - // when they are requested, but we must declare those that we - // explicitely want to be here... - - var propertyTypes = new[] - { - // AutoPublishedContentType will auto-generate other properties - factory.CreatePropertyType("umbracoNaviHide", 1001), - factory.CreatePropertyType("selectedNodes", 1), - factory.CreatePropertyType("umbracoUrlAlias", 1), - factory.CreatePropertyType("content", 1002), - factory.CreatePropertyType("testRecursive", 1), - }; - var compositionAliases = new[] { "MyCompositionAlias" }; - var type = new AutoPublishedContentType(0, "anything", compositionAliases, propertyTypes); - ContentTypesCache.GetPublishedContentTypeByAlias = alias => type; - } - - protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) - { - var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); - - // this is so the model factory looks into the test assembly - pluginManager.AssembliesToScan = pluginManager.AssembliesToScan - .Union(new[] { typeof(PublishedContentTests).Assembly }) - .ToList(); - - return pluginManager; - } - - private readonly Guid _node1173Guid = Guid.NewGuid(); - - protected override string GetXmlContent(int templateId) - { - return @" - - - - -]> - - - - - 1 - - - This is some content]]> - - - - - - - - - - - - - - - - 1 - - - - - - - - - -"; - } - - internal IPublishedContent GetNode(int id) - { - var ctx = GetUmbracoContext("/test"); - var doc = ctx.ContentCache.GetById(id); - Assert.IsNotNull(doc); - return doc; - } - - [Test] - public void GetNodeByIds() - { - var ctx = GetUmbracoContext("/test"); - var contentById = ctx.ContentCache.GetById(1173); - Assert.IsNotNull(contentById); - var contentByGuid = ctx.ContentCache.GetById(_node1173Guid); - Assert.IsNotNull(contentByGuid); - Assert.AreEqual(contentById.Id, contentByGuid.Id); - Assert.AreEqual(contentById.Key, contentByGuid.Key); - - contentById = ctx.ContentCache.GetById(666); - Assert.IsNull(contentById); - contentByGuid = ctx.ContentCache.GetById(Guid.NewGuid()); - Assert.IsNull(contentByGuid); - } - - [Test] - public void Is_Last_From_Where_Filter_Dynamic_Linq() - { - var doc = GetNode(1173); - - var items = doc.Children.Where(x => x.IsVisible()).ToIndexedArray(); - - foreach (var item in items) - { - if (item.Content.Id != 1178) - { - Assert.IsFalse(item.IsLast()); - } - else - { - Assert.IsTrue(item.IsLast()); - } - } - } - - [Test] - public void Is_Last_From_Where_Filter() - { - var doc = GetNode(1173); - - var items = doc - .Children - .Where(x => x.IsVisible()) - .ToIndexedArray(); - - Assert.AreEqual(4, items.Length); - - foreach (var d in items) - { - switch (d.Content.Id) - { - case 1174: - Assert.IsTrue(d.IsFirst()); - Assert.IsFalse(d.IsLast()); - break; - case 117: - Assert.IsFalse(d.IsFirst()); - Assert.IsFalse(d.IsLast()); - break; - case 1177: - Assert.IsFalse(d.IsFirst()); - Assert.IsFalse(d.IsLast()); - break; - case 1178: - Assert.IsFalse(d.IsFirst()); - Assert.IsTrue(d.IsLast()); - break; - default: - Assert.Fail("Invalid id."); - break; - } - } - } - - [PublishedModel("Home")] - internal class Home : PublishedContentModel - { - public Home(IPublishedContent content) - : base(content) - {} - } - - [PublishedModel("anything")] - internal class Anything : PublishedContentModel - { - public Anything(IPublishedContent content) - : base(content) - { } - } - - [Test] - public void Is_Last_From_Where_Filter2() - { - var doc = GetNode(1173); - - var items = doc.Children - .Select(x => x.CreateModel()) // linq, returns IEnumerable - - // only way around this is to make sure every IEnumerable extension - // explicitely returns a PublishedContentSet, not an IEnumerable - - .OfType() // ours, return IEnumerable (actually a PublishedContentSet) - .Where(x => x.IsVisible()) // so, here it's linq again :-( - .ToIndexedArray(); // so, we need that one for the test to pass - - Assert.AreEqual(1, items.Length); - - foreach (var d in items) - { - switch (d.Content.Id) - { - case 1174: - Assert.IsTrue(d.IsFirst()); - Assert.IsTrue(d.IsLast()); - break; - default: - Assert.Fail("Invalid id."); - break; - } - } - } - - [Test] - public void Is_Last_From_Take() - { - var doc = GetNode(1173); - - var items = doc.Children.Take(4).ToIndexedArray(); - - foreach (var item in items) - { - if (item.Content.Id != 1178) - { - Assert.IsFalse(item.IsLast()); - } - else - { - Assert.IsTrue(item.IsLast()); - } - } - } - - [Test] - public void Is_Last_From_Skip() - { - var doc = GetNode(1173); - - foreach (var d in doc.Children.Skip(1).ToIndexedArray()) - { - if (d.Content.Id != 1176) - { - Assert.IsFalse(d.IsLast()); - } - else - { - Assert.IsTrue(d.IsLast()); - } - } - } - - [Test] - public void Is_Last_From_Concat() - { - var doc = GetNode(1173); - - var items = doc.Children - .Concat(new[] { GetNode(1175), GetNode(4444) }) - .ToIndexedArray(); - - foreach (var item in items) - { - if (item.Content.Id != 4444) - { - Assert.IsFalse(item.IsLast()); - } - else - { - Assert.IsTrue(item.IsLast()); - } - } - } - - [Test] - public void Descendants_Ordered_Properly() - { - var doc = GetNode(1046); - - var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; - var exindex = 0; - - // must respect the XPath descendants-or-self axis! - foreach (var d in doc.DescendantsOrSelf()) - Assert.AreEqual(expected[exindex++], d.Id); - } - - [Test] - public void Get_Property_Value_Recursive() - { - var doc = GetNode(1174); - var rVal = doc.Value("testRecursive", fallback: Fallback.ToAncestors); - var nullVal = doc.Value("DoNotFindThis", fallback: Fallback.ToAncestors); - Assert.AreEqual("This is the recursive val", rVal); - Assert.AreEqual(null, nullVal); - } - - [Test] - public void Get_Property_Value_Uses_Converter() - { - var doc = GetNode(1173); - - var propVal = doc.Value("content"); - Assert.IsInstanceOf(typeof(IHtmlString), propVal); - Assert.AreEqual("
This is some content
", propVal.ToString()); - - var propVal2 = doc.Value("content"); - Assert.IsInstanceOf(typeof(IHtmlString), propVal2); - Assert.AreEqual("
This is some content
", propVal2.ToString()); - - var propVal3 = doc.Value("Content"); - Assert.IsInstanceOf(typeof(IHtmlString), propVal3); - Assert.AreEqual("
This is some content
", propVal3.ToString()); - } - - [Test] - public void Complex_Linq() - { - var doc = GetNode(1173); - - var result = doc.Ancestors().OrderBy(x => x.Level) - .Single() - .Descendants() - .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); - - Assert.IsNotNull(result); - } - - [Test] - public void Children_GroupBy_DocumentTypeAlias() - { - var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); - var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); - var contentTypes = new Dictionary - { - { home.Alias, home }, - { custom.Alias, custom } - }; - ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; - - var doc = GetNode(1046); - - var found1 = doc.Children.GroupBy(x => x.ContentType.Alias).ToArray(); - - Assert.AreEqual(2, found1.Length); - Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count()); - Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count()); - } - - [Test] - public void Children_Where_DocumentTypeAlias() - { - var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); - var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); - var contentTypes = new Dictionary - { - { home.Alias, home }, - { custom.Alias, custom } - }; - ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; - - var doc = GetNode(1046); - - var found1 = doc.Children.Where(x => x.ContentType.Alias == "CustomDocument"); - var found2 = doc.Children.Where(x => x.ContentType.Alias == "Home"); - - Assert.AreEqual(1, found1.Count()); - Assert.AreEqual(2, found2.Count()); - } - - [Test] - public void Children_Order_By_Update_Date() - { - var doc = GetNode(1173); - - var ordered = doc.Children.OrderBy(x => x.UpdateDate); - - var correctOrder = new[] { 1178, 1177, 1174, 1176 }; - for (var i = 0; i < correctOrder.Length; i++) - { - Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id); - } - - } - - [Test] - public void FirstChild() - { - var doc = GetNode(1173); // has child nodes - Assert.IsNotNull(doc.FirstChild()); - Assert.IsNotNull(doc.FirstChild(x => true)); - Assert.IsNotNull(doc.FirstChild()); - - doc = GetNode(1175); // does not have child nodes - Assert.IsNull(doc.FirstChild()); - Assert.IsNull(doc.FirstChild(x => true)); - Assert.IsNull(doc.FirstChild()); - } - - [Test] - public void FirstChildAsT() - { - var doc = GetNode(1046); // has child nodes - - var model = doc.FirstChild(x => true); // predicate - - Assert.IsNotNull(model); - Assert.IsTrue(model.Id == 1173); - Assert.IsInstanceOf(model); - Assert.IsInstanceOf(model); - - doc = GetNode(1175); // does not have child nodes - Assert.IsNull(doc.FirstChild()); - Assert.IsNull(doc.FirstChild(x => true)); - } - - [Test] - public void IsComposedOf() - { - var doc = GetNode(1173); - - var isComposedOf = doc.IsComposedOf("MyCompositionAlias"); - - Assert.IsTrue(isComposedOf); - } - - [Test] - public void HasProperty() - { - var doc = GetNode(1173); - - var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias); - - Assert.IsTrue(hasProp); - } - - [Test] - public void HasValue() - { - var doc = GetNode(1173); - - var hasValue = doc.HasValue(Constants.Conventions.Content.UrlAlias); - var noValue = doc.HasValue("blahblahblah"); - - Assert.IsTrue(hasValue); - Assert.IsFalse(noValue); - } - - [Test] - public void Ancestors_Where_Visible() - { - var doc = GetNode(1174); - - var whereVisible = doc.Ancestors().Where(x => x.IsVisible()); - Assert.AreEqual(1, whereVisible.Count()); - - } - - [Test] - public void Visible() - { - var hidden = GetNode(1046); - var visible = GetNode(1173); - - Assert.IsFalse(hidden.IsVisible()); - Assert.IsTrue(visible.IsVisible()); - } - - [Test] - public void Ancestor_Or_Self() - { - var doc = GetNode(1173); - - var result = doc.AncestorOrSelf(); - - Assert.IsNotNull(result); - - // ancestor-or-self has to be self! - Assert.AreEqual(1173, result.Id); - } - - [Test] - public void U4_4559() - { - var doc = GetNode(1174); - var result = doc.AncestorOrSelf(1); - Assert.IsNotNull(result); - Assert.AreEqual(1046, result.Id); - } - - [Test] - public void Ancestors_Or_Self() - { - var doc = GetNode(1174); - - var result = doc.AncestorsOrSelf().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(3, result.Length); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 })); - } - - [Test] - public void Ancestors() - { - var doc = GetNode(1174); - - var result = doc.Ancestors().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(2, result.Length); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 })); - } - - [Test] - public void IsAncestor() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsTrue(root.IsAncestor(customDoc4)); - Assert.IsFalse(root.IsAncestor(customDoc3)); - Assert.IsTrue(root.IsAncestor(customDoc2)); - Assert.IsTrue(root.IsAncestor(customDoc)); - Assert.IsTrue(root.IsAncestor(home)); - Assert.IsFalse(root.IsAncestor(root)); - - Assert.IsTrue(home.IsAncestor(customDoc4)); - Assert.IsFalse(home.IsAncestor(customDoc3)); - Assert.IsTrue(home.IsAncestor(customDoc2)); - Assert.IsTrue(home.IsAncestor(customDoc)); - Assert.IsFalse(home.IsAncestor(home)); - Assert.IsFalse(home.IsAncestor(root)); - - Assert.IsFalse(customDoc.IsAncestor(customDoc4)); - Assert.IsFalse(customDoc.IsAncestor(customDoc3)); - Assert.IsTrue(customDoc.IsAncestor(customDoc2)); - Assert.IsFalse(customDoc.IsAncestor(customDoc)); - Assert.IsFalse(customDoc.IsAncestor(home)); - Assert.IsFalse(customDoc.IsAncestor(root)); - - Assert.IsFalse(customDoc2.IsAncestor(customDoc4)); - Assert.IsFalse(customDoc2.IsAncestor(customDoc3)); - Assert.IsFalse(customDoc2.IsAncestor(customDoc2)); - Assert.IsFalse(customDoc2.IsAncestor(customDoc)); - Assert.IsFalse(customDoc2.IsAncestor(home)); - Assert.IsFalse(customDoc2.IsAncestor(root)); - - Assert.IsFalse(customDoc3.IsAncestor(customDoc3)); - } - - [Test] - public void IsAncestorOrSelf() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsTrue(root.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(root.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(root.IsAncestorOrSelf(customDoc2)); - Assert.IsTrue(root.IsAncestorOrSelf(customDoc)); - Assert.IsTrue(root.IsAncestorOrSelf(home)); - Assert.IsTrue(root.IsAncestorOrSelf(root)); - - Assert.IsTrue(home.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(home.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(home.IsAncestorOrSelf(customDoc2)); - Assert.IsTrue(home.IsAncestorOrSelf(customDoc)); - Assert.IsTrue(home.IsAncestorOrSelf(home)); - Assert.IsFalse(home.IsAncestorOrSelf(root)); - - Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc2)); - Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc)); - Assert.IsFalse(customDoc.IsAncestorOrSelf(home)); - Assert.IsFalse(customDoc.IsAncestorOrSelf(root)); - - Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc4)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc3)); - Assert.IsTrue(customDoc2.IsAncestorOrSelf(customDoc2)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(home)); - Assert.IsFalse(customDoc2.IsAncestorOrSelf(root)); - - Assert.IsTrue(customDoc4.IsAncestorOrSelf(customDoc4)); - Assert.IsTrue(customDoc3.IsAncestorOrSelf(customDoc3)); - } - - - [Test] - public void Descendants_Or_Self() - { - var doc = GetNode(1046); - - var result = doc.DescendantsOrSelf().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(10, result.Count()); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); - } - - [Test] - public void Descendants() - { - var doc = GetNode(1046); - - var result = doc.Descendants().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(9, result.Count()); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); - } - - [Test] - public void IsDescendant() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsFalse(root.IsDescendant(root)); - Assert.IsFalse(root.IsDescendant(home)); - Assert.IsFalse(root.IsDescendant(customDoc)); - Assert.IsFalse(root.IsDescendant(customDoc2)); - Assert.IsFalse(root.IsDescendant(customDoc3)); - Assert.IsFalse(root.IsDescendant(customDoc4)); - - Assert.IsTrue(home.IsDescendant(root)); - Assert.IsFalse(home.IsDescendant(home)); - Assert.IsFalse(home.IsDescendant(customDoc)); - Assert.IsFalse(home.IsDescendant(customDoc2)); - Assert.IsFalse(home.IsDescendant(customDoc3)); - Assert.IsFalse(home.IsDescendant(customDoc4)); - - Assert.IsTrue(customDoc.IsDescendant(root)); - Assert.IsTrue(customDoc.IsDescendant(home)); - Assert.IsFalse(customDoc.IsDescendant(customDoc)); - Assert.IsFalse(customDoc.IsDescendant(customDoc2)); - Assert.IsFalse(customDoc.IsDescendant(customDoc3)); - Assert.IsFalse(customDoc.IsDescendant(customDoc4)); - - Assert.IsTrue(customDoc2.IsDescendant(root)); - Assert.IsTrue(customDoc2.IsDescendant(home)); - Assert.IsTrue(customDoc2.IsDescendant(customDoc)); - Assert.IsFalse(customDoc2.IsDescendant(customDoc2)); - Assert.IsFalse(customDoc2.IsDescendant(customDoc3)); - Assert.IsFalse(customDoc2.IsDescendant(customDoc4)); - - Assert.IsFalse(customDoc3.IsDescendant(customDoc3)); - } - - [Test] - public void IsDescendantOrSelf() - { - // Structure: - // - Root : 1046 (no parent) - // -- Home: 1173 (parent 1046) - // -- Custom Doc: 1178 (parent 1173) - // --- Custom Doc2: 1179 (parent: 1178) - // -- Custom Doc4: 117 (parent 1173) - // - Custom Doc3: 1172 (no parent) - - var home = GetNode(1173); - var root = GetNode(1046); - var customDoc = GetNode(1178); - var customDoc2 = GetNode(1179); - var customDoc3 = GetNode(1172); - var customDoc4 = GetNode(117); - - Assert.IsTrue(root.IsDescendantOrSelf(root)); - Assert.IsFalse(root.IsDescendantOrSelf(home)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(root.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(home.IsDescendantOrSelf(root)); - Assert.IsTrue(home.IsDescendantOrSelf(home)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(home.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(customDoc.IsDescendantOrSelf(root)); - Assert.IsTrue(customDoc.IsDescendantOrSelf(home)); - Assert.IsTrue(customDoc.IsDescendantOrSelf(customDoc)); - Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(customDoc2.IsDescendantOrSelf(root)); - Assert.IsTrue(customDoc2.IsDescendantOrSelf(home)); - Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc)); - Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc2)); - Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc3)); - Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc4)); - - Assert.IsTrue(customDoc3.IsDescendantOrSelf(customDoc3)); - } - - [Test] - public void Up() - { - var doc = GetNode(1173); - - var result = doc.Up(); - - Assert.IsNotNull(result); - - Assert.AreEqual(1046, result.Id); - } - - [Test] - public void Down() - { - var doc = GetNode(1173); - - var result = doc.Down(); - - Assert.IsNotNull(result); - - Assert.AreEqual(1174, result.Id); - } - - [Test] - public void FragmentProperty() - { - var factory = Factory.GetInstance() as PublishedContentTypeFactory; - - var pt = factory.CreatePropertyType("detached", 1003); - var ct = factory.CreateContentType(0, "alias", new[] { pt }); - var prop = new PublishedElementPropertyBase(pt, null, false, PropertyCacheLevel.None, 5548); - Assert.IsInstanceOf(prop.GetValue()); - Assert.AreEqual(5548, prop.GetValue()); - } - - public void Fragment1() - { - var type = ContentTypesCache.Get(PublishedItemType.Content, "detachedSomething"); - var values = new Dictionary(); - var f = new PublishedElement(type, Guid.NewGuid(), values, false); - } - - [Test] - public void Fragment2() - { - var factory = Factory.GetInstance() as PublishedContentTypeFactory; - - var pt1 = factory.CreatePropertyType("legend", 1004); - var pt2 = factory.CreatePropertyType("image", 1005); - var pt3 = factory.CreatePropertyType("size", 1003); - const string val1 = "boom bam"; - const int val2 = 0; - const int val3 = 666; - - var guid = Guid.NewGuid(); - - var ct = factory.CreateContentType(0, "alias", new[] { pt1, pt2, pt3 }); - - var c = new ImageWithLegendModel(ct, guid, new Dictionary - { - { "legend", val1 }, - { "image", val2 }, - { "size", val3 }, - }, false); - - Assert.AreEqual(val1, c.Legend); - Assert.AreEqual(val3, c.Size); - } - - class ImageWithLegendModel : PublishedElement - { - public ImageWithLegendModel(PublishedContentType contentType, Guid fragmentKey, Dictionary values, bool previewing) - : base(contentType, fragmentKey, values, previewing) - { } - - - public string Legend => this.Value("legend"); - - public IPublishedContent Image => this.Value("image"); - - public int Size => this.Value("size"); - } - } -} +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Web; +//using NUnit.Framework; +//using Umbraco.Core; +//using Umbraco.Core.Models.PublishedContent; +//using Umbraco.Core.PropertyEditors; +//using Umbraco.Web; +//using Umbraco.Web.PublishedCache; +//using Umbraco.Core.Composing; +//using Moq; +//using Umbraco.Core.Cache; +//using Umbraco.Core.Configuration; +//using Umbraco.Core.Logging; +//using Umbraco.Core.Models; +//using Umbraco.Core.Services; +//using Umbraco.Tests.TestHelpers; +//using Umbraco.Tests.Testing; +//using Umbraco.Web.Models.PublishedContent; +//using Umbraco.Web.PropertyEditors; +// +//namespace Umbraco.Tests.PublishedContent +//{ +// /// +// /// Tests the methods on IPublishedContent using the DefaultPublishedContentStore +// /// +// [TestFixture] +// [UmbracoTest(TypeLoader = UmbracoTestOptions.TypeLoader.PerFixture)] +// public class PublishedContentTests : PublishedContentTestBase +// { +// protected override void Compose() +// { +// base.Compose(); +// +// Composition.RegisterUnique(f => new PublishedModelFactory(f.GetInstance().GetTypes())); +// Composition.RegisterUnique(); +// Composition.RegisterUnique(); +// +// var logger = Mock.Of(); +// var dataTypeService = new TestObjects.TestDataTypeService( +// new DataType(new VoidEditor(logger)) { Id = 1 }, +// new DataType(new TrueFalsePropertyEditor(logger)) { Id = 1001 }, +// new DataType(new RichTextPropertyEditor(logger)) { Id = 1002 }, +// new DataType(new IntegerPropertyEditor(logger)) { Id = 1003 }, +// new DataType(new TextboxPropertyEditor(logger)) { Id = 1004 }, +// new DataType(new MediaPickerPropertyEditor(logger)) { Id = 1005 }); +// Composition.RegisterUnique(f => dataTypeService); +// } +// +// protected override void Initialize() +// { +// base.Initialize(); +// +// var factory = Factory.GetInstance() as PublishedContentTypeFactory; +// +// // need to specify a custom callback for unit tests +// // AutoPublishedContentTypes generates properties automatically +// // when they are requested, but we must declare those that we +// // explicitely want to be here... +// +// var propertyTypes = new[] +// { +// // AutoPublishedContentType will auto-generate other properties +// factory.CreatePropertyType("umbracoNaviHide", 1001), +// factory.CreatePropertyType("selectedNodes", 1), +// factory.CreatePropertyType("umbracoUrlAlias", 1), +// factory.CreatePropertyType("content", 1002), +// factory.CreatePropertyType("testRecursive", 1), +// }; +// var compositionAliases = new[] { "MyCompositionAlias" }; +// var type = new AutoPublishedContentType(0, "anything", compositionAliases, propertyTypes); +// ContentTypesCache.GetPublishedContentTypeByAlias = alias => type; +// } +// +// protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) +// { +// var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); +// +// // this is so the model factory looks into the test assembly +// pluginManager.AssembliesToScan = pluginManager.AssembliesToScan +// .Union(new[] { typeof(PublishedContentTests).Assembly }) +// .ToList(); +// +// return pluginManager; +// } +// +// private readonly Guid _node1173Guid = Guid.NewGuid(); +// +// protected override string GetXmlContent(int templateId) +// { +// return @" +// +// +// +// +//]> +// +// +// +// +// 1 +// +// +// This is some content]]> +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// 1 +// +// +// +// +// +// +// +// +// +//"; +// } +// +// internal IPublishedContent GetNode(int id) +// { +// var ctx = GetUmbracoContext("/test"); +// var doc = ctx.ContentCache.GetById(id); +// Assert.IsNotNull(doc); +// return doc; +// } +// +// [Test] +// public void GetNodeByIds() +// { +// var ctx = GetUmbracoContext("/test"); +// var contentById = ctx.ContentCache.GetById(1173); +// Assert.IsNotNull(contentById); +// var contentByGuid = ctx.ContentCache.GetById(_node1173Guid); +// Assert.IsNotNull(contentByGuid); +// Assert.AreEqual(contentById.Id, contentByGuid.Id); +// Assert.AreEqual(contentById.Key, contentByGuid.Key); +// +// contentById = ctx.ContentCache.GetById(666); +// Assert.IsNull(contentById); +// contentByGuid = ctx.ContentCache.GetById(Guid.NewGuid()); +// Assert.IsNull(contentByGuid); +// } +// +// [Test] +// public void Is_Last_From_Where_Filter_Dynamic_Linq() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children.Where(x => x.IsVisible()).ToIndexedArray(); +// +// foreach (var item in items) +// { +// if (item.Content.Id != 1178) +// { +// Assert.IsFalse(item.IsLast()); +// } +// else +// { +// Assert.IsTrue(item.IsLast()); +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Where_Filter() +// { +// var doc = GetNode(1173); +// +// var items = doc +// .Children +// .Where(x => x.IsVisible()) +// .ToIndexedArray(); +// +// Assert.AreEqual(4, items.Length); +// +// foreach (var d in items) +// { +// switch (d.Content.Id) +// { +// case 1174: +// Assert.IsTrue(d.IsFirst()); +// Assert.IsFalse(d.IsLast()); +// break; +// case 117: +// Assert.IsFalse(d.IsFirst()); +// Assert.IsFalse(d.IsLast()); +// break; +// case 1177: +// Assert.IsFalse(d.IsFirst()); +// Assert.IsFalse(d.IsLast()); +// break; +// case 1178: +// Assert.IsFalse(d.IsFirst()); +// Assert.IsTrue(d.IsLast()); +// break; +// default: +// Assert.Fail("Invalid id."); +// break; +// } +// } +// } +// +// [PublishedModel("Home")] +// internal class Home : PublishedContentModel +// { +// public Home(IPublishedContent content) +// : base(content) +// {} +// } +// +// [PublishedModel("anything")] +// internal class Anything : PublishedContentModel +// { +// public Anything(IPublishedContent content) +// : base(content) +// { } +// } +// +// [Test] +// public void Is_Last_From_Where_Filter2() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children +// .Select(x => x.CreateModel()) // linq, returns IEnumerable +// +// // only way around this is to make sure every IEnumerable extension +// // explicitely returns a PublishedContentSet, not an IEnumerable +// +// .OfType() // ours, return IEnumerable (actually a PublishedContentSet) +// .Where(x => x.IsVisible()) // so, here it's linq again :-( +// .ToIndexedArray(); // so, we need that one for the test to pass +// +// Assert.AreEqual(1, items.Length); +// +// foreach (var d in items) +// { +// switch (d.Content.Id) +// { +// case 1174: +// Assert.IsTrue(d.IsFirst()); +// Assert.IsTrue(d.IsLast()); +// break; +// default: +// Assert.Fail("Invalid id."); +// break; +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Take() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children.Take(4).ToIndexedArray(); +// +// foreach (var item in items) +// { +// if (item.Content.Id != 1178) +// { +// Assert.IsFalse(item.IsLast()); +// } +// else +// { +// Assert.IsTrue(item.IsLast()); +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Skip() +// { +// var doc = GetNode(1173); +// +// foreach (var d in doc.Children.Skip(1).ToIndexedArray()) +// { +// if (d.Content.Id != 1176) +// { +// Assert.IsFalse(d.IsLast()); +// } +// else +// { +// Assert.IsTrue(d.IsLast()); +// } +// } +// } +// +// [Test] +// public void Is_Last_From_Concat() +// { +// var doc = GetNode(1173); +// +// var items = doc.Children +// .Concat(new[] { GetNode(1175), GetNode(4444) }) +// .ToIndexedArray(); +// +// foreach (var item in items) +// { +// if (item.Content.Id != 4444) +// { +// Assert.IsFalse(item.IsLast()); +// } +// else +// { +// Assert.IsTrue(item.IsLast()); +// } +// } +// } +// +// [Test] +// public void Descendants_Ordered_Properly() +// { +// var doc = GetNode(1046); +// +// var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; +// var exindex = 0; +// +// // must respect the XPath descendants-or-self axis! +// foreach (var d in doc.DescendantsOrSelf()) +// Assert.AreEqual(expected[exindex++], d.Id); +// } +// +// [Test] +// public void Get_Property_Value_Recursive() +// { +// var doc = GetNode(1174); +// var rVal = doc.Value("testRecursive", fallback: Fallback.ToAncestors); +// var nullVal = doc.Value("DoNotFindThis", fallback: Fallback.ToAncestors); +// Assert.AreEqual("This is the recursive val", rVal); +// Assert.AreEqual(null, nullVal); +// } +// +// [Test] +// public void Get_Property_Value_Uses_Converter() +// { +// var doc = GetNode(1173); +// +// var propVal = doc.Value("content"); +// Assert.IsInstanceOf(typeof(IHtmlString), propVal); +// Assert.AreEqual("
This is some content
", propVal.ToString()); +// +// var propVal2 = doc.Value("content"); +// Assert.IsInstanceOf(typeof(IHtmlString), propVal2); +// Assert.AreEqual("
This is some content
", propVal2.ToString()); +// +// var propVal3 = doc.Value("Content"); +// Assert.IsInstanceOf(typeof(IHtmlString), propVal3); +// Assert.AreEqual("
This is some content
", propVal3.ToString()); +// } +// +// [Test] +// public void Complex_Linq() +// { +// var doc = GetNode(1173); +// +// var result = doc.Ancestors().OrderBy(x => x.Level) +// .Single() +// .Descendants() +// .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); +// +// Assert.IsNotNull(result); +// } +// +// [Test] +// public void Children_GroupBy_DocumentTypeAlias() +// { +// var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); +// var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); +// var contentTypes = new Dictionary +// { +// { home.Alias, home }, +// { custom.Alias, custom } +// }; +// ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; +// +// var doc = GetNode(1046); +// +// var found1 = doc.Children.GroupBy(x => x.ContentType.Alias).ToArray(); +// +// Assert.AreEqual(2, found1.Length); +// Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count()); +// Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count()); +// } +// +// [Test] +// public void Children_Where_DocumentTypeAlias() +// { +// var home = new AutoPublishedContentType(22, "Home", new PublishedPropertyType[] { }); +// var custom = new AutoPublishedContentType(23, "CustomDocument", new PublishedPropertyType[] { }); +// var contentTypes = new Dictionary +// { +// { home.Alias, home }, +// { custom.Alias, custom } +// }; +// ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; +// +// var doc = GetNode(1046); +// +// var found1 = doc.Children.Where(x => x.ContentType.Alias == "CustomDocument"); +// var found2 = doc.Children.Where(x => x.ContentType.Alias == "Home"); +// +// Assert.AreEqual(1, found1.Count()); +// Assert.AreEqual(2, found2.Count()); +// } +// +// [Test] +// public void Children_Order_By_Update_Date() +// { +// var doc = GetNode(1173); +// +// var ordered = doc.Children.OrderBy(x => x.UpdateDate); +// +// var correctOrder = new[] { 1178, 1177, 1174, 1176 }; +// for (var i = 0; i < correctOrder.Length; i++) +// { +// Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id); +// } +// +// } +// +// [Test] +// public void FirstChild() +// { +// var doc = GetNode(1173); // has child nodes +// Assert.IsNotNull(doc.FirstChild()); +// Assert.IsNotNull(doc.FirstChild(x => true)); +// Assert.IsNotNull(doc.FirstChild()); +// +// doc = GetNode(1175); // does not have child nodes +// Assert.IsNull(doc.FirstChild()); +// Assert.IsNull(doc.FirstChild(x => true)); +// Assert.IsNull(doc.FirstChild()); +// } +// +// [Test] +// public void FirstChildAsT() +// { +// var doc = GetNode(1046); // has child nodes +// +// var model = doc.FirstChild(x => true); // predicate +// +// Assert.IsNotNull(model); +// Assert.IsTrue(model.Id == 1173); +// Assert.IsInstanceOf(model); +// Assert.IsInstanceOf(model); +// +// doc = GetNode(1175); // does not have child nodes +// Assert.IsNull(doc.FirstChild()); +// Assert.IsNull(doc.FirstChild(x => true)); +// } +// +// [Test] +// public void IsComposedOf() +// { +// var doc = GetNode(1173); +// +// var isComposedOf = doc.IsComposedOf("MyCompositionAlias"); +// +// Assert.IsTrue(isComposedOf); +// } +// +// [Test] +// public void HasProperty() +// { +// var doc = GetNode(1173); +// +// var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias); +// +// Assert.IsTrue(hasProp); +// } +// +// [Test] +// public void HasValue() +// { +// var doc = GetNode(1173); +// +// var hasValue = doc.HasValue(Constants.Conventions.Content.UrlAlias); +// var noValue = doc.HasValue("blahblahblah"); +// +// Assert.IsTrue(hasValue); +// Assert.IsFalse(noValue); +// } +// +// [Test] +// public void Ancestors_Where_Visible() +// { +// var doc = GetNode(1174); +// +// var whereVisible = doc.Ancestors().Where(x => x.IsVisible()); +// Assert.AreEqual(1, whereVisible.Count()); +// +// } +// +// [Test] +// public void Visible() +// { +// var hidden = GetNode(1046); +// var visible = GetNode(1173); +// +// Assert.IsFalse(hidden.IsVisible()); +// Assert.IsTrue(visible.IsVisible()); +// } +// +// [Test] +// public void Ancestor_Or_Self() +// { +// var doc = GetNode(1173); +// +// var result = doc.AncestorOrSelf(); +// +// Assert.IsNotNull(result); +// +// // ancestor-or-self has to be self! +// Assert.AreEqual(1173, result.Id); +// } +// +// [Test] +// public void U4_4559() +// { +// var doc = GetNode(1174); +// var result = doc.AncestorOrSelf(1); +// Assert.IsNotNull(result); +// Assert.AreEqual(1046, result.Id); +// } +// +// [Test] +// public void Ancestors_Or_Self() +// { +// var doc = GetNode(1174); +// +// var result = doc.AncestorsOrSelf().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(3, result.Length); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 })); +// } +// +// [Test] +// public void Ancestors() +// { +// var doc = GetNode(1174); +// +// var result = doc.Ancestors().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(2, result.Length); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 })); +// } +// +// [Test] +// public void IsAncestor() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsTrue(root.IsAncestor(customDoc4)); +// Assert.IsFalse(root.IsAncestor(customDoc3)); +// Assert.IsTrue(root.IsAncestor(customDoc2)); +// Assert.IsTrue(root.IsAncestor(customDoc)); +// Assert.IsTrue(root.IsAncestor(home)); +// Assert.IsFalse(root.IsAncestor(root)); +// +// Assert.IsTrue(home.IsAncestor(customDoc4)); +// Assert.IsFalse(home.IsAncestor(customDoc3)); +// Assert.IsTrue(home.IsAncestor(customDoc2)); +// Assert.IsTrue(home.IsAncestor(customDoc)); +// Assert.IsFalse(home.IsAncestor(home)); +// Assert.IsFalse(home.IsAncestor(root)); +// +// Assert.IsFalse(customDoc.IsAncestor(customDoc4)); +// Assert.IsFalse(customDoc.IsAncestor(customDoc3)); +// Assert.IsTrue(customDoc.IsAncestor(customDoc2)); +// Assert.IsFalse(customDoc.IsAncestor(customDoc)); +// Assert.IsFalse(customDoc.IsAncestor(home)); +// Assert.IsFalse(customDoc.IsAncestor(root)); +// +// Assert.IsFalse(customDoc2.IsAncestor(customDoc4)); +// Assert.IsFalse(customDoc2.IsAncestor(customDoc3)); +// Assert.IsFalse(customDoc2.IsAncestor(customDoc2)); +// Assert.IsFalse(customDoc2.IsAncestor(customDoc)); +// Assert.IsFalse(customDoc2.IsAncestor(home)); +// Assert.IsFalse(customDoc2.IsAncestor(root)); +// +// Assert.IsFalse(customDoc3.IsAncestor(customDoc3)); +// } +// +// [Test] +// public void IsAncestorOrSelf() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsTrue(root.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(root.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(root.IsAncestorOrSelf(customDoc2)); +// Assert.IsTrue(root.IsAncestorOrSelf(customDoc)); +// Assert.IsTrue(root.IsAncestorOrSelf(home)); +// Assert.IsTrue(root.IsAncestorOrSelf(root)); +// +// Assert.IsTrue(home.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(home.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(home.IsAncestorOrSelf(customDoc2)); +// Assert.IsTrue(home.IsAncestorOrSelf(customDoc)); +// Assert.IsTrue(home.IsAncestorOrSelf(home)); +// Assert.IsFalse(home.IsAncestorOrSelf(root)); +// +// Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc2)); +// Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc)); +// Assert.IsFalse(customDoc.IsAncestorOrSelf(home)); +// Assert.IsFalse(customDoc.IsAncestorOrSelf(root)); +// +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc4)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc3)); +// Assert.IsTrue(customDoc2.IsAncestorOrSelf(customDoc2)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(home)); +// Assert.IsFalse(customDoc2.IsAncestorOrSelf(root)); +// +// Assert.IsTrue(customDoc4.IsAncestorOrSelf(customDoc4)); +// Assert.IsTrue(customDoc3.IsAncestorOrSelf(customDoc3)); +// } +// +// +// [Test] +// public void Descendants_Or_Self() +// { +// var doc = GetNode(1046); +// +// var result = doc.DescendantsOrSelf().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(10, result.Count()); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); +// } +// +// [Test] +// public void Descendants() +// { +// var doc = GetNode(1046); +// +// var result = doc.Descendants().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(9, result.Count()); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); +// } +// +// [Test] +// public void IsDescendant() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsFalse(root.IsDescendant(root)); +// Assert.IsFalse(root.IsDescendant(home)); +// Assert.IsFalse(root.IsDescendant(customDoc)); +// Assert.IsFalse(root.IsDescendant(customDoc2)); +// Assert.IsFalse(root.IsDescendant(customDoc3)); +// Assert.IsFalse(root.IsDescendant(customDoc4)); +// +// Assert.IsTrue(home.IsDescendant(root)); +// Assert.IsFalse(home.IsDescendant(home)); +// Assert.IsFalse(home.IsDescendant(customDoc)); +// Assert.IsFalse(home.IsDescendant(customDoc2)); +// Assert.IsFalse(home.IsDescendant(customDoc3)); +// Assert.IsFalse(home.IsDescendant(customDoc4)); +// +// Assert.IsTrue(customDoc.IsDescendant(root)); +// Assert.IsTrue(customDoc.IsDescendant(home)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc2)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc3)); +// Assert.IsFalse(customDoc.IsDescendant(customDoc4)); +// +// Assert.IsTrue(customDoc2.IsDescendant(root)); +// Assert.IsTrue(customDoc2.IsDescendant(home)); +// Assert.IsTrue(customDoc2.IsDescendant(customDoc)); +// Assert.IsFalse(customDoc2.IsDescendant(customDoc2)); +// Assert.IsFalse(customDoc2.IsDescendant(customDoc3)); +// Assert.IsFalse(customDoc2.IsDescendant(customDoc4)); +// +// Assert.IsFalse(customDoc3.IsDescendant(customDoc3)); +// } +// +// [Test] +// public void IsDescendantOrSelf() +// { +// // Structure: +// // - Root : 1046 (no parent) +// // -- Home: 1173 (parent 1046) +// // -- Custom Doc: 1178 (parent 1173) +// // --- Custom Doc2: 1179 (parent: 1178) +// // -- Custom Doc4: 117 (parent 1173) +// // - Custom Doc3: 1172 (no parent) +// +// var home = GetNode(1173); +// var root = GetNode(1046); +// var customDoc = GetNode(1178); +// var customDoc2 = GetNode(1179); +// var customDoc3 = GetNode(1172); +// var customDoc4 = GetNode(117); +// +// Assert.IsTrue(root.IsDescendantOrSelf(root)); +// Assert.IsFalse(root.IsDescendantOrSelf(home)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(root.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(home.IsDescendantOrSelf(root)); +// Assert.IsTrue(home.IsDescendantOrSelf(home)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(home.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(customDoc.IsDescendantOrSelf(root)); +// Assert.IsTrue(customDoc.IsDescendantOrSelf(home)); +// Assert.IsTrue(customDoc.IsDescendantOrSelf(customDoc)); +// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(root)); +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(home)); +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc)); +// Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc2)); +// Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc3)); +// Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc4)); +// +// Assert.IsTrue(customDoc3.IsDescendantOrSelf(customDoc3)); +// } +// +// [Test] +// public void Up() +// { +// var doc = GetNode(1173); +// +// var result = doc.Up(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(1046, result.Id); +// } +// +// [Test] +// public void Down() +// { +// var doc = GetNode(1173); +// +// var result = doc.Down(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(1174, result.Id); +// } +// +// [Test] +// public void FragmentProperty() +// { +// var factory = Factory.GetInstance() as PublishedContentTypeFactory; +// +// var pt = factory.CreatePropertyType("detached", 1003); +// var ct = factory.CreateContentType(0, "alias", new[] { pt }); +// var prop = new PublishedElementPropertyBase(pt, null, false, PropertyCacheLevel.None, 5548); +// Assert.IsInstanceOf(prop.GetValue()); +// Assert.AreEqual(5548, prop.GetValue()); +// } +// +// public void Fragment1() +// { +// var type = ContentTypesCache.Get(PublishedItemType.Content, "detachedSomething"); +// var values = new Dictionary(); +// var f = new PublishedElement(type, Guid.NewGuid(), values, false); +// } +// +// [Test] +// public void Fragment2() +// { +// var factory = Factory.GetInstance() as PublishedContentTypeFactory; +// +// var pt1 = factory.CreatePropertyType("legend", 1004); +// var pt2 = factory.CreatePropertyType("image", 1005); +// var pt3 = factory.CreatePropertyType("size", 1003); +// const string val1 = "boom bam"; +// const int val2 = 0; +// const int val3 = 666; +// +// var guid = Guid.NewGuid(); +// +// var ct = factory.CreateContentType(0, "alias", new[] { pt1, pt2, pt3 }); +// +// var c = new ImageWithLegendModel(ct, guid, new Dictionary +// { +// { "legend", val1 }, +// { "image", val2 }, +// { "size", val3 }, +// }, false); +// +// Assert.AreEqual(val1, c.Legend); +// Assert.AreEqual(val3, c.Size); +// } +// +// class ImageWithLegendModel : PublishedElement +// { +// public ImageWithLegendModel(PublishedContentType contentType, Guid fragmentKey, Dictionary values, bool previewing) +// : base(contentType, fragmentKey, values, previewing) +// { } +// +// +// public string Legend => this.Value("legend"); +// +// public IPublishedContent Image => this.Value("image"); +// +// public int Size => this.Value("size"); +// } +// } +//} diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index 21353049d8..08813c8a8c 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -1023,21 +1023,15 @@ namespace Umbraco.Web #region Axes: children - private static IEnumerable WhereHasCulture(this IEnumerable contents, string culture = null) + private static IEnumerable WhereHasCultureOrInvariant(this IEnumerable contents, string culture = null) { if (contents == null) throw new ArgumentNullException(nameof(contents)); - var actualCulture = culture ?? GetCurrentCulture(); + var actualCulture = culture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - return contents.Where(x=>x.HasCulture(actualCulture) ||x.HasCulture(null)); + return contents.Where(x=>x.HasCulture(actualCulture) || !x.Cultures.Any()); } - private static string GetCurrentCulture() - { - - //Review: is this the correct way to get the current culture? - return System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - } /// /// Gets the children of the content. @@ -1051,7 +1045,7 @@ namespace Umbraco.Web public static IEnumerable Children(this IPublishedContent content, string culture = null) { if (content == null) throw new ArgumentNullException(nameof(content)); - return content.Children.WhereHasCulture(culture); + return content.Children.WhereHasCultureOrInvariant(culture); } /// From c71f438e6215ef440aec96208f4087e4d628b4e9 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 16 Jan 2019 08:08:13 +0100 Subject: [PATCH 10/41] #3305 - Uncommented irrelevant tests. These tests are irrelevant because they use the legacy `XmlPublishedContent` and not the NuCache --- .../PublishedContentDataTableTests.cs | 422 +++++------ .../PublishedContent/PublishedContentTests.cs | 156 ++--- .../PublishedContent/PublishedMediaTests.cs | 656 +++++++++--------- 3 files changed, 617 insertions(+), 617 deletions(-) diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs index 4e3c17403b..fa60b050cc 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs @@ -1,78 +1,78 @@ -//using System; -//using System.Collections.Generic; -//using System.Collections.ObjectModel; -//using System.Linq; -//using Moq; -//using NUnit.Framework; -//using Umbraco.Core; -//using Umbraco.Core.Composing; -//using Umbraco.Core.Logging; -//using Umbraco.Core.Models; -//using Umbraco.Core.Models.PublishedContent; -//using Umbraco.Core.PropertyEditors; -//using Umbraco.Core.Services; -//using Umbraco.Tests.TestHelpers; -//using Umbraco.Web; -// -//namespace Umbraco.Tests.PublishedContent -//{ -// /// -// /// Unit tests for IPublishedContent and extensions -// /// -// [TestFixture] -// public class PublishedContentDataTableTests : BaseWebTest -// { -// public override void SetUp() -// { -// base.SetUp(); -// -// // need to specify a different callback for testing -// PublishedContentExtensions.GetPropertyAliasesAndNames = (services, alias) => -// { -// var userFields = new Dictionary() -// { -// {"property1", "Property 1"}, -// {"property2", "Property 2"} -// }; -// if (alias == "Child") -// { -// userFields.Add("property4", "Property 4"); -// } -// else -// { -// userFields.Add("property3", "Property 3"); -// } -// -// //ensure the standard fields are there -// var allFields = new Dictionary() -// { -// {"Id", "Id"}, -// {"NodeName", "NodeName"}, -// {"NodeTypeAlias", "NodeTypeAlias"}, -// {"CreateDate", "CreateDate"}, -// {"UpdateDate", "UpdateDate"}, -// {"CreatorName", "CreatorName"}, -// {"WriterName", "WriterName"}, -// {"Url", "Url"} -// }; -// foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key))) -// { -// allFields.Add(f.Key, f.Value); -// } -// return allFields; -// }; -// var umbracoContext = GetUmbracoContext("/test"); -// -// //set the UmbracoContext.Current since the extension methods rely on it -// Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; -// } -// -// public override void TearDown() -// { -// base.TearDown(); -// Umbraco.Web.PublishedContentExtensions.GetPropertyAliasesAndNames = null; -// } -// +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using Moq; +using NUnit.Framework; +using Umbraco.Core; +using Umbraco.Core.Composing; +using Umbraco.Core.Logging; +using Umbraco.Core.Models; +using Umbraco.Core.Models.PublishedContent; +using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Services; +using Umbraco.Tests.TestHelpers; +using Umbraco.Web; + +namespace Umbraco.Tests.PublishedContent +{ + /// + /// Unit tests for IPublishedContent and extensions + /// + [TestFixture] + public class PublishedContentDataTableTests : BaseWebTest + { + public override void SetUp() + { + base.SetUp(); + + // need to specify a different callback for testing + PublishedContentExtensions.GetPropertyAliasesAndNames = (services, alias) => + { + var userFields = new Dictionary() + { + {"property1", "Property 1"}, + {"property2", "Property 2"} + }; + if (alias == "Child") + { + userFields.Add("property4", "Property 4"); + } + else + { + userFields.Add("property3", "Property 3"); + } + + //ensure the standard fields are there + var allFields = new Dictionary() + { + {"Id", "Id"}, + {"NodeName", "NodeName"}, + {"NodeTypeAlias", "NodeTypeAlias"}, + {"CreateDate", "CreateDate"}, + {"UpdateDate", "UpdateDate"}, + {"CreatorName", "CreatorName"}, + {"WriterName", "WriterName"}, + {"Url", "Url"} + }; + foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key))) + { + allFields.Add(f.Key, f.Value); + } + return allFields; + }; + var umbracoContext = GetUmbracoContext("/test"); + + //set the UmbracoContext.Current since the extension methods rely on it + Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; + } + + public override void TearDown() + { + base.TearDown(); + Umbraco.Web.PublishedContentExtensions.GetPropertyAliasesAndNames = null; + } + // [Test] // public void To_DataTable() // { @@ -91,7 +91,7 @@ // Assert.AreEqual("value11", dt.Rows[2]["Property 2"]); // Assert.AreEqual("value12", dt.Rows[2]["Property 4"]); // } -// + // [Test] // public void To_DataTable_With_Filter() // { @@ -111,138 +111,138 @@ // Assert.AreEqual("value11", dt.Rows[1]["Property 2"]); // Assert.AreEqual("value12", dt.Rows[1]["Property 4"]); // } -// -// [Test] -// public void To_DataTable_No_Rows() -// { -// var doc = GetContent(false, 1); -// var dt = doc.ChildrenAsTable(Current.Services); -// //will return an empty data table -// Assert.AreEqual(0, dt.Columns.Count); -// Assert.AreEqual(0, dt.Rows.Count); -// } -// -// private IPublishedContent GetContent(bool createChildren, int indexVals) -// { -// var dataTypeService = new TestObjects.TestDataTypeService( -// new DataType(new VoidEditor(Mock.Of())) { Id = 1 }); -// -// var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); -// var contentTypeAlias = createChildren ? "Parent" : "Child"; -// var d = new TestPublishedContent -// { -// CreateDate = DateTime.Now, -// CreatorId = 1, -// CreatorName = "Shannon", -// Id = 3, -// SortOrder = 4, -// TemplateId = 5, -// UpdateDate = DateTime.Now, -// Path = "-1,3", -// UrlSegment = "home-page", -// Name = "Page" + Guid.NewGuid().ToString(), -// Version = Guid.NewGuid(), -// WriterId = 1, -// WriterName = "Shannon", -// Parent = null, -// Level = 1, -// Children = new List() -// }; -// d.Properties = new Collection(new List -// { -// new RawValueProperty(factory.CreatePropertyType("property1", 1), d, "value" + indexVals), -// new RawValueProperty(factory.CreatePropertyType("property2", 1), d, "value" + (indexVals + 1)) -// }); -// if (createChildren) -// { -// d.Children = new List() -// { -// GetContent(false, indexVals + 3), -// GetContent(false, indexVals + 6), -// GetContent(false, indexVals + 9) -// }; -// } -// -// if (!createChildren) -// { -// //create additional columns, used to test the different columns for child nodes -// ((Collection) d.Properties).Add( -// new RawValueProperty(factory.CreatePropertyType("property4",1), d, "value" + (indexVals + 2))); -// } -// else -// { -// ((Collection) d.Properties).Add( -// new RawValueProperty(factory.CreatePropertyType("property3", 1), d, "value" + (indexVals + 2))); -// } -// -// d.ContentType = new PublishedContentType(22, contentTypeAlias, PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); -// return d; -// } -// -// // note - could probably rewrite those tests using SolidPublishedContentCache -// // l8tr... -// private class TestPublishedContent : IPublishedContent -// { -// public string Url { get; set; } -// public string GetUrl(string culture = null) => throw new NotSupportedException(); -// -// public PublishedItemType ItemType { get; set; } -// -// IPublishedContent IPublishedContent.Parent -// { -// get { return Parent; } -// } -// -// IEnumerable IPublishedContent.Children -// { -// get { return Children; } -// } -// -// public IPublishedContent Parent { get; set; } -// public int Id { get; set; } -// public Guid Key { get; set; } -// public int? TemplateId { get; set; } -// public int SortOrder { get; set; } -// public string Name { get; set; } -// public PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); -// public IReadOnlyDictionary Cultures => throw new NotSupportedException(); -// public string UrlSegment { get; set; } -// public string WriterName { get; set; } -// public string CreatorName { get; set; } -// public int WriterId { get; set; } -// public int CreatorId { get; set; } -// public string Path { get; set; } -// public DateTime CreateDate { get; set; } -// public DateTime UpdateDate { get; set; } -// public Guid Version { get; set; } -// public int Level { get; set; } -// public bool IsDraft(string culture = null) => false; -// -// public IEnumerable Properties { get; set; } -// -// public IEnumerable Children { get; set; } -// -// public IPublishedProperty GetProperty(string alias) -// { -// return Properties.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); -// } -// -// public IPublishedProperty GetProperty(string alias, bool recurse) -// { -// var property = GetProperty(alias); -// if (recurse == false) return property; -// -// IPublishedContent content = this; -// while (content != null && (property == null || property.HasValue() == false)) -// { -// content = content.Parent; -// property = content == null ? null : content.GetProperty(alias); -// } -// -// return property; -// } -// -// public PublishedContentType ContentType { get; set; } -// } -// } -//} + + [Test] + public void To_DataTable_No_Rows() + { + var doc = GetContent(false, 1); + var dt = doc.ChildrenAsTable(Current.Services); + //will return an empty data table + Assert.AreEqual(0, dt.Columns.Count); + Assert.AreEqual(0, dt.Rows.Count); + } + + private IPublishedContent GetContent(bool createChildren, int indexVals) + { + var dataTypeService = new TestObjects.TestDataTypeService( + new DataType(new VoidEditor(Mock.Of())) { Id = 1 }); + + var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); + var contentTypeAlias = createChildren ? "Parent" : "Child"; + var d = new TestPublishedContent + { + CreateDate = DateTime.Now, + CreatorId = 1, + CreatorName = "Shannon", + Id = 3, + SortOrder = 4, + TemplateId = 5, + UpdateDate = DateTime.Now, + Path = "-1,3", + UrlSegment = "home-page", + Name = "Page" + Guid.NewGuid().ToString(), + Version = Guid.NewGuid(), + WriterId = 1, + WriterName = "Shannon", + Parent = null, + Level = 1, + Children = new List() + }; + d.Properties = new Collection(new List + { + new RawValueProperty(factory.CreatePropertyType("property1", 1), d, "value" + indexVals), + new RawValueProperty(factory.CreatePropertyType("property2", 1), d, "value" + (indexVals + 1)) + }); + if (createChildren) + { + d.Children = new List() + { + GetContent(false, indexVals + 3), + GetContent(false, indexVals + 6), + GetContent(false, indexVals + 9) + }; + } + + if (!createChildren) + { + //create additional columns, used to test the different columns for child nodes + ((Collection) d.Properties).Add( + new RawValueProperty(factory.CreatePropertyType("property4",1), d, "value" + (indexVals + 2))); + } + else + { + ((Collection) d.Properties).Add( + new RawValueProperty(factory.CreatePropertyType("property3", 1), d, "value" + (indexVals + 2))); + } + + d.ContentType = new PublishedContentType(22, contentTypeAlias, PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); + return d; + } + + // note - could probably rewrite those tests using SolidPublishedContentCache + // l8tr... + private class TestPublishedContent : IPublishedContent + { + public string Url { get; set; } + public string GetUrl(string culture = null) => throw new NotSupportedException(); + + public PublishedItemType ItemType { get; set; } + + IPublishedContent IPublishedContent.Parent + { + get { return Parent; } + } + + IEnumerable IPublishedContent.Children + { + get { return Children; } + } + + public IPublishedContent Parent { get; set; } + public int Id { get; set; } + public Guid Key { get; set; } + public int? TemplateId { get; set; } + public int SortOrder { get; set; } + public string Name { get; set; } + public PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); + public IReadOnlyDictionary Cultures => throw new NotSupportedException(); + public string UrlSegment { get; set; } + public string WriterName { get; set; } + public string CreatorName { get; set; } + public int WriterId { get; set; } + public int CreatorId { get; set; } + public string Path { get; set; } + public DateTime CreateDate { get; set; } + public DateTime UpdateDate { get; set; } + public Guid Version { get; set; } + public int Level { get; set; } + public bool IsDraft(string culture = null) => false; + + public IEnumerable Properties { get; set; } + + public IEnumerable Children { get; set; } + + public IPublishedProperty GetProperty(string alias) + { + return Properties.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); + } + + public IPublishedProperty GetProperty(string alias, bool recurse) + { + var property = GetProperty(alias); + if (recurse == false) return property; + + IPublishedContent content = this; + while (content != null && (property == null || property.HasValue() == false)) + { + content = content.Parent; + property = content == null ? null : content.GetProperty(alias); + } + + return property; + } + + public PublishedContentType ContentType { get; set; } + } + } +} diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index 603464e18b..855d864cc4 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -326,18 +326,18 @@ namespace Umbraco.Tests.PublishedContent } } - [Test] - public void Descendants_Ordered_Properly() - { - var doc = GetNode(1046); - - var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; - var exindex = 0; - - // must respect the XPath descendants-or-self axis! - foreach (var d in doc.DescendantsOrSelf()) - Assert.AreEqual(expected[exindex++], d.Id); - } +// [Test] +// public void Descendants_Ordered_Properly() +// { +// var doc = GetNode(1046); +// +// var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; +// var exindex = 0; +// +// // must respect the XPath descendants-or-self axis! +// foreach (var d in doc.DescendantsOrSelf()) +// Assert.AreEqual(expected[exindex++], d.Id); +// } [Test] public void Get_Property_Value_Recursive() @@ -367,18 +367,18 @@ namespace Umbraco.Tests.PublishedContent Assert.AreEqual("
This is some content
", propVal3.ToString()); } - [Test] - public void Complex_Linq() - { - var doc = GetNode(1173); - - var result = doc.Ancestors().OrderBy(x => x.Level) - .Single() - .Descendants() - .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); - - Assert.IsNotNull(result); - } +// [Test] +// public void Complex_Linq() +// { +// var doc = GetNode(1173); +// +// var result = doc.Ancestors().OrderBy(x => x.Level) +// .Single() +// .Descendants() +// .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); +// +// Assert.IsNotNull(result); +// } [Test] public void Children_GroupBy_DocumentTypeAlias() @@ -437,36 +437,36 @@ namespace Umbraco.Tests.PublishedContent } - [Test] - public void FirstChild() - { - var doc = GetNode(1173); // has child nodes - Assert.IsNotNull(doc.FirstChild()); - Assert.IsNotNull(doc.FirstChild(x => true)); - Assert.IsNotNull(doc.FirstChild()); +// [Test] +// public void FirstChild() +// { +// var doc = GetNode(1173); // has child nodes +// Assert.IsNotNull(doc.FirstChild()); +// Assert.IsNotNull(doc.FirstChild(x => true)); +// Assert.IsNotNull(doc.FirstChild()); +// +// doc = GetNode(1175); // does not have child nodes +// Assert.IsNull(doc.FirstChild()); +// Assert.IsNull(doc.FirstChild(x => true)); +// Assert.IsNull(doc.FirstChild()); +// } - doc = GetNode(1175); // does not have child nodes - Assert.IsNull(doc.FirstChild()); - Assert.IsNull(doc.FirstChild(x => true)); - Assert.IsNull(doc.FirstChild()); - } - - [Test] - public void FirstChildAsT() - { - var doc = GetNode(1046); // has child nodes - - var model = doc.FirstChild(x => true); // predicate - - Assert.IsNotNull(model); - Assert.IsTrue(model.Id == 1173); - Assert.IsInstanceOf(model); - Assert.IsInstanceOf(model); - - doc = GetNode(1175); // does not have child nodes - Assert.IsNull(doc.FirstChild()); - Assert.IsNull(doc.FirstChild(x => true)); - } +// [Test] +// public void FirstChildAsT() +// { +// var doc = GetNode(1046); // has child nodes +// +// var model = doc.FirstChild(x => true); // predicate +// +// Assert.IsNotNull(model); +// Assert.IsTrue(model.Id == 1173); +// Assert.IsInstanceOf(model); +// Assert.IsInstanceOf(model); +// +// doc = GetNode(1175); // does not have child nodes +// Assert.IsNull(doc.FirstChild()); +// Assert.IsNull(doc.FirstChild(x => true)); +// } [Test] public void IsComposedOf() @@ -668,31 +668,31 @@ namespace Umbraco.Tests.PublishedContent } - [Test] - public void Descendants_Or_Self() - { - var doc = GetNode(1046); - - var result = doc.DescendantsOrSelf().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(10, result.Count()); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); - } - - [Test] - public void Descendants() - { - var doc = GetNode(1046); - - var result = doc.Descendants().ToArray(); - - Assert.IsNotNull(result); - - Assert.AreEqual(9, result.Count()); - Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); - } +// [Test] +// public void Descendants_Or_Self() +// { +// var doc = GetNode(1046); +// +// var result = doc.DescendantsOrSelf().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(10, result.Count()); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); +// } +// +// [Test] +// public void Descendants() +// { +// var doc = GetNode(1046); +// +// var result = doc.Descendants().ToArray(); +// +// Assert.IsNotNull(result); +// +// Assert.AreEqual(9, result.Count()); +// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); +// } [Test] public void IsDescendant() diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index f88f37a972..7653b9c5f8 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -1,113 +1,113 @@ -//using System.Web; -//using System.Xml.Linq; -//using System.Xml.XPath; -//using NUnit.Framework; -//using Umbraco.Core; -//using Umbraco.Core.Models; -//using Umbraco.Tests.TestHelpers; -//using Umbraco.Tests.TestHelpers.Entities; -//using Umbraco.Tests.UmbracoExamine; -//using Umbraco.Web; -//using Umbraco.Web.PublishedCache.XmlPublishedCache; -//using System.Linq; -//using System.Threading; -//using System.Xml; -//using Examine; -//using Umbraco.Core.Cache; -//using Umbraco.Core.Models.PublishedContent; -//using Umbraco.Core.Strings; -//using Umbraco.Examine; -//using Current = Umbraco.Web.Composing.Current; -//using Umbraco.Tests.Testing; -//using Umbraco.Core.Composing; -//using Umbraco.Core.Models.Membership; -//using Umbraco.Core.PropertyEditors; -// -//namespace Umbraco.Tests.PublishedContent -//{ -// /// -// /// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore -// /// -// [TestFixture] -// [Apartment(ApartmentState.STA)] -// [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, WithApplication = true)] -// public class PublishedMediaTests : PublishedContentTestBase -// { -// /// -// /// sets up resolvers before resolution is frozen -// /// -// protected override void Compose() -// { -// base.Compose(); -// -// Composition.WithCollectionBuilder() -// .Clear() -// .Append(); -// } -// -// private IMediaType MakeNewMediaType(IUser user, string text, int parentId = -1) -// { -// var mt = new MediaType(parentId) { Name = text, Alias = text, Thumbnail = "icon-folder", Icon = "icon-folder" }; -// ServiceContext.MediaTypeService.Save(mt); -// return mt; -// } -// -// private IMedia MakeNewMedia(string name, IMediaType mediaType, IUser user, int parentId) -// { -// var m = ServiceContext.MediaService.CreateMediaWithIdentity(name, parentId, mediaType.Alias); -// return m; -// } -// -// /// -// /// Shared with PublishMediaStoreTests -// /// -// /// -// /// -// /// -// internal IPublishedContent GetNode(int id, UmbracoContext umbracoContext) -// { -// var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new StaticCacheProvider(), ContentTypesCache); -// var doc = cache.GetById(id); -// Assert.IsNotNull(doc); -// return doc; -// } -// -// private IPublishedContent GetNode(int id) -// { -// return GetNode(id, GetUmbracoContext("/test")); -// } -// -// [Test] -// public void Get_Property_Value_Uses_Converter() -// { -// var mType = MockedContentTypes.CreateImageMediaType("image2"); -// //lets add an RTE to this -// mType.PropertyGroups.First().PropertyTypes.Add( -// new PropertyType("test", ValueStorageType.Nvarchar, "content") -// { -// Name = "Rich Text", -// DataTypeId = -87 //tiny mce -// }); -// ServiceContext.MediaTypeService.Save(mType); -// var media = MockedMedia.CreateMediaImage(mType, -1); -// media.Properties["content"].SetValue("
This is some content
"); -// ServiceContext.MediaService.Save(media); -// -// var publishedMedia = GetNode(media.Id); -// -// var propVal = publishedMedia.Value("content"); -// Assert.IsInstanceOf(propVal); -// Assert.AreEqual("
This is some content
", propVal.ToString()); -// -// var propVal2 = publishedMedia.Value("content"); -// Assert.IsInstanceOf(propVal2); -// Assert.AreEqual("
This is some content
", propVal2.ToString()); -// -// var propVal3 = publishedMedia.Value("Content"); -// Assert.IsInstanceOf(propVal3); -// Assert.AreEqual("
This is some content
", propVal3.ToString()); -// } -// +using System.Web; +using System.Xml.Linq; +using System.Xml.XPath; +using NUnit.Framework; +using Umbraco.Core; +using Umbraco.Core.Models; +using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.TestHelpers.Entities; +using Umbraco.Tests.UmbracoExamine; +using Umbraco.Web; +using Umbraco.Web.PublishedCache.XmlPublishedCache; +using System.Linq; +using System.Threading; +using System.Xml; +using Examine; +using Umbraco.Core.Cache; +using Umbraco.Core.Models.PublishedContent; +using Umbraco.Core.Strings; +using Umbraco.Examine; +using Current = Umbraco.Web.Composing.Current; +using Umbraco.Tests.Testing; +using Umbraco.Core.Composing; +using Umbraco.Core.Models.Membership; +using Umbraco.Core.PropertyEditors; + +namespace Umbraco.Tests.PublishedContent +{ + /// + /// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore + /// + [TestFixture] + [Apartment(ApartmentState.STA)] + [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, WithApplication = true)] + public class PublishedMediaTests : PublishedContentTestBase + { + /// + /// sets up resolvers before resolution is frozen + /// + protected override void Compose() + { + base.Compose(); + + Composition.WithCollectionBuilder() + .Clear() + .Append(); + } + + private IMediaType MakeNewMediaType(IUser user, string text, int parentId = -1) + { + var mt = new MediaType(parentId) { Name = text, Alias = text, Thumbnail = "icon-folder", Icon = "icon-folder" }; + ServiceContext.MediaTypeService.Save(mt); + return mt; + } + + private IMedia MakeNewMedia(string name, IMediaType mediaType, IUser user, int parentId) + { + var m = ServiceContext.MediaService.CreateMediaWithIdentity(name, parentId, mediaType.Alias); + return m; + } + + /// + /// Shared with PublishMediaStoreTests + /// + /// + /// + /// + internal IPublishedContent GetNode(int id, UmbracoContext umbracoContext) + { + var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new StaticCacheProvider(), ContentTypesCache); + var doc = cache.GetById(id); + Assert.IsNotNull(doc); + return doc; + } + + private IPublishedContent GetNode(int id) + { + return GetNode(id, GetUmbracoContext("/test")); + } + + [Test] + public void Get_Property_Value_Uses_Converter() + { + var mType = MockedContentTypes.CreateImageMediaType("image2"); + //lets add an RTE to this + mType.PropertyGroups.First().PropertyTypes.Add( + new PropertyType("test", ValueStorageType.Nvarchar, "content") + { + Name = "Rich Text", + DataTypeId = -87 //tiny mce + }); + ServiceContext.MediaTypeService.Save(mType); + var media = MockedMedia.CreateMediaImage(mType, -1); + media.Properties["content"].SetValue("
This is some content
"); + ServiceContext.MediaService.Save(media); + + var publishedMedia = GetNode(media.Id); + + var propVal = publishedMedia.Value("content"); + Assert.IsInstanceOf(propVal); + Assert.AreEqual("
This is some content
", propVal.ToString()); + + var propVal2 = publishedMedia.Value("content"); + Assert.IsInstanceOf(propVal2); + Assert.AreEqual("
This is some content
", propVal2.ToString()); + + var propVal3 = publishedMedia.Value("Content"); + Assert.IsInstanceOf(propVal3); + Assert.AreEqual("
This is some content
", propVal3.ToString()); + } + // [Test] // public void Ensure_Children_Sorted_With_Examine() // { @@ -136,55 +136,55 @@ // } // } // } -// -// [Test] -// public void Do_Not_Find_In_Recycle_Bin() -// { -// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); -// -// using (var luceneDir = new RandomIdRamDirectory()) -// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, -// //include unpublished content since this uses the 'internal' indexer, it's up to the media cache to filter -// validator: new ContentValueSetValidator(false))) -// using (indexer.ProcessNonAsync()) -// { -// rebuilder.RegisterIndex(indexer.Name); -// rebuilder.Populate(indexer); -// -// var searcher = indexer.GetSearcher(); -// var ctx = GetUmbracoContext("/test"); -// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); -// -// //ensure it is found -// var publishedMedia = cache.GetById(3113); -// Assert.IsNotNull(publishedMedia); -// -// //move item to recycle bin -// var newXml = XElement.Parse(@" -// -// 115 -// 268 -// 10726 -// jpg -// "); -// indexer.IndexItems(new[]{ newXml.ConvertToValueSet("media") }); -// -// -// //ensure it still exists in the index (raw examine search) -// var criteria = searcher.CreateQuery(); -// var filter = criteria.Id(3113); -// var found = filter.Execute(); -// Assert.IsNotNull(found); -// Assert.AreEqual(1, found.TotalItemCount); -// -// //ensure it does not show up in the published media store -// var recycledMedia = cache.GetById(3113); -// Assert.IsNull(recycledMedia); -// -// } -// -// } -// + + [Test] + public void Do_Not_Find_In_Recycle_Bin() + { + var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); + + using (var luceneDir = new RandomIdRamDirectory()) + using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, + //include unpublished content since this uses the 'internal' indexer, it's up to the media cache to filter + validator: new ContentValueSetValidator(false))) + using (indexer.ProcessNonAsync()) + { + rebuilder.RegisterIndex(indexer.Name); + rebuilder.Populate(indexer); + + var searcher = indexer.GetSearcher(); + var ctx = GetUmbracoContext("/test"); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); + + //ensure it is found + var publishedMedia = cache.GetById(3113); + Assert.IsNotNull(publishedMedia); + + //move item to recycle bin + var newXml = XElement.Parse(@" + + 115 + 268 + 10726 + jpg + "); + indexer.IndexItems(new[]{ newXml.ConvertToValueSet("media") }); + + + //ensure it still exists in the index (raw examine search) + var criteria = searcher.CreateQuery(); + var filter = criteria.Id(3113); + var found = filter.Execute(); + Assert.IsNotNull(found); + Assert.AreEqual(1, found.TotalItemCount); + + //ensure it does not show up in the published media store + var recycledMedia = cache.GetById(3113); + Assert.IsNull(recycledMedia); + + } + + } + // [Test] // public void Children_With_Examine() // { @@ -212,7 +212,7 @@ // Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { 2112 })); // } // } -// + // [Test] // public void Descendants_With_Examine() // { @@ -240,7 +240,7 @@ // Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 3113 })); // } // } -// + // [Test] // public void DescendantsOrSelf_With_Examine() // { @@ -268,58 +268,58 @@ // Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2222, 2112, 3113 })); // } // } -// -// [Test] -// public void Ancestors_With_Examine() -// { -// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); -// -// -// using (var luceneDir = new RandomIdRamDirectory()) -// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, -// validator: new ContentValueSetValidator(true))) -// using (indexer.ProcessNonAsync()) -// { -// rebuilder.RegisterIndex(indexer.Name); -// rebuilder.Populate(indexer); -// -// var ctx = GetUmbracoContext("/test"); -// var searcher = indexer.GetSearcher(); -// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); -// -// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace -// var publishedMedia = cache.GetById(3113); -// var ancestors = publishedMedia.Ancestors(); -// Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1111 })); -// } -// -// } -// -// [Test] -// public void AncestorsOrSelf_With_Examine() -// { -// var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); -// -// using (var luceneDir = new RandomIdRamDirectory()) -// using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, -// validator: new ContentValueSetValidator(true))) -// using (indexer.ProcessNonAsync()) -// { -// rebuilder.RegisterIndex(indexer.Name); -// rebuilder.Populate(indexer); -// -// -// var ctx = GetUmbracoContext("/test"); -// var searcher = indexer.GetSearcher(); -// var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); -// -// //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace -// var publishedMedia = cache.GetById(3113); -// var ancestors = publishedMedia.AncestorsOrSelf(); -// Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 3113, 2112, 2222, 1111 })); -// } -// } -// + + [Test] + public void Ancestors_With_Examine() + { + var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); + + + using (var luceneDir = new RandomIdRamDirectory()) + using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, + validator: new ContentValueSetValidator(true))) + using (indexer.ProcessNonAsync()) + { + rebuilder.RegisterIndex(indexer.Name); + rebuilder.Populate(indexer); + + var ctx = GetUmbracoContext("/test"); + var searcher = indexer.GetSearcher(); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); + + //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace + var publishedMedia = cache.GetById(3113); + var ancestors = publishedMedia.Ancestors(); + Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1111 })); + } + + } + + [Test] + public void AncestorsOrSelf_With_Examine() + { + var rebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); + + using (var luceneDir = new RandomIdRamDirectory()) + using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, + validator: new ContentValueSetValidator(true))) + using (indexer.ProcessNonAsync()) + { + rebuilder.RegisterIndex(indexer.Name); + rebuilder.Populate(indexer); + + + var ctx = GetUmbracoContext("/test"); + var searcher = indexer.GetSearcher(); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, indexer, new StaticCacheProvider(), ContentTypesCache); + + //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace + var publishedMedia = cache.GetById(3113); + var ancestors = publishedMedia.AncestorsOrSelf(); + Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 3113, 2112, 2222, 1111 })); + } + } + // [Test] // public void Children_Without_Examine() // { @@ -343,7 +343,7 @@ // var subChildren = publishedChild1.Children(); // Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); // } -// + // [Test] // public void Descendants_Without_Examine() // { @@ -367,7 +367,7 @@ // var subDescendants = publishedChild1.Descendants(); // Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); // } -// + // [Test] // public void DescendantsOrSelf_Without_Examine() // { @@ -393,116 +393,116 @@ // Assert.IsTrue(subDescendantsOrSelf.Select(x => x.Id).ContainsAll( // new[] { mChild1.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); // } -// -// [Test] -// public void Parent_Without_Examine() -// { -// var user = ServiceContext.UserService.GetUserById(0); -// var mType = MakeNewMediaType(user, "TestMediaType"); -// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); -// -// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); -// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); -// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); -// -// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); -// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); -// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); -// -// var publishedRoot = GetNode(mRoot.Id); -// Assert.AreEqual(null, publishedRoot.Parent); -// -// var publishedChild1 = GetNode(mChild1.Id); -// Assert.AreEqual(mRoot.Id, publishedChild1.Parent.Id); -// -// var publishedSubChild1 = GetNode(mSubChild1.Id); -// Assert.AreEqual(mChild1.Id, publishedSubChild1.Parent.Id); -// } -// -// [Test] -// public void Ancestors_Without_Examine() -// { -// var user = ServiceContext.UserService.GetUserById(0); -// var mType = MakeNewMediaType(user, "TestMediaType"); -// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); -// -// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); -// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); -// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); -// -// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); -// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); -// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); -// -// var publishedSubChild1 = GetNode(mSubChild1.Id); -// Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mRoot.Id })); -// } -// -// [Test] -// public void AncestorsOrSelf_Without_Examine() -// { -// var user = ServiceContext.UserService.GetUserById(0); -// var mType = MakeNewMediaType(user, "TestMediaType"); -// var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); -// -// var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); -// var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); -// var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); -// -// var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); -// var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); -// var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); -// -// var publishedSubChild1 = GetNode(mSubChild1.Id); -// Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id).ContainsAll( -// new[] { mSubChild1.Id, mChild1.Id, mRoot.Id })); -// } -// -// [Test] -// public void Convert_From_Standard_Xml() -// { -// var nodeId = 2112; -// -// var xml = XElement.Parse(@" -// -// 115 -// 268 -// 10726 -// jpg -// -// -// 115 -// 268 -// 10726 -// jpg -// -// "); -// var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); -// -// var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); -// -// var nav = node.CreateNavigator(); -// -// var converted = publishedMedia.CreateFromCacheValues( -// publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/Image"), nodeId)); -// -// Assert.AreEqual(nodeId, converted.Id); -// Assert.AreEqual(3, converted.Level); -// Assert.AreEqual(1, converted.SortOrder); -// Assert.AreEqual("Sam's Umbraco Image", converted.Name); -// Assert.AreEqual("-1,1111,2222,2112", converted.Path); -// } -// -// [Test] -// public void Detects_Error_In_Xml() -// { -// var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); -// var nav = errorXml.CreateNavigator(); -// -// var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); -// var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); -// -// Assert.IsNull(converted); -// } -// } -//} + + [Test] + public void Parent_Without_Examine() + { + var user = ServiceContext.UserService.GetUserById(0); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); + + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); + + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); + + var publishedRoot = GetNode(mRoot.Id); + Assert.AreEqual(null, publishedRoot.Parent); + + var publishedChild1 = GetNode(mChild1.Id); + Assert.AreEqual(mRoot.Id, publishedChild1.Parent.Id); + + var publishedSubChild1 = GetNode(mSubChild1.Id); + Assert.AreEqual(mChild1.Id, publishedSubChild1.Parent.Id); + } + + [Test] + public void Ancestors_Without_Examine() + { + var user = ServiceContext.UserService.GetUserById(0); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); + + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); + + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); + + var publishedSubChild1 = GetNode(mSubChild1.Id); + Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mRoot.Id })); + } + + [Test] + public void AncestorsOrSelf_Without_Examine() + { + var user = ServiceContext.UserService.GetUserById(0); + var mType = MakeNewMediaType(user, "TestMediaType"); + var mRoot = MakeNewMedia("MediaRoot", mType, user, -1); + + var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id); + var mChild2 = MakeNewMedia("Child2", mType, user, mRoot.Id); + var mChild3 = MakeNewMedia("Child3", mType, user, mRoot.Id); + + var mSubChild1 = MakeNewMedia("SubChild1", mType, user, mChild1.Id); + var mSubChild2 = MakeNewMedia("SubChild2", mType, user, mChild1.Id); + var mSubChild3 = MakeNewMedia("SubChild3", mType, user, mChild1.Id); + + var publishedSubChild1 = GetNode(mSubChild1.Id); + Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id).ContainsAll( + new[] { mSubChild1.Id, mChild1.Id, mRoot.Id })); + } + + [Test] + public void Convert_From_Standard_Xml() + { + var nodeId = 2112; + + var xml = XElement.Parse(@" + + 115 + 268 + 10726 + jpg + + + 115 + 268 + 10726 + jpg + + "); + var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); + + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); + + var nav = node.CreateNavigator(); + + var converted = publishedMedia.CreateFromCacheValues( + publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/Image"), nodeId)); + + Assert.AreEqual(nodeId, converted.Id); + Assert.AreEqual(3, converted.Level); + Assert.AreEqual(1, converted.SortOrder); + Assert.AreEqual("Sam's Umbraco Image", converted.Name); + Assert.AreEqual("-1,1111,2222,2112", converted.Path); + } + + [Test] + public void Detects_Error_In_Xml() + { + var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); + var nav = errorXml.CreateNavigator(); + + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache); + var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); + + Assert.IsNull(converted); + } + } +} From 8ad998ab12836eafe39e00694aad023af24ee1b0 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 16 Jan 2019 08:21:24 +0100 Subject: [PATCH 11/41] #3305 - Clean up and xml-comments --- src/Umbraco.Web/PublishedContentExtensions.cs | 82 +++++++++++-------- 1 file changed, 46 insertions(+), 36 deletions(-) diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index 08813c8a8c..0e1f75684a 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -4,9 +4,7 @@ using System.Data; using System.Linq; using System.Web; using Examine; -using Examine.Search; using Umbraco.Core; -using Umbraco.Core.Configuration; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Models; using Umbraco.Core.Services; @@ -268,6 +266,20 @@ namespace Umbraco.Web public static bool HasCulture(this IPublishedContent content, string culture) => content.Cultures.ContainsKey(culture); + /// + /// Filter by the specific culture or invariant. If null is provided, the method uses the current culture instead. + /// + /// The content. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) + /// These of the inputs that has the specified culture or are invariant. + public static IEnumerable WhereHasCultureOrInvariant(this IEnumerable contents, string culture = null) + { + if (contents == null) throw new ArgumentNullException(nameof(contents)); + + var actualCulture = culture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; + + return contents.Where(x=>x.HasCulture(actualCulture) || !x.Cultures.Any()); + } #endregion #region Search @@ -767,27 +779,29 @@ namespace Umbraco.Web ///
/// /// + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// /// /// This can be useful in order to return all nodes in an entire site by a type when combined with TypedContentAtRoot /// - public static IEnumerable DescendantsOrSelf(this IEnumerable parentNodes, string docTypeAlias) + public static IEnumerable DescendantsOrSelf(this IEnumerable parentNodes, string docTypeAlias, string culture = null) { - return parentNodes.SelectMany(x => x.DescendantsOrSelf(docTypeAlias)); + return parentNodes.SelectMany(x => x.DescendantsOrSelf(docTypeAlias, culture)); } /// /// Returns all DescendantsOrSelf of all content referenced /// /// + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// /// /// This can be useful in order to return all nodes in an entire site by a type when combined with TypedContentAtRoot /// - public static IEnumerable DescendantsOrSelf(this IEnumerable parentNodes) + public static IEnumerable DescendantsOrSelf(this IEnumerable parentNodes, string culture = null) where T : class, IPublishedContent { - return parentNodes.SelectMany(x => x.DescendantsOrSelf()); + return parentNodes.SelectMany(x => x.DescendantsOrSelf(culture)); } @@ -810,58 +824,58 @@ namespace Umbraco.Web // - the relative order of siblings is the order in which they occur in the children property of their parent node. // - children and descendants occur before following siblings. - public static IEnumerable Descendants(this IPublishedContent content) + public static IEnumerable Descendants(this IPublishedContent content, string culture = null) { - return content.DescendantsOrSelf(false, null); + return content.DescendantsOrSelf(false, null, culture); } - public static IEnumerable Descendants(this IPublishedContent content, int level) + public static IEnumerable Descendants(this IPublishedContent content, int level, string culture = null) { - return content.DescendantsOrSelf(false, p => p.Level >= level); + return content.DescendantsOrSelf(false, p => p.Level >= level, culture); } - public static IEnumerable Descendants(this IPublishedContent content, string contentTypeAlias) + public static IEnumerable Descendants(this IPublishedContent content, string contentTypeAlias, string culture = null) { - return content.DescendantsOrSelf(false, p => p.ContentType.Alias == contentTypeAlias); + return content.DescendantsOrSelf(false, p => p.ContentType.Alias == contentTypeAlias, culture); } - public static IEnumerable Descendants(this IPublishedContent content) + public static IEnumerable Descendants(this IPublishedContent content, string culture = null) where T : class, IPublishedContent { - return content.Descendants().OfType(); + return content.Descendants(culture).OfType(); } - public static IEnumerable Descendants(this IPublishedContent content, int level) + public static IEnumerable Descendants(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent { - return content.Descendants(level).OfType(); + return content.Descendants(level, culture).OfType(); } - public static IEnumerable DescendantsOrSelf(this IPublishedContent content) + public static IEnumerable DescendantsOrSelf(this IPublishedContent content, string culture = null) { - return content.DescendantsOrSelf(true, null); + return content.DescendantsOrSelf(true, null, culture); } - public static IEnumerable DescendantsOrSelf(this IPublishedContent content, int level) + public static IEnumerable DescendantsOrSelf(this IPublishedContent content, int level, string culture = null) { - return content.DescendantsOrSelf(true, p => p.Level >= level); + return content.DescendantsOrSelf(true, p => p.Level >= level, culture); } - public static IEnumerable DescendantsOrSelf(this IPublishedContent content, string contentTypeAlias) + public static IEnumerable DescendantsOrSelf(this IPublishedContent content, string contentTypeAlias, string culture = null) { - return content.DescendantsOrSelf(true, p => p.ContentType.Alias == contentTypeAlias); + return content.DescendantsOrSelf(true, p => p.ContentType.Alias == contentTypeAlias, culture); } - public static IEnumerable DescendantsOrSelf(this IPublishedContent content) + public static IEnumerable DescendantsOrSelf(this IPublishedContent content, string culture = null) where T : class, IPublishedContent { - return content.DescendantsOrSelf().OfType(); + return content.DescendantsOrSelf(culture).OfType(); } - public static IEnumerable DescendantsOrSelf(this IPublishedContent content, int level) + public static IEnumerable DescendantsOrSelf(this IPublishedContent content, int level, string culture = null) where T : class, IPublishedContent { - return content.DescendantsOrSelf(level).OfType(); + return content.DescendantsOrSelf(level, culture).OfType(); } public static IPublishedContent Descendant(this IPublishedContent content, string culture = null) @@ -1023,20 +1037,11 @@ namespace Umbraco.Web #region Axes: children - private static IEnumerable WhereHasCultureOrInvariant(this IEnumerable contents, string culture = null) - { - if (contents == null) throw new ArgumentNullException(nameof(contents)); - - var actualCulture = culture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - - return contents.Where(x=>x.HasCulture(actualCulture) || !x.Cultures.Any()); - } - - /// /// Gets the children of the content. /// /// The content. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// The children of the content. /// /// Children are sorted by their sortOrder. @@ -1053,6 +1058,7 @@ namespace Umbraco.Web ///
/// The content. /// The predicate. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// The children of the content, filtered by the predicate. /// /// Children are sorted by their sortOrder. @@ -1066,6 +1072,7 @@ namespace Umbraco.Web /// Gets the children of the content, of any of the specified types. ///
/// The content. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// One or more content type alias. /// The children of the content, of any of the specified types. public static IEnumerable Children(this IPublishedContent content, string culture = null, params string[] alias) @@ -1078,6 +1085,7 @@ namespace Umbraco.Web ///
/// The content type. /// The content. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// The children of content, of the given content type. /// /// Children are sorted by their sortOrder. @@ -1127,6 +1135,7 @@ namespace Umbraco.Web /// The content. /// A service context. /// An optional content type alias. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// The children of the content. public static DataTable ChildrenAsTable(this IPublishedContent content, ServiceContext services, string contentTypeAliasFilter = "", string culture = null) { @@ -1139,6 +1148,7 @@ namespace Umbraco.Web /// The content. /// A service context. /// An optional content type alias. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// The children of the content. private static DataTable GenerateDataTable(IPublishedContent content, ServiceContext services, string contentTypeAliasFilter = "", string culture = null) { From b4f2d514be5b2c14bbb5c4b2729daf407bd70176 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 16 Jan 2019 11:44:27 +0100 Subject: [PATCH 12/41] #3305 - changed new method to be internal --- src/Umbraco.Web/PublishedContentExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index 0e1f75684a..d30414b3d3 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -272,7 +272,7 @@ namespace Umbraco.Web /// The content. /// The specific culture to filter for. If null is used the current culture is used. (Default is null) /// These of the inputs that has the specified culture or are invariant. - public static IEnumerable WhereHasCultureOrInvariant(this IEnumerable contents, string culture = null) + internal static IEnumerable WhereHasCultureOrInvariant(this IEnumerable contents, string culture = null) { if (contents == null) throw new ArgumentNullException(nameof(contents)); From 35650536c8f9956a86cb87284744e7d1283be202 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 16 Jan 2019 13:23:19 +0100 Subject: [PATCH 13/41] 3305 - Use the `VariationContext` instead of thread directly --- src/Umbraco.Web/PublishedContentExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index d30414b3d3..4efe6bc82b 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -276,7 +276,7 @@ namespace Umbraco.Web { if (contents == null) throw new ArgumentNullException(nameof(contents)); - var actualCulture = culture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; + var actualCulture = culture ?? Current.VariationContextAccessor.VariationContext.Culture; return contents.Where(x=>x.HasCulture(actualCulture) || !x.Cultures.Any()); } From 664a892fd5073a37a9d10bb4a5ea57c0e29df948 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 16 Jan 2019 15:25:42 +0100 Subject: [PATCH 14/41] 3305 - fixed tests --- .../Testing/Objects/Accessors/TestVariationContextAccessor.cs | 2 +- .../PublishedCache/XmlPublishedCache/XmlPublishedContent.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs b/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs index 3c7377f2cc..4b56799fa4 100644 --- a/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs +++ b/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs @@ -12,6 +12,6 @@ namespace Umbraco.Tests.Testing.Objects.Accessors { get; set; - } + } = new VariationContext(); } } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs index efd4535bd4..d8436c05b5 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs @@ -138,7 +138,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public override PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); - public override IReadOnlyDictionary Cultures => throw new NotSupportedException(); + public override IReadOnlyDictionary Cultures => new Dictionary(); public override string WriterName { From 0d0179cb476450b4c580efb95f5c6b785270e3e1 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Thu, 17 Jan 2019 12:14:17 +0100 Subject: [PATCH 15/41] Use constants in upgrade migration --- .../UpdateMemberGroupPickerData.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs index 2dbc69e58a..62cbeacc78 100644 --- a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs +++ b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenFourteenZero/UpdateMemberGroupPickerData.cs @@ -16,17 +16,17 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenFourtee public override void Up() { // move the data for all member group properties from the NVarchar to the NText column and clear the NVarchar column - Execute.Sql(@"UPDATE cmsPropertyData SET dataNtext = dataNvarchar, dataNvarchar = NULL + Execute.Sql($@"UPDATE cmsPropertyData SET dataNtext = dataNvarchar, dataNvarchar = NULL WHERE dataNtext IS NULL AND id IN ( SELECT id FROM cmsPropertyData WHERE propertyTypeId in ( SELECT id from cmsPropertyType where dataTypeID IN ( - SELECT nodeId FROM cmsDataType WHERE propertyEditorAlias = 'Umbraco.MemberGroupPicker' + SELECT nodeId FROM cmsDataType WHERE propertyEditorAlias = '{Constants.PropertyEditors.MemberGroupPickerAlias}' ) ) )"); // ensure that all exising member group properties are defined as NText - Execute.Sql("UPDATE cmsDataType SET dbType = 'Ntext' WHERE propertyEditorAlias = 'Umbraco.MemberGroupPicker'"); + Execute.Sql($"UPDATE cmsDataType SET dbType = 'Ntext' WHERE propertyEditorAlias = '{Constants.PropertyEditors.MemberGroupPickerAlias}'"); } public override void Down() From 77cf071e046dc54adb92194537d9b221d28eda5f Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Thu, 17 Jan 2019 12:20:13 +0100 Subject: [PATCH 16/41] Add "Move" option for deleted items in the media tree (#3914) --- .../views/media/media.restore.controller.js | 135 +++++++++++++----- .../src/views/media/restore.html | 97 +++++++++++-- 2 files changed, 187 insertions(+), 45 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/media/media.restore.controller.js b/src/Umbraco.Web.UI.Client/src/views/media/media.restore.controller.js index 6ef9232c37..bc02217660 100644 --- a/src/Umbraco.Web.UI.Client/src/views/media/media.restore.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/media/media.restore.controller.js @@ -1,63 +1,134 @@ angular.module("umbraco").controller("Umbraco.Editors.Media.RestoreController", - function ($scope, relationResource, mediaResource, navigationService, appState, treeService, localizationService) { + function ($scope, relationResource, mediaResource, navigationService, appState, treeService, userService) { var dialogOptions = $scope.dialogOptions; - var node = dialogOptions.currentNode; + $scope.source = _.clone(dialogOptions.currentNode); - $scope.error = null; - $scope.success = false; + $scope.error = null; + $scope.loading = true; + $scope.moving = false; + $scope.success = false; - relationResource.getByChildId(node.id, "relateParentDocumentOnDelete").then(function (data) { + $scope.dialogTreeEventHandler = $({}); + $scope.searchInfo = { + showSearch: false, + results: [], + selectedSearchResults: [] + } + $scope.treeModel = { + hideHeader: false + } + userService.getCurrentUser().then(function (userData) { + $scope.treeModel.hideHeader = userData.startContentIds.length > 0 && userData.startContentIds.indexOf(-1) == -1; + }); - if (data.length == 0) { - $scope.success = false; - $scope.error = { - errorMsg: localizationService.localize('recycleBin_itemCannotBeRestored'), - data: { - Message: localizationService.localize('recycleBin_noRestoreRelation') - } - } - return; + function nodeSelectHandler(ev, args) { + + if (args && args.event) { + args.event.preventDefault(); + args.event.stopPropagation(); } + if ($scope.target) { + //un-select if there's a current one selected + $scope.target.selected = false; + } + + $scope.target = args.node; + $scope.target.selected = true; + + } + + function nodeExpandedHandler(ev, args) { + // open mini list view for list views + if (args.node.metaData.isContainer) { + openMiniListView(args.node); + } + } + + $scope.hideSearch = function () { + $scope.searchInfo.showSearch = false; + $scope.searchInfo.results = []; + } + + // method to select a search result + $scope.selectResult = function (evt, result) { + result.selected = result.selected === true ? false : true; + nodeSelectHandler(evt, { event: evt, node: result }); + }; + + //callback when there are search results + $scope.onSearchResults = function (results) { + $scope.searchInfo.results = results; + $scope.searchInfo.showSearch = true; + }; + + $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); + $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); + + $scope.$on('$destroy', function () { + $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); + $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); + }); + + // Mini list view + $scope.selectListViewNode = function (node) { + node.selected = node.selected === true ? false : true; + nodeSelectHandler({}, { node: node }); + }; + + $scope.closeMiniListView = function () { + $scope.miniListView = undefined; + }; + + function openMiniListView(node) { + $scope.miniListView = node; + } + + relationResource.getByChildId($scope.source.id, "relateParentDocumentOnDelete").then(function (data) { + $scope.loading = false; + + if (!data.length) { + $scope.moving = true; + return; + } + $scope.relation = data[0]; if ($scope.relation.parentId == -1) { $scope.target = { id: -1, name: "Root" }; } else { + $scope.loading = true; + mediaResource.getById($scope.relation.parentId).then(function (data) { + $scope.loading = false; $scope.target = data; - // make sure the target item isn't in the recycle bin - if ($scope.target.path.indexOf("-20") !== -1) { - $scope.error = { - errorMsg: localizationService.localize('recycleBin_itemCannotBeRestored'), - data: { - Message: localizationService.localize('recycleBin_restoreUnderRecycled').then(function (value) { - value.replace('%0%', $scope.target.name); - }) - } - }; - $scope.success = false; + // make sure the target item isn't in the recycle bin + if ($scope.target.path.indexOf("-21") !== -1) { + $scope.moving = true; + $scope.target = null; } - }, function (err) { - $scope.success = false; + $scope.loading = false; $scope.error = err; }); } }, function (err) { - $scope.success = false; - $scope.error = err; + $scope.loading = false; + $scope.error = err; }); - $scope.restore = function () { + $scope.restore = function () { + $scope.loading = true; + // this code was copied from `content.move.controller.js` - mediaResource.move({ parentId: $scope.target.id, id: node.id }) + mediaResource.move({ parentId: $scope.target.id, id: $scope.source.id }) .then(function (path) { + $scope.loading = false; $scope.success = true; //first we need to remove the node that launched the dialog @@ -78,7 +149,7 @@ angular.module("umbraco").controller("Umbraco.Editors.Media.RestoreController", }); }, function (err) { - $scope.success = false; + $scope.loading = false; $scope.error = err; }); }; diff --git a/src/Umbraco.Web.UI.Client/src/views/media/restore.html b/src/Umbraco.Web.UI.Client/src/views/media/restore.html index 17fff154d1..a24700afe7 100644 --- a/src/Umbraco.Web.UI.Client/src/views/media/restore.html +++ b/src/Umbraco.Web.UI.Client/src/views/media/restore.html @@ -1,25 +1,96 @@
-
+
+ + -

- Restore {{currentNode.name}} under {{target.name}}? -

+
+
+
{{error.errorMsg}}
+
{{error.data.Message}}
+
+
-
-
{{error.errorMsg}}
-
{{error.data.Message}}
-
+
+
+ {{source.name}} + was restored under + was moved underneath + {{target.name}} +
+ +
-
-

{{currentNode.name}} was moved underneath {{target.name}}

- -
+
+ +

+ Restore {{source.name}} under {{target.name}}? +

+ +
+ +
+
+
+
Cannot automatically restore this item
+
There is no location where this item can be automatically restored. You can move the item manually using the tree below.
+
+
+ +
+ + + +
+ + + + +
+ + +
+
+ + + + +
-
-
Required alias
-
Invalid alias
-
{{lockedFieldForm.lockedField.errorMsg}}
+
+ Required alias +
+
+ Invalid alias +
+
{{lockedFieldForm.lockedField.errorMsg}} +
From adc9957504dce78296f70c86557fc47f69af377c Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Wed, 16 Jan 2019 22:27:58 +0100 Subject: [PATCH 35/41] Show the media link in the info app --- .../views/components/media/umb-media-node-info.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/components/media/umb-media-node-info.html b/src/Umbraco.Web.UI.Client/src/views/components/media/umb-media-node-info.html index 2e09fbfa3b..4004c2b958 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/media/umb-media-node-info.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/media/umb-media-node-info.html @@ -5,16 +5,16 @@ -
/// The content property value. + /// The value property type /// The content dependencies. /// The deploy property value. - string ToArtifact(object value, ICollection dependencies); + string ToArtifact(object value, PropertyType propertyType, ICollection dependencies); /// /// Gets the content property value corresponding to a deploy property value. From e42995cf101347d82ac3069ccb293711fde33f57 Mon Sep 17 00:00:00 2001 From: Stephan Date: Thu, 17 Jan 2019 18:03:07 +0100 Subject: [PATCH 40/41] Fixes for the IPublishedContent Linq/Culture PR --- .../PublishedContentDataTableTests.cs | 74 ++++----- .../PublishedContent/PublishedContentTests.cs | 156 +++++++++--------- .../Accessors/TestVariationContextAccessor.cs | 6 +- .../DictionaryPublishedContent.cs | 5 +- .../XmlPublishedCache/XmlPublishedContent.cs | 5 +- src/Umbraco.Web/PublishedContentExtensions.cs | 27 ++- 6 files changed, 140 insertions(+), 133 deletions(-) diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs index fa60b050cc..73f3cd1537 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs @@ -73,44 +73,44 @@ namespace Umbraco.Tests.PublishedContent Umbraco.Web.PublishedContentExtensions.GetPropertyAliasesAndNames = null; } -// [Test] -// public void To_DataTable() -// { -// var doc = GetContent(true, 1); -// var dt = doc.ChildrenAsTable(Current.Services); -// -// Assert.AreEqual(11, dt.Columns.Count); -// Assert.AreEqual(3, dt.Rows.Count); -// Assert.AreEqual("value4", dt.Rows[0]["Property 1"]); -// Assert.AreEqual("value5", dt.Rows[0]["Property 2"]); -// Assert.AreEqual("value6", dt.Rows[0]["Property 4"]); -// Assert.AreEqual("value7", dt.Rows[1]["Property 1"]); -// Assert.AreEqual("value8", dt.Rows[1]["Property 2"]); -// Assert.AreEqual("value9", dt.Rows[1]["Property 4"]); -// Assert.AreEqual("value10", dt.Rows[2]["Property 1"]); -// Assert.AreEqual("value11", dt.Rows[2]["Property 2"]); -// Assert.AreEqual("value12", dt.Rows[2]["Property 4"]); -// } + [Test] + public void To_DataTable() + { + var doc = GetContent(true, 1); + var dt = doc.ChildrenAsTable(Current.Services); -// [Test] -// public void To_DataTable_With_Filter() -// { -// var doc = GetContent(true, 1); -// //change a doc type alias -// var c = (TestPublishedContent) doc.Children.ElementAt(0); -// c.ContentType = new PublishedContentType(22, "DontMatch", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); -// -// var dt = doc.ChildrenAsTable(Current.Services, "Child"); -// -// Assert.AreEqual(11, dt.Columns.Count); -// Assert.AreEqual(2, dt.Rows.Count); -// Assert.AreEqual("value7", dt.Rows[0]["Property 1"]); -// Assert.AreEqual("value8", dt.Rows[0]["Property 2"]); -// Assert.AreEqual("value9", dt.Rows[0]["Property 4"]); -// Assert.AreEqual("value10", dt.Rows[1]["Property 1"]); -// Assert.AreEqual("value11", dt.Rows[1]["Property 2"]); -// Assert.AreEqual("value12", dt.Rows[1]["Property 4"]); -// } + Assert.AreEqual(11, dt.Columns.Count); + Assert.AreEqual(3, dt.Rows.Count); + Assert.AreEqual("value4", dt.Rows[0]["Property 1"]); + Assert.AreEqual("value5", dt.Rows[0]["Property 2"]); + Assert.AreEqual("value6", dt.Rows[0]["Property 4"]); + Assert.AreEqual("value7", dt.Rows[1]["Property 1"]); + Assert.AreEqual("value8", dt.Rows[1]["Property 2"]); + Assert.AreEqual("value9", dt.Rows[1]["Property 4"]); + Assert.AreEqual("value10", dt.Rows[2]["Property 1"]); + Assert.AreEqual("value11", dt.Rows[2]["Property 2"]); + Assert.AreEqual("value12", dt.Rows[2]["Property 4"]); + } + + [Test] + public void To_DataTable_With_Filter() + { + var doc = GetContent(true, 1); + //change a doc type alias + var c = (TestPublishedContent)doc.Children.ElementAt(0); + c.ContentType = new PublishedContentType(22, "DontMatch", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); + + var dt = doc.ChildrenAsTable(Current.Services, "Child"); + + Assert.AreEqual(11, dt.Columns.Count); + Assert.AreEqual(2, dt.Rows.Count); + Assert.AreEqual("value7", dt.Rows[0]["Property 1"]); + Assert.AreEqual("value8", dt.Rows[0]["Property 2"]); + Assert.AreEqual("value9", dt.Rows[0]["Property 4"]); + Assert.AreEqual("value10", dt.Rows[1]["Property 1"]); + Assert.AreEqual("value11", dt.Rows[1]["Property 2"]); + Assert.AreEqual("value12", dt.Rows[1]["Property 4"]); + } [Test] public void To_DataTable_No_Rows() diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index 855d864cc4..603464e18b 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -326,18 +326,18 @@ namespace Umbraco.Tests.PublishedContent } } -// [Test] -// public void Descendants_Ordered_Properly() -// { -// var doc = GetNode(1046); -// -// var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; -// var exindex = 0; -// -// // must respect the XPath descendants-or-self axis! -// foreach (var d in doc.DescendantsOrSelf()) -// Assert.AreEqual(expected[exindex++], d.Id); -// } + [Test] + public void Descendants_Ordered_Properly() + { + var doc = GetNode(1046); + + var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; + var exindex = 0; + + // must respect the XPath descendants-or-self axis! + foreach (var d in doc.DescendantsOrSelf()) + Assert.AreEqual(expected[exindex++], d.Id); + } [Test] public void Get_Property_Value_Recursive() @@ -367,18 +367,18 @@ namespace Umbraco.Tests.PublishedContent Assert.AreEqual("
This is some content
", propVal3.ToString()); } -// [Test] -// public void Complex_Linq() -// { -// var doc = GetNode(1173); -// -// var result = doc.Ancestors().OrderBy(x => x.Level) -// .Single() -// .Descendants() -// .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); -// -// Assert.IsNotNull(result); -// } + [Test] + public void Complex_Linq() + { + var doc = GetNode(1173); + + var result = doc.Ancestors().OrderBy(x => x.Level) + .Single() + .Descendants() + .FirstOrDefault(x => x.Value("selectedNodes", defaultValue: "").Split(',').Contains("1173")); + + Assert.IsNotNull(result); + } [Test] public void Children_GroupBy_DocumentTypeAlias() @@ -437,36 +437,36 @@ namespace Umbraco.Tests.PublishedContent } -// [Test] -// public void FirstChild() -// { -// var doc = GetNode(1173); // has child nodes -// Assert.IsNotNull(doc.FirstChild()); -// Assert.IsNotNull(doc.FirstChild(x => true)); -// Assert.IsNotNull(doc.FirstChild()); -// -// doc = GetNode(1175); // does not have child nodes -// Assert.IsNull(doc.FirstChild()); -// Assert.IsNull(doc.FirstChild(x => true)); -// Assert.IsNull(doc.FirstChild()); -// } + [Test] + public void FirstChild() + { + var doc = GetNode(1173); // has child nodes + Assert.IsNotNull(doc.FirstChild()); + Assert.IsNotNull(doc.FirstChild(x => true)); + Assert.IsNotNull(doc.FirstChild()); -// [Test] -// public void FirstChildAsT() -// { -// var doc = GetNode(1046); // has child nodes -// -// var model = doc.FirstChild(x => true); // predicate -// -// Assert.IsNotNull(model); -// Assert.IsTrue(model.Id == 1173); -// Assert.IsInstanceOf(model); -// Assert.IsInstanceOf(model); -// -// doc = GetNode(1175); // does not have child nodes -// Assert.IsNull(doc.FirstChild()); -// Assert.IsNull(doc.FirstChild(x => true)); -// } + doc = GetNode(1175); // does not have child nodes + Assert.IsNull(doc.FirstChild()); + Assert.IsNull(doc.FirstChild(x => true)); + Assert.IsNull(doc.FirstChild()); + } + + [Test] + public void FirstChildAsT() + { + var doc = GetNode(1046); // has child nodes + + var model = doc.FirstChild(x => true); // predicate + + Assert.IsNotNull(model); + Assert.IsTrue(model.Id == 1173); + Assert.IsInstanceOf(model); + Assert.IsInstanceOf(model); + + doc = GetNode(1175); // does not have child nodes + Assert.IsNull(doc.FirstChild()); + Assert.IsNull(doc.FirstChild(x => true)); + } [Test] public void IsComposedOf() @@ -668,31 +668,31 @@ namespace Umbraco.Tests.PublishedContent } -// [Test] -// public void Descendants_Or_Self() -// { -// var doc = GetNode(1046); -// -// var result = doc.DescendantsOrSelf().ToArray(); -// -// Assert.IsNotNull(result); -// -// Assert.AreEqual(10, result.Count()); -// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); -// } -// -// [Test] -// public void Descendants() -// { -// var doc = GetNode(1046); -// -// var result = doc.Descendants().ToArray(); -// -// Assert.IsNotNull(result); -// -// Assert.AreEqual(9, result.Count()); -// Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); -// } + [Test] + public void Descendants_Or_Self() + { + var doc = GetNode(1046); + + var result = doc.DescendantsOrSelf().ToArray(); + + Assert.IsNotNull(result); + + Assert.AreEqual(10, result.Count()); + Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 })); + } + + [Test] + public void Descendants() + { + var doc = GetNode(1046); + + var result = doc.Descendants().ToArray(); + + Assert.IsNotNull(result); + + Assert.AreEqual(9, result.Count()); + Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); + } [Test] public void IsDescendant() diff --git a/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs b/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs index 4b56799fa4..134b709447 100644 --- a/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs +++ b/src/Umbraco.Tests/Testing/Objects/Accessors/TestVariationContextAccessor.cs @@ -8,10 +8,6 @@ namespace Umbraco.Tests.Testing.Objects.Accessors public class TestVariationContextAccessor : IVariationContextAccessor { /// - public VariationContext VariationContext - { - get; - set; - } = new VariationContext(); + public VariationContext VariationContext { get; set; } } } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs index 6f6a39144a..c418b7a525 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs @@ -154,9 +154,10 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public override string Name => _name; - public override PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); + public override PublishedCultureInfo GetCulture(string culture = null) => null; - public override IReadOnlyDictionary Cultures => throw new NotSupportedException(); + private static readonly Lazy> NoCultures = new Lazy>(() => new Dictionary()); + public override IReadOnlyDictionary Cultures => NoCultures.Value; public override string UrlSegment => _urlName; diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs index d8436c05b5..65c7dc7229 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs @@ -136,9 +136,10 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache } } - public override PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); + public override PublishedCultureInfo GetCulture(string culture = null) => null; - public override IReadOnlyDictionary Cultures => new Dictionary(); + private static readonly Lazy> NoCultures = new Lazy>(() => new Dictionary()); + public override IReadOnlyDictionary Cultures => NoCultures.Value; public override string WriterName { diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index 4efe6bc82b..0ada3d8c5b 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -267,19 +267,20 @@ namespace Umbraco.Web => content.Cultures.ContainsKey(culture); /// - /// Filter by the specific culture or invariant. If null is provided, the method uses the current culture instead. + /// Filters a sequence of to return invariant items, and items that are published for the specified culture. /// - /// The content. - /// The specific culture to filter for. If null is used the current culture is used. (Default is null) - /// These of the inputs that has the specified culture or are invariant. - internal static IEnumerable WhereHasCultureOrInvariant(this IEnumerable contents, string culture = null) + /// The content items. + /// The specific culture to filter for. If null is used the current culture is used. (Default is null). + internal static IEnumerable WhereIsInvariantOrHasCulture(this IEnumerable contents, string culture = null) { if (contents == null) throw new ArgumentNullException(nameof(contents)); - var actualCulture = culture ?? Current.VariationContextAccessor.VariationContext.Culture; + culture = culture ?? Current.VariationContextAccessor.VariationContext?.Culture ?? ""; - return contents.Where(x=>x.HasCulture(actualCulture) || !x.Cultures.Any()); + // either does not vary by culture, or has the specified culture + return contents.Where(x => !x.ContentType.VariesByCulture() || x.HasCulture(culture)); } + #endregion #region Search @@ -1036,7 +1037,6 @@ namespace Umbraco.Web #region Axes: children - /// /// Gets the children of the content. /// @@ -1050,7 +1050,16 @@ namespace Umbraco.Web public static IEnumerable Children(this IPublishedContent content, string culture = null) { if (content == null) throw new ArgumentNullException(nameof(content)); - return content.Children.WhereHasCultureOrInvariant(culture); + + // + return content.Children.Where(x => + { + if (!x.ContentType.VariesByCulture()) return true; // invariant = always ok + return x.HasCulture(culture); + return false; + }); + + return content.Children.WhereIsInvariantOrHasCulture(culture); } /// From 537b7e5ce9845f64a42dfc57479140ab1b0c438c Mon Sep 17 00:00:00 2001 From: mclausen Date: Thu, 17 Jan 2019 18:52:08 +0100 Subject: [PATCH 41/41] - Added PropertyType parameter to IValueConnector.FromArtifact --- src/Umbraco.Core/Deploy/IValueConnector.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Core/Deploy/IValueConnector.cs b/src/Umbraco.Core/Deploy/IValueConnector.cs index 81df59f1f1..7d9f43b5fe 100644 --- a/src/Umbraco.Core/Deploy/IValueConnector.cs +++ b/src/Umbraco.Core/Deploy/IValueConnector.cs @@ -29,8 +29,9 @@ namespace Umbraco.Core.Deploy /// Gets the content property value corresponding to a deploy property value. /// /// The deploy property value. + /// The value property type< /// The current content property value. /// The content property value. - object FromArtifact(string value, object currentValue); + object FromArtifact(string value, PropertyType propertyType, object currentValue); } }