diff --git a/.github/BUILD.md b/.github/BUILD.md index ad33872423..5f962a8911 100644 --- a/.github/BUILD.md +++ b/.github/BUILD.md @@ -39,7 +39,7 @@ To build Umbraco, fire up PowerShell and move to Umbraco's repository root (the build/build.ps1 -If you only see a build.bat-file, you're probably on the wrong branch. If you switch to the correct branch (dev-v8) the file will appear and you can build it. +If you only see a build.bat-file, you're probably on the wrong branch. If you switch to the correct branch (v8/contrib) the file will appear and you can build it. You might run into [Powershell quirks](#powershell-quirks). diff --git a/.gitignore b/.gitignore index ea2ddfbb68..15c9fb52f2 100644 --- a/.gitignore +++ b/.gitignore @@ -198,3 +198,5 @@ src/Umbraco.Tests.Integration/Views/ src/Umbraco.Tests/TEMP/ /src/Umbraco.Web.UI.NetCore/Umbraco/Data/* + +/src/Umbraco.Web.UI/config/umbracoSettings.config diff --git a/build/NuSpecs/tools/ReadmeUpgrade.txt b/build/NuSpecs/tools/ReadmeUpgrade.txt index 91d49d896c..fd1b2174e2 100644 --- a/build/NuSpecs/tools/ReadmeUpgrade.txt +++ b/build/NuSpecs/tools/ReadmeUpgrade.txt @@ -11,7 +11,7 @@ Y88 88Y 888 888 888 888 d88P 888 888 888 Y88b. Y88..88P Don't forget to build! -We've done our best to transform your configuration files but in case something is not quite right: we recommmend you look in source control for the previous version so you can find the original files before they were transformed. +We've done our best to transform your configuration files but in case something is not quite right: we recommend you look in source control for the previous version so you can find the original files before they were transformed. This NuGet package includes build targets that extend the creation of a deploy package, which is generated by Publishing from Visual Studio. The targets will only work once Publishing is configured, so if you don't use diff --git a/src/SolutionInfo.cs b/src/SolutionInfo.cs index 0a2e2c5c54..3a1f151388 100644 --- a/src/SolutionInfo.cs +++ b/src/SolutionInfo.cs @@ -2,7 +2,7 @@ using System.Resources; [assembly: AssemblyCompany("Umbraco")] -[assembly: AssemblyCopyright("Copyright © Umbraco 2020")] +[assembly: AssemblyCopyright("Copyright © Umbraco 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/src/Umbraco.Core/Collections/EventClearingObservableCollection.cs b/src/Umbraco.Core/Collections/EventClearingObservableCollection.cs new file mode 100644 index 0000000000..af25cc1b4a --- /dev/null +++ b/src/Umbraco.Core/Collections/EventClearingObservableCollection.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; + +namespace Umbraco.Core.Collections +{ + /// + /// Allows clearing all event handlers + /// + /// + public class EventClearingObservableCollection : ObservableCollection, INotifyCollectionChanged + { + public EventClearingObservableCollection() + { + } + + public EventClearingObservableCollection(List list) : base(list) + { + } + + public EventClearingObservableCollection(IEnumerable collection) : base(collection) + { + } + + // need to explicitly implement with event accessor syntax in order to override in order to to clear + // c# events are weird, they do not behave the same way as other c# things that are 'virtual', + // a good article is here: https://medium.com/@unicorn_dev/virtual-events-in-c-something-went-wrong-c6f6f5fbe252 + // and https://stackoverflow.com/questions/2268065/c-sharp-language-design-explicit-interface-implementation-of-an-event + private NotifyCollectionChangedEventHandler _changed; + event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged + { + add { _changed += value; } + remove { _changed -= value; } + } + + /// + /// Clears all event handlers for the event + /// + public void ClearCollectionChangedEvents() => _changed = null; + } +} diff --git a/src/Umbraco.Core/Collections/ObservableDictionary.cs b/src/Umbraco.Core/Collections/ObservableDictionary.cs index c6aedab377..fd9e469f07 100644 --- a/src/Umbraco.Core/Collections/ObservableDictionary.cs +++ b/src/Umbraco.Core/Collections/ObservableDictionary.cs @@ -1,11 +1,14 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; namespace Umbraco.Core.Collections { + /// /// An ObservableDictionary /// @@ -15,7 +18,7 @@ namespace Umbraco.Core.Collections /// /// The type of elements contained in the BindableCollection /// The type of the indexing key - public class ObservableDictionary : ObservableCollection, IReadOnlyDictionary, IDictionary + public class ObservableDictionary : ObservableCollection, IReadOnlyDictionary, IDictionary, INotifyCollectionChanged { protected Dictionary Indecies { get; } protected Func KeySelector { get; } @@ -74,6 +77,22 @@ namespace Umbraco.Core.Collections #endregion + // need to explicitly implement with event accessor syntax in order to override in order to to clear + // c# events are weird, they do not behave the same way as other c# things that are 'virtual', + // a good article is here: https://medium.com/@unicorn_dev/virtual-events-in-c-something-went-wrong-c6f6f5fbe252 + // and https://stackoverflow.com/questions/2268065/c-sharp-language-design-explicit-interface-implementation-of-an-event + private NotifyCollectionChangedEventHandler _changed; + event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged + { + add { _changed += value; } + remove { _changed -= value; } + } + + /// + /// Clears all event handlers + /// + public void ClearCollectionChangedEvents() => _changed = null; + public bool ContainsKey(TKey key) { return Indecies.ContainsKey(key); diff --git a/src/Umbraco.Core/Composing/ComponentComposer.cs b/src/Umbraco.Core/Composing/ComponentComposer.cs index 853d4f4502..fca0161d05 100644 --- a/src/Umbraco.Core/Composing/ComponentComposer.cs +++ b/src/Umbraco.Core/Composing/ComponentComposer.cs @@ -1,5 +1,4 @@ - -using Umbraco.Core.DependencyInjection; +using Umbraco.Core.DependencyInjection; namespace Umbraco.Core.Composing { diff --git a/src/Umbraco.Core/Configuration/IConfigManipulator.cs b/src/Umbraco.Core/Configuration/IConfigManipulator.cs index bc89b7bd1d..16c5a509f2 100644 --- a/src/Umbraco.Core/Configuration/IConfigManipulator.cs +++ b/src/Umbraco.Core/Configuration/IConfigManipulator.cs @@ -1,6 +1,4 @@ -using Umbraco.Core.IO; - -namespace Umbraco.Core.Configuration +namespace Umbraco.Core.Configuration { public interface IConfigManipulator { @@ -8,5 +6,6 @@ namespace Umbraco.Core.Configuration void SaveConnectionString(string connectionString, string providerName); void SaveConfigValue(string itemPath, object value); void SaveDisableRedirectUrlTracking(bool disable); + void SetGlobalId(string id); } } diff --git a/src/Umbraco.Core/Configuration/Models/ContentSettings.cs b/src/Umbraco.Core/Configuration/Models/ContentSettings.cs index 55881cd8db..01ffffa190 100644 --- a/src/Umbraco.Core/Configuration/Models/ContentSettings.cs +++ b/src/Umbraco.Core/Configuration/Models/ContentSettings.cs @@ -193,8 +193,15 @@ namespace Umbraco.Core.Configuration.Models public bool ShowDeprecatedPropertyEditors { get; set; } = false; /// - /// Gets or sets a value for the pate to the login screen background image. + /// Gets or sets a value for the path to the login screen background image. /// public string LoginBackgroundImage { get; set; } = "assets/img/login.jpg"; + + /// + /// Gets or sets a value for the path to the login screen logo image. + /// + public string LoginLogoImage { get; set; } = "assets/img/application/umbraco_logo_white.svg"; + + } } diff --git a/src/Umbraco.Core/Configuration/Models/GlobalSettings.cs b/src/Umbraco.Core/Configuration/Models/GlobalSettings.cs index eb13427d2b..c6e5d92794 100644 --- a/src/Umbraco.Core/Configuration/Models/GlobalSettings.cs +++ b/src/Umbraco.Core/Configuration/Models/GlobalSettings.cs @@ -94,10 +94,15 @@ namespace Umbraco.Core.Configuration.Models public bool InstallMissingDatabase { get; set; } = false; /// - /// Gets or sets a value indicating whether to install the database when it is empty. + /// Gets or sets a value indicating whether unattended installs are enabled. /// - public bool InstallEmptyDatabase { get; set; } = false; - + /// + /// By default, when a database connection string is configured and it is possible to connect to + /// the database, but the database is empty, the runtime enters the Install level. + /// If this option is set to true an unattended install will be performed and the runtime enters + /// the Run level. + /// + public bool InstallUnattended { get; set; } = false; /// /// Gets or sets a value indicating whether to disable the election for a single server. /// @@ -112,6 +117,7 @@ namespace Umbraco.Core.Configuration.Models /// Gets or sets a value for the main dom lock. /// public string MainDomLock { get; set; } = string.Empty; + public string Id { get; set; } = string.Empty; /// /// Gets or sets a value for the path to the no content view. diff --git a/src/Umbraco.Core/Constants-Configuration.cs b/src/Umbraco.Core/Constants-Configuration.cs index a60f29c39d..451ac5d438 100644 --- a/src/Umbraco.Core/Constants-Configuration.cs +++ b/src/Umbraco.Core/Constants-Configuration.cs @@ -16,10 +16,10 @@ public const string ConfigCorePrefix = ConfigPrefix + "Core:"; public const string ConfigCustomErrorsPrefix = ConfigPrefix + "CustomErrors:"; public const string ConfigGlobalPrefix = ConfigPrefix + "Global:"; + public const string ConfigGlobalId = ConfigGlobalPrefix + "Id"; public const string ConfigHostingPrefix = ConfigPrefix + "Hosting:"; public const string ConfigModelsBuilderPrefix = ConfigPrefix + "ModelsBuilder:"; public const string ConfigSecurityPrefix = ConfigPrefix + "Security:"; - public const string ConfigContentNotificationsEmail = ConfigContentNotificationsPrefix + "Email"; public const string ConfigContentMacroErrors = ConfigContentPrefix + "MacroErrors"; public const string ConfigGlobalUseHttps = ConfigGlobalPrefix + "UseHttps"; diff --git a/src/Umbraco.Core/Constants-SqlTemplates.cs b/src/Umbraco.Core/Constants-SqlTemplates.cs index 984bc495b0..5a78b62f5b 100644 --- a/src/Umbraco.Core/Constants-SqlTemplates.cs +++ b/src/Umbraco.Core/Constants-SqlTemplates.cs @@ -14,7 +14,16 @@ public const string GetParentNode = "Umbraco.Core.VersionableRepository.GetParentNode"; public const string GetReservedId = "Umbraco.Core.VersionableRepository.GetReservedId"; } + public static class RelationRepository + { + public const string DeleteByParentAll = "Umbraco.Core.RelationRepository.DeleteByParent"; + public const string DeleteByParentIn = "Umbraco.Core.RelationRepository.DeleteByParentIn"; + } + public static class DataTypeRepository + { + public const string EnsureUniqueNodeName = "Umbraco.Core.DataTypeDefinitionRepository.EnsureUniqueNodeName"; + } } } } diff --git a/src/Umbraco.Core/Constants-SvgSanitizer.cs b/src/Umbraco.Core/Constants-SvgSanitizer.cs index 447ea66668..c92b9f56c7 100644 --- a/src/Umbraco.Core/Constants-SvgSanitizer.cs +++ b/src/Umbraco.Core/Constants-SvgSanitizer.cs @@ -17,7 +17,7 @@ namespace Umbraco.Core /// /// Allowlist for SVG tabs. /// - public static readonly IList Tags = new [] { "a", "altGlyph", "altGlyphDef", "altGlyphItem", "animate", "animateColor", "animateMotion", "animateTransform", "circle", "clipPath", "color-profile", "cursor", "defs", "desc", "discard", "ellipse", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "filter", "font", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignObject", "g", "glyph", "glyphRef", "hatch", "hatchpath", "hkern", "image", "line", "linearGradient", "marker", "mask", "mesh", "meshgradient", "meshpatch", "meshrow", "metadata", "missing-glyph", "mpath", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "set", "solidcolor", "stop", "style", "svg", "switch", "symbol", "text", "textPath", "title", "tref", "tspan", "unknown", "use", "view", "vkern" }; + public static readonly IList Tags = new [] { "a", "altGlyph", "altGlyphDef", "altGlyphItem", "animate", "animateColor", "animateMotion", "animateTransform", "circle", "clipPath", "color-profile", "cursor", "defs", "desc", "discard", "ellipse", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "filter", "font", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignObject", "g", "glyph", "glyphRef", "hatch", "hatchpath", "hkern", "image", "line", "linearGradient", "marker", "mask", "mesh", "meshgradient", "meshpatch", "meshrow", "metadata", "missing-glyph", "mpath", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "set", "solidcolor", "stop", "svg", "switch", "symbol", "text", "textPath", "title", "tref", "tspan", "unknown", "use", "view", "vkern" }; } } } diff --git a/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs b/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs index 260ec5487f..54e5982a58 100644 --- a/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs +++ b/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs @@ -114,9 +114,7 @@ namespace Umbraco.Core.DependencyInjection // Adds no-op registrations as many core services require these dependencies but these // dependencies cannot be fulfilled in the Core project Services.AddUnique(); - Services.AddUnique(); Services.AddUnique(); - Services.AddUnique(); Services.AddUnique(); Services.AddUnique(); diff --git a/src/Umbraco.Core/Exceptions/UnattendedInstallException.cs b/src/Umbraco.Core/Exceptions/UnattendedInstallException.cs new file mode 100644 index 0000000000..6f672d17cd --- /dev/null +++ b/src/Umbraco.Core/Exceptions/UnattendedInstallException.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.Serialization; + +namespace Umbraco.Core.Exceptions +{ + /// + /// An exception that is thrown if an unattended installation occurs. + /// + [Serializable] + public class UnattendedInstallException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public UnattendedInstallException() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public UnattendedInstallException(string message) : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message + /// and a reference to the inner exception which is the cause of this exception. + /// + /// The message that describes the error. + /// The inner exception, or null. + public UnattendedInstallException(string message, Exception innerException) : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected UnattendedInstallException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } +} diff --git a/src/Umbraco.Core/Hosting/IUmbracoApplicationLifetime.cs b/src/Umbraco.Core/Hosting/IUmbracoApplicationLifetime.cs index a4368a2634..50b7727ecf 100644 --- a/src/Umbraco.Core/Hosting/IUmbracoApplicationLifetime.cs +++ b/src/Umbraco.Core/Hosting/IUmbracoApplicationLifetime.cs @@ -1,5 +1,3 @@ -using System; - namespace Umbraco.Core.Hosting { public interface IUmbracoApplicationLifetime @@ -13,8 +11,5 @@ namespace Umbraco.Core.Hosting /// Terminates the current application. The application restarts the next time a request is received for it. /// void Restart(); - - // TODO: Should be killed and replaced with UmbracoApplicationStarting notifications - event EventHandler ApplicationInit; } } diff --git a/src/Umbraco.Core/Hosting/IUmbracoApplicationLifetimeManager.cs b/src/Umbraco.Core/Hosting/IUmbracoApplicationLifetimeManager.cs deleted file mode 100644 index 778edc24dd..0000000000 --- a/src/Umbraco.Core/Hosting/IUmbracoApplicationLifetimeManager.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Umbraco.Core.Hosting -{ - // TODO: Should be killed and replaced with UmbracoApplicationStarting notifications - public interface IUmbracoApplicationLifetimeManager - { - void InvokeApplicationInit(); - } -} diff --git a/src/Umbraco.Core/Hosting/NoopUmbracoApplicationLifetimeManager.cs b/src/Umbraco.Core/Hosting/NoopUmbracoApplicationLifetimeManager.cs deleted file mode 100644 index 7833fd1224..0000000000 --- a/src/Umbraco.Core/Hosting/NoopUmbracoApplicationLifetimeManager.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Hosting -{ - internal class NoopUmbracoApplicationLifetimeManager : IUmbracoApplicationLifetimeManager - { - public void InvokeApplicationInit() { } - } -} diff --git a/src/Umbraco.Core/IO/SystemFiles.cs b/src/Umbraco.Core/IO/SystemFiles.cs index c8151d076c..92e9156f2f 100644 --- a/src/Umbraco.Core/IO/SystemFiles.cs +++ b/src/Umbraco.Core/IO/SystemFiles.cs @@ -9,8 +9,6 @@ namespace Umbraco.Core.IO { public static string TinyMceConfig => Constants.SystemDirectories.Config + "/tinyMceConfig.config"; - public static string TelemetricsIdentifier => Constants.SystemDirectories.Data + "/telemetrics-id.umb"; - // TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache public static string GetContentCacheXml(IHostingEnvironment hostingEnvironment) { diff --git a/src/Umbraco.Core/Install/InstallSteps/TelemetryIdentifierStep.cs b/src/Umbraco.Core/Install/InstallSteps/TelemetryIdentifierStep.cs new file mode 100644 index 0000000000..01d8e428c7 --- /dev/null +++ b/src/Umbraco.Core/Install/InstallSteps/TelemetryIdentifierStep.cs @@ -0,0 +1,54 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Umbraco.Web.Install.Models; + +namespace Umbraco.Web.Install.InstallSteps +{ + [InstallSetupStep(InstallationType.NewInstall | InstallationType.Upgrade, + "TelemetryIdConfiguration", 0, "", + PerformsAppRestart = false)] + public class TelemetryIdentifierStep : InstallSetupStep + { + private readonly ILogger _logger; + private readonly IOptions _globalSettings; + private readonly IConfigManipulator _configManipulator; + + public TelemetryIdentifierStep(ILogger logger, IOptions globalSettings, IConfigManipulator configManipulator) + { + _logger = logger; + _globalSettings = globalSettings; + _configManipulator = configManipulator; + } + + public override Task ExecuteAsync(object model) + { + // Generate GUID + var telemetrySiteIdentifier = Guid.NewGuid(); + + try + { + _configManipulator.SetGlobalId(telemetrySiteIdentifier.ToString()); + } + catch (Exception ex) + { + _logger.LogError(ex, "Couldn't update config files with a telemetry site identifier"); + } + + return Task.FromResult(null); + } + + public override bool RequiresExecution(object model) + { + // Verify that Json value is not empty string + // Try & get a value stored in appSettings.json + var backofficeIdentifierRaw = _globalSettings.Value.Id; + + // No need to add Id again if already found + return string.IsNullOrEmpty(backofficeIdentifierRaw); + } + } +} diff --git a/src/Umbraco.Core/Models/Content.cs b/src/Umbraco.Core/Models/Content.cs index c5930bf998..04f49e704e 100644 --- a/src/Umbraco.Core/Models/Content.cs +++ b/src/Umbraco.Core/Models/Content.cs @@ -98,10 +98,15 @@ namespace Umbraco.Core.Models set { if (_schedule != null) - _schedule.CollectionChanged -= ScheduleCollectionChanged; + { + _schedule.ClearCollectionChangedEvents(); + } + SetPropertyValueAndDetectChanges(value, ref _schedule, nameof(ContentSchedule)); if (_schedule != null) + { _schedule.CollectionChanged += ScheduleCollectionChanged; + } } } @@ -223,10 +228,16 @@ namespace Umbraco.Core.Models } set { - if (_publishInfos != null) _publishInfos.CollectionChanged -= PublishNamesCollectionChanged; + if (_publishInfos != null) + { + _publishInfos.ClearCollectionChangedEvents(); + } + _publishInfos = value; if (_publishInfos != null) + { _publishInfos.CollectionChanged += PublishNamesCollectionChanged; + } } } @@ -321,7 +332,7 @@ namespace Umbraco.Core.Models else Properties.EnsurePropertyTypes(contentType.CompositionPropertyTypes); - Properties.CollectionChanged -= PropertiesChanged; // be sure not to double add + Properties.ClearCollectionChangedEvents(); // be sure not to double add Properties.CollectionChanged += PropertiesChanged; } @@ -438,7 +449,7 @@ namespace Umbraco.Core.Models //if culture infos exist then deal with event bindings if (clonedContent._publishInfos != null) { - clonedContent._publishInfos.CollectionChanged -= PublishNamesCollectionChanged; //clear this event handler if any + clonedContent._publishInfos.ClearCollectionChangedEvents(); //clear this event handler if any clonedContent._publishInfos = (ContentCultureInfosCollection)_publishInfos.DeepClone(); //manually deep clone clonedContent._publishInfos.CollectionChanged += clonedContent.PublishNamesCollectionChanged; //re-assign correct event handler } @@ -446,7 +457,7 @@ namespace Umbraco.Core.Models //if properties exist then deal with event bindings if (clonedContent._schedule != null) { - clonedContent._schedule.CollectionChanged -= ScheduleCollectionChanged; //clear this event handler if any + clonedContent._schedule.ClearCollectionChangedEvents(); //clear this event handler if any clonedContent._schedule = (ContentScheduleCollection)_schedule.DeepClone(); //manually deep clone clonedContent._schedule.CollectionChanged += clonedContent.ScheduleCollectionChanged; //re-assign correct event handler } diff --git a/src/Umbraco.Core/Models/ContentBase.cs b/src/Umbraco.Core/Models/ContentBase.cs index 2b522b2931..1e71da34c4 100644 --- a/src/Umbraco.Core/Models/ContentBase.cs +++ b/src/Umbraco.Core/Models/ContentBase.cs @@ -138,7 +138,11 @@ namespace Umbraco.Core.Models get => _properties; set { - if (_properties != null) _properties.CollectionChanged -= PropertiesChanged; + if (_properties != null) + { + _properties.ClearCollectionChangedEvents(); + } + _properties = value; _properties.CollectionChanged += PropertiesChanged; } @@ -173,10 +177,15 @@ namespace Umbraco.Core.Models } set { - if (_cultureInfos != null) _cultureInfos.CollectionChanged -= CultureInfosCollectionChanged; + if (_cultureInfos != null) + { + _cultureInfos.ClearCollectionChangedEvents(); + } _cultureInfos = value; if (_cultureInfos != null) + { _cultureInfos.CollectionChanged += CultureInfosCollectionChanged; + } } } @@ -479,7 +488,7 @@ namespace Umbraco.Core.Models //if culture infos exist then deal with event bindings if (clonedContent._cultureInfos != null) { - clonedContent._cultureInfos.CollectionChanged -= CultureInfosCollectionChanged; //clear this event handler if any + clonedContent._cultureInfos.ClearCollectionChangedEvents(); //clear this event handler if any clonedContent._cultureInfos = (ContentCultureInfosCollection)_cultureInfos.DeepClone(); //manually deep clone clonedContent._cultureInfos.CollectionChanged += clonedContent.CultureInfosCollectionChanged; //re-assign correct event handler } @@ -487,7 +496,7 @@ namespace Umbraco.Core.Models //if properties exist then deal with event bindings if (clonedContent._properties != null) { - clonedContent._properties.CollectionChanged -= PropertiesChanged; //clear this event handler if any + clonedContent._properties.ClearCollectionChangedEvents(); //clear this event handler if any clonedContent._properties = (IPropertyCollection)_properties.DeepClone(); //manually deep clone clonedContent._properties.CollectionChanged += clonedContent.PropertiesChanged; //re-assign correct event handler } diff --git a/src/Umbraco.Core/Models/ContentScheduleCollection.cs b/src/Umbraco.Core/Models/ContentScheduleCollection.cs index 6c7dd79312..0ebcc0fe4b 100644 --- a/src/Umbraco.Core/Models/ContentScheduleCollection.cs +++ b/src/Umbraco.Core/Models/ContentScheduleCollection.cs @@ -14,6 +14,11 @@ namespace Umbraco.Core.Models public event NotifyCollectionChangedEventHandler CollectionChanged; + /// + /// Clears all event handlers + /// + public void ClearCollectionChangedEvents() => CollectionChanged = null; + private void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { CollectionChanged?.Invoke(this, args); diff --git a/src/Umbraco.Core/Models/ContentTypeBase.cs b/src/Umbraco.Core/Models/ContentTypeBase.cs index 9823bb8a1d..cb1531d739 100644 --- a/src/Umbraco.Core/Models/ContentTypeBase.cs +++ b/src/Umbraco.Core/Models/ContentTypeBase.cs @@ -266,7 +266,10 @@ namespace Umbraco.Core.Models set { if (_noGroupPropertyTypes != null) - _noGroupPropertyTypes.CollectionChanged -= PropertyTypesChanged; + { + _noGroupPropertyTypes.ClearCollectionChangedEvents(); + } + _noGroupPropertyTypes = new PropertyTypeCollection(SupportsPublishing, value); _noGroupPropertyTypes.CollectionChanged += PropertyTypesChanged; PropertyTypesChanged(_noGroupPropertyTypes, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); @@ -484,14 +487,14 @@ namespace Umbraco.Core.Models // its ignored from the auto-clone process because its return values are unions, not raw and // we end up with duplicates, see: http://issues.umbraco.org/issue/U4-4842 - clonedEntity._noGroupPropertyTypes.CollectionChanged -= PropertyTypesChanged; //clear this event handler if any + clonedEntity._noGroupPropertyTypes.ClearCollectionChangedEvents(); //clear this event handler if any clonedEntity._noGroupPropertyTypes = (PropertyTypeCollection) _noGroupPropertyTypes.DeepClone(); //manually deep clone clonedEntity._noGroupPropertyTypes.CollectionChanged += clonedEntity.PropertyTypesChanged; //re-assign correct event handler } if (clonedEntity._propertyGroups != null) { - clonedEntity._propertyGroups.CollectionChanged -= PropertyGroupsChanged; //clear this event handler if any + clonedEntity._propertyGroups.ClearCollectionChangedEvents(); //clear this event handler if any clonedEntity._propertyGroups = (PropertyGroupCollection) _propertyGroups.DeepClone(); //manually deep clone clonedEntity._propertyGroups.CollectionChanged += clonedEntity.PropertyGroupsChanged; //re-assign correct event handler } diff --git a/src/Umbraco.Core/Models/IPropertyCollection.cs b/src/Umbraco.Core/Models/IPropertyCollection.cs index c0a9622e6e..c947a5e12d 100644 --- a/src/Umbraco.Core/Models/IPropertyCollection.cs +++ b/src/Umbraco.Core/Models/IPropertyCollection.cs @@ -34,5 +34,6 @@ namespace Umbraco.Core.Models void Add(IProperty property); int Count { get; } + void ClearCollectionChangedEvents(); } } diff --git a/src/Umbraco.Core/Models/Media.cs b/src/Umbraco.Core/Models/Media.cs index 452bb615d1..c4e841f27b 100644 --- a/src/Umbraco.Core/Models/Media.cs +++ b/src/Umbraco.Core/Models/Media.cs @@ -77,7 +77,7 @@ namespace Umbraco.Core.Models else Properties.EnsurePropertyTypes(contentType.CompositionPropertyTypes); - Properties.CollectionChanged -= PropertiesChanged; // be sure not to double add + Properties.ClearCollectionChangedEvents(); // be sure not to double add Properties.CollectionChanged += PropertiesChanged; } } diff --git a/src/Umbraco.Core/Models/PropertyCollection.cs b/src/Umbraco.Core/Models/PropertyCollection.cs index e206a3b38c..21b13d58da 100644 --- a/src/Umbraco.Core/Models/PropertyCollection.cs +++ b/src/Umbraco.Core/Models/PropertyCollection.cs @@ -155,6 +155,8 @@ namespace Umbraco.Core.Models /// public event NotifyCollectionChangedEventHandler CollectionChanged; + public void ClearCollectionChangedEvents() => CollectionChanged = null; + protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { CollectionChanged?.Invoke(this, args); diff --git a/src/Umbraco.Core/Models/PropertyGroup.cs b/src/Umbraco.Core/Models/PropertyGroup.cs index 2e6da5d837..022fb6ed03 100644 --- a/src/Umbraco.Core/Models/PropertyGroup.cs +++ b/src/Umbraco.Core/Models/PropertyGroup.cs @@ -66,7 +66,10 @@ namespace Umbraco.Core.Models set { if (_propertyTypes != null) - _propertyTypes.CollectionChanged -= PropertyTypesChanged; + { + _propertyTypes.ClearCollectionChangedEvents(); + } + _propertyTypes = value; // since we're adding this collection to this group, @@ -100,7 +103,7 @@ namespace Umbraco.Core.Models if (clonedEntity._propertyTypes != null) { - clonedEntity._propertyTypes.CollectionChanged -= PropertyTypesChanged; //clear this event handler if any + clonedEntity._propertyTypes.ClearCollectionChangedEvents(); //clear this event handler if any clonedEntity._propertyTypes = (PropertyTypeCollection) _propertyTypes.DeepClone(); //manually deep clone clonedEntity._propertyTypes.CollectionChanged += clonedEntity.PropertyTypesChanged; //re-assign correct event handler } diff --git a/src/Umbraco.Core/Models/PropertyGroupCollection.cs b/src/Umbraco.Core/Models/PropertyGroupCollection.cs index f5b3012b1a..11f4e470ee 100644 --- a/src/Umbraco.Core/Models/PropertyGroupCollection.cs +++ b/src/Umbraco.Core/Models/PropertyGroupCollection.cs @@ -160,6 +160,11 @@ namespace Umbraco.Core.Models public event NotifyCollectionChangedEventHandler CollectionChanged; + /// + /// Clears all event handlers + /// + public void ClearCollectionChangedEvents() => CollectionChanged = null; + protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { CollectionChanged?.Invoke(this, args); diff --git a/src/Umbraco.Core/Models/PropertyTypeCollection.cs b/src/Umbraco.Core/Models/PropertyTypeCollection.cs index bca7e88e03..132c80e7d1 100644 --- a/src/Umbraco.Core/Models/PropertyTypeCollection.cs +++ b/src/Umbraco.Core/Models/PropertyTypeCollection.cs @@ -165,7 +165,11 @@ namespace Umbraco.Core.Models } public event NotifyCollectionChangedEventHandler CollectionChanged; - + + /// + /// Clears all event handlers + /// + public void ClearCollectionChangedEvents() => CollectionChanged = null; protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { CollectionChanged?.Invoke(this, args); diff --git a/src/Umbraco.Core/Models/PublicAccessEntry.cs b/src/Umbraco.Core/Models/PublicAccessEntry.cs index b7f9caed44..e48e3bd711 100644 --- a/src/Umbraco.Core/Models/PublicAccessEntry.cs +++ b/src/Umbraco.Core/Models/PublicAccessEntry.cs @@ -4,6 +4,7 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Runtime.Serialization; +using Umbraco.Core.Collections; using Umbraco.Core.Models.Entities; namespace Umbraco.Core.Models @@ -12,7 +13,7 @@ namespace Umbraco.Core.Models [DataContract(IsReference = true)] public class PublicAccessEntry : EntityBase { - private readonly ObservableCollection _ruleCollection; + private readonly EventClearingObservableCollection _ruleCollection; private int _protectedNodeId; private int _noAccessNodeId; private int _loginNodeId; @@ -28,7 +29,7 @@ namespace Umbraco.Core.Models NoAccessNodeId = noAccessNode.Id; _protectedNodeId = protectedNode.Id; - _ruleCollection = new ObservableCollection(ruleCollection); + _ruleCollection = new EventClearingObservableCollection(ruleCollection); _ruleCollection.CollectionChanged += _ruleCollection_CollectionChanged; foreach (var rule in _ruleCollection) @@ -44,7 +45,7 @@ namespace Umbraco.Core.Models NoAccessNodeId = noAccessNodeId; _protectedNodeId = protectedNodeId; - _ruleCollection = new ObservableCollection(ruleCollection); + _ruleCollection = new EventClearingObservableCollection(ruleCollection); _ruleCollection.CollectionChanged += _ruleCollection_CollectionChanged; foreach (var rule in _ruleCollection) @@ -148,7 +149,7 @@ namespace Umbraco.Core.Models if (cloneEntity._ruleCollection != null) { - cloneEntity._ruleCollection.CollectionChanged -= _ruleCollection_CollectionChanged; //clear this event handler if any + cloneEntity._ruleCollection.ClearCollectionChangedEvents(); //clear this event handler if any cloneEntity._ruleCollection.CollectionChanged += cloneEntity._ruleCollection_CollectionChanged; //re-assign correct event handler } } diff --git a/src/Umbraco.Core/Models/Range.cs b/src/Umbraco.Core/Models/Range.cs index 83afa11658..108d564665 100644 --- a/src/Umbraco.Core/Models/Range.cs +++ b/src/Umbraco.Core/Models/Range.cs @@ -1,52 +1,130 @@ using System; +using System.Globalization; + namespace Umbraco.Core.Models { - // The Range class. Adapted from http://stackoverflow.com/questions/5343006/is-there-a-c-sharp-type-for-representing-an-integer-range - /// Generic parameter. - public class Range where T : IComparable + /// + /// Represents a range with a minimum and maximum value. + /// + /// The type of the minimum and maximum values. + /// + public class Range : IEquatable> + where T : IComparable { - /// Minimum value of the range. + /// + /// Gets or sets the minimum value. + /// + /// + /// The minimum value. + /// public T Minimum { get; set; } - /// Maximum value of the range. + /// + /// Gets or sets the maximum value. + /// + /// + /// The maximum value. + /// public T Maximum { get; set; } - /// Presents the Range in readable format. - /// String representation of the Range - public override string ToString() - { - return string.Format("{0},{1}", this.Minimum, this.Maximum); - } + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() => this.ToString("{0},{1}", CultureInfo.InvariantCulture); - /// Determines if the range is valid. - /// True if range is valid, else false - public bool IsValid() - { - return this.Minimum.CompareTo(this.Maximum) <= 0; - } + /// + /// Returns a that represents this instance. + /// + /// A composite format string for a single value (minimum and maximum are equal). Use {0} for the minimum and {1} for the maximum value. + /// A composite format string for the range values. Use {0} for the minimum and {1} for the maximum value. + /// An object that supplies culture-specific formatting information. + /// + /// A that represents this instance. + /// + public string ToString(string format, string formatRange, IFormatProvider provider = null) => this.ToString(this.Minimum.CompareTo(this.Maximum) == 0 ? format : formatRange, provider); - /// Determines if the provided value is inside the range. - /// The value to test - /// True if the value is inside Range, else false - public bool ContainsValue(T value) - { - return (this.Minimum.CompareTo(value) <= 0) && (value.CompareTo(this.Maximum) <= 0); - } + /// + /// Returns a that represents this instance. + /// + /// A composite format string for the range values. Use {0} for the minimum and {1} for the maximum value. + /// An object that supplies culture-specific formatting information. + /// + /// A that represents this instance. + /// + public string ToString(string format, IFormatProvider provider = null) => string.Format(provider, format, this.Minimum, this.Maximum); - /// Determines if this Range is inside the bounds of another range. - /// The parent range to test on - /// True if range is inclusive, else false - public bool IsInsideRange(Range range) - { - return this.IsValid() && range.IsValid() && range.ContainsValue(this.Minimum) && range.ContainsValue(this.Maximum); - } + /// + /// Determines whether this range is valid (the minimum value is lower than or equal to the maximum value). + /// + /// + /// true if this range is valid; otherwise, false. + /// + public bool IsValid() => this.Minimum.CompareTo(this.Maximum) <= 0; - /// Determines if another range is inside the bounds of this range. - /// The child range to test - /// True if range is inside, else false - public bool ContainsRange(Range range) - { - return this.IsValid() && range.IsValid() && this.ContainsValue(range.Minimum) && this.ContainsValue(range.Maximum); - } + /// + /// Determines whether this range contains the specified value. + /// + /// The value. + /// + /// true if this range contains the specified value; otherwise, false. + /// + public bool ContainsValue(T value) => this.Minimum.CompareTo(value) <= 0 && value.CompareTo(this.Maximum) <= 0; + + /// + /// Determines whether this range is inside the specified range. + /// + /// The range. + /// + /// true if this range is inside the specified range; otherwise, false. + /// + public bool IsInsideRange(Range range) => this.IsValid() && range.IsValid() && range.ContainsValue(this.Minimum) && range.ContainsValue(this.Maximum); + + /// + /// Determines whether this range contains the specified range. + /// + /// The range. + /// + /// true if this range contains the specified range; otherwise, false. + /// + public bool ContainsRange(Range range) => this.IsValid() && range.IsValid() && this.ContainsValue(range.Minimum) && this.ContainsValue(range.Maximum); + + /// + /// Determines whether the specified , is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public override bool Equals(object obj) => obj is Range other && this.Equals(other); + + /// + /// Indicates whether the current object is equal to another object of the same type. + /// + /// An object to compare with this object. + /// + /// if the current object is equal to the parameter; otherwise, . + /// + public bool Equals(Range other) => other != null && this.Equals(other.Minimum, other.Maximum); + + /// + /// Determines whether the specified and values are equal to this instance values. + /// + /// The minimum value. + /// The maximum value. + /// + /// true if the specified and values are equal to this instance values; otherwise, false. + /// + public bool Equals(T minimum, T maximum) => this.Minimum.CompareTo(minimum) == 0 && this.Maximum.CompareTo(maximum) == 0; + + /// + /// Returns a hash code for this instance. + /// + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// + public override int GetHashCode() => (this.Minimum, this.Maximum).GetHashCode(); } } diff --git a/src/Umbraco.Core/Models/SimpleValidationModel.cs b/src/Umbraco.Core/Models/SimpleValidationModel.cs new file mode 100644 index 0000000000..cca44613fb --- /dev/null +++ b/src/Umbraco.Core/Models/SimpleValidationModel.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace Umbraco.Core.Models +{ + public class SimpleValidationModel + { + public SimpleValidationModel(IDictionary modelState, string message = "The request is invalid.") + { + Message = message; + ModelState = modelState; + } + + public string Message { get; } + public IDictionary ModelState { get; } + } +} diff --git a/src/Umbraco.Core/Routing/PublishedRequest.cs b/src/Umbraco.Core/Routing/PublishedRequest.cs index 0c129bf279..7a3d44149d 100644 --- a/src/Umbraco.Core/Routing/PublishedRequest.cs +++ b/src/Umbraco.Core/Routing/PublishedRequest.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; @@ -13,10 +11,10 @@ namespace Umbraco.Web.Routing /// /// Initializes a new instance of the class. /// - public PublishedRequest(Uri uri, string absPathDecoded, IPublishedContent publishedContent, bool isInternalRedirect, ITemplate template, DomainAndUri domain, string culture, string redirectUrl, int? responseStatusCode, IReadOnlyList cacheExtensions, IReadOnlyDictionary headers, bool setNoCacheHeader, bool ignorePublishedContentCollisions) + public PublishedRequest(Uri uri, string absolutePathDecoded, IPublishedContent publishedContent, bool isInternalRedirect, ITemplate template, DomainAndUri domain, string culture, string redirectUrl, int? responseStatusCode, IReadOnlyList cacheExtensions, IReadOnlyDictionary headers, bool setNoCacheHeader, bool ignorePublishedContentCollisions) { Uri = uri ?? throw new ArgumentNullException(nameof(uri)); - AbsolutePathDecoded = absPathDecoded ?? throw new ArgumentNullException(nameof(absPathDecoded)); + AbsolutePathDecoded = absolutePathDecoded ?? throw new ArgumentNullException(nameof(absolutePathDecoded)); PublishedContent = publishedContent; IsInternalRedirect = isInternalRedirect; Template = template; diff --git a/src/Umbraco.Core/Routing/UmbracoRequestPaths.cs b/src/Umbraco.Core/Routing/UmbracoRequestPaths.cs index e670930691..8e8541cb2c 100644 --- a/src/Umbraco.Core/Routing/UmbracoRequestPaths.cs +++ b/src/Umbraco.Core/Routing/UmbracoRequestPaths.cs @@ -22,9 +22,7 @@ namespace Umbraco.Core.Routing private readonly string _apiMvcPath; private readonly string _installPath; private readonly string _appPath; - private readonly List _aspLegacyJsExt = new List { ".asmx/", ".aspx/", ".ashx/", ".axd/", ".svc/" }; - private readonly List _aspLegacyExt = new List { ".asmx", ".aspx", ".ashx", ".axd", ".svc" }; - + private readonly List _defaultUmbPaths; /// /// Initializes a new instance of the class. @@ -38,7 +36,7 @@ namespace Umbraco.Core.Routing .EnsureStartsWith('/').TrimStart(_appPath.EnsureStartsWith('/')).EnsureStartsWith('/'); _mvcArea = globalSettings.Value.GetUmbracoMvcArea(hostingEnvironment); - + _defaultUmbPaths = new List { "/" + _mvcArea, "/" + _mvcArea + "/" }; _backOfficeMvcPath = "/" + _mvcArea + "/BackOffice/"; _previewMvcPath = "/" + _mvcArea + "/Preview/"; _surfaceMvcPath = "/" + _mvcArea + "/Surface/"; @@ -50,22 +48,25 @@ namespace Umbraco.Core.Routing /// Checks if the current uri is a back office request /// /// + /// /// There are some special routes we need to check to properly determine this: - /// - /// If any route has an extension in the path like .aspx = back office - /// + /// + /// /// These are def back office: /// /Umbraco/BackOffice = back office /// /Umbraco/Preview = back office - /// If it's not any of the above, and there's no extension then we cannot determine if it's back office or front-end + /// + /// + /// If it's not any of the above then we cannot determine if it's back office or front-end /// so we can only assume that it is not back office. This will occur if people use an UmbracoApiController for the backoffice /// but do not inherit from UmbracoAuthorizedApiController and do not use [IsBackOffice] attribute. - /// + /// + /// /// These are def front-end: /// /Umbraco/Surface = front-end /// /Umbraco/Api = front-end /// But if we've got this far we'll just have to assume it's front-end anyways. - /// + /// /// public bool IsBackOfficeRequest(string absPath) { @@ -82,24 +83,7 @@ namespace Umbraco.Core.Routing } // if its the normal /umbraco path - if (urlPath.InvariantEquals("/" + _mvcArea) - || urlPath.InvariantEquals("/" + _mvcArea + "/")) - { - return true; - } - - // check for a file extension - var extension = Path.GetExtension(absPath); - - // has an extension, def back office - if (extension.IsNullOrWhiteSpace() == false) - { - return true; - } - - // check for special case asp.net calls like: - // /umbraco/webservices/legacyAjaxCalls.asmx/js which will return a null file extension but are still considered requests with an extension - if (_aspLegacyJsExt.Any(x => urlPath.InvariantContains(x))) + if (_defaultUmbPaths.Any(x => urlPath.InvariantEquals(x))) { return true; } @@ -143,12 +127,7 @@ namespace Umbraco.Core.Routing public bool IsClientSideRequest(string absPath) { var ext = Path.GetExtension(absPath); - if (ext.IsNullOrWhiteSpace()) - { - return false; - } - - return _aspLegacyExt.Any(ext.InvariantEquals) == false; + return !ext.IsNullOrWhiteSpace(); } } } diff --git a/src/Umbraco.Core/Scheduling/RecurringTaskBase.cs b/src/Umbraco.Core/Scheduling/RecurringTaskBase.cs index 58df54a07e..4544711946 100644 --- a/src/Umbraco.Core/Scheduling/RecurringTaskBase.cs +++ b/src/Umbraco.Core/Scheduling/RecurringTaskBase.cs @@ -15,9 +15,29 @@ namespace Umbraco.Web.Scheduling public abstract class RecurringTaskBase : LatchedBackgroundTaskBase { private readonly IBackgroundTaskRunner _runner; - private readonly int _periodMilliseconds; + private readonly long _periodMilliseconds; private readonly Timer _timer; + /// + /// Initializes a new instance of the class. + /// + /// The task runner. + /// The delay. + /// The period. + /// The task will repeat itself periodically. Use this constructor to create a new task. + protected RecurringTaskBase(IBackgroundTaskRunner runner, long delayMilliseconds, long periodMilliseconds) + { + _runner = runner; + _periodMilliseconds = periodMilliseconds; + + // note + // must use the single-parameter constructor on Timer to avoid it from being GC'd + // read http://stackoverflow.com/questions/4962172/why-does-a-system-timers-timer-survive-gc-but-not-system-threading-timer + + _timer = new Timer(_ => Release()); + _timer.Change(delayMilliseconds, 0); + } + /// /// Initializes a new instance of the class. /// diff --git a/src/Umbraco.Core/Services/ContentTypeServiceExtensions.cs b/src/Umbraco.Core/Services/ContentTypeServiceExtensions.cs index 8d21c21276..d03820b53e 100644 --- a/src/Umbraco.Core/Services/ContentTypeServiceExtensions.cs +++ b/src/Umbraco.Core/Services/ContentTypeServiceExtensions.cs @@ -37,7 +37,7 @@ namespace Umbraco.Core.Services /// This is required because in the case of creating/modifying a content type because new property types being added to it are not yet persisted so cannot /// be looked up via the db, they need to be passed in. /// - /// Wether the composite content types should be applicable for an element type + /// Whether the composite content types should be applicable for an element type /// public static ContentTypeAvailableCompositionsResults GetAvailableCompositeContentTypes(this IContentTypeService ctService, IContentTypeComposition source, diff --git a/src/Umbraco.Core/Services/IRuntimeState.cs b/src/Umbraco.Core/Services/IRuntimeState.cs index ef826014be..2e5f8630d4 100644 --- a/src/Umbraco.Core/Services/IRuntimeState.cs +++ b/src/Umbraco.Core/Services/IRuntimeState.cs @@ -57,5 +57,6 @@ namespace Umbraco.Core void Configure(RuntimeLevel level, RuntimeLevelReason reason); + void DoUnattendedInstall(); } } diff --git a/src/Umbraco.Core/Telemetry/TelemetryMarkerComponent.cs b/src/Umbraco.Core/Telemetry/TelemetryMarkerComponent.cs deleted file mode 100644 index 157cacd618..0000000000 --- a/src/Umbraco.Core/Telemetry/TelemetryMarkerComponent.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.IO; -using Microsoft.Extensions.Logging; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Hosting; -using Umbraco.Core.IO; - -namespace Umbraco.Web.Telemetry -{ - public class TelemetryMarkerComponent : IComponent - { - private readonly ILogger _logger; - private readonly IRuntimeState _runtime; - private readonly IHostingEnvironment _hostingEnvironment; - - public TelemetryMarkerComponent(ILogger logger, IRuntimeState runtime, IHostingEnvironment hostingEnvironment) - { - _logger = logger; - _runtime = runtime; - _hostingEnvironment = hostingEnvironment; - } - - public void Initialize() - { - if (_runtime.Level != RuntimeLevel.Install && _runtime.Level != RuntimeLevel.Upgrade) - { - return; - } - - var telemetricsFilePath = _hostingEnvironment.MapPathContentRoot(SystemFiles.TelemetricsIdentifier); - - // Verify file does not exist already (if we are upgrading) - // In a clean install we know it would not exist - // If the site is upgraded and the file was removed it would re-create one - // NOTE: If user removed the marker file to opt out it would re-create a new guid marker file & potentially skew - if (_runtime.Level == RuntimeLevel.Upgrade && File.Exists(telemetricsFilePath)) - { - _logger.LogWarning("When upgrading the anonymous telemetry file already existed on disk at {filePath}", telemetricsFilePath); - return; - } - if (_runtime.Level == RuntimeLevel.Install && File.Exists(telemetricsFilePath)) - { - // No need to log for when level is install if file exists (As this component hit several times during install process) - return; - } - - // We are a clean install or an upgrade without the marker file - // Generate GUID - var telemetrySiteIdentifier = Guid.NewGuid(); - - // Write file contents - try - { - File.WriteAllText(telemetricsFilePath, telemetrySiteIdentifier.ToString()); - } - catch (Exception ex) - { - _logger.LogError(ex, "Unable to create telemetry file at {filePath}", telemetricsFilePath); - } - - - - } - - public void Terminate() - { - } - } -} diff --git a/src/Umbraco.Core/Telemetry/TelemetryMarkerComposer.cs b/src/Umbraco.Core/Telemetry/TelemetryMarkerComposer.cs deleted file mode 100644 index ccb66c7b2a..0000000000 --- a/src/Umbraco.Core/Telemetry/TelemetryMarkerComposer.cs +++ /dev/null @@ -1,8 +0,0 @@ -using Umbraco.Core; -using Umbraco.Core.Composing; - -namespace Umbraco.Web.Telemetry -{ - public class TelemetryMarkerComposer : ComponentComposer, ICoreComposer - { } -} diff --git a/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs b/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs index a3a43d2b93..0d6be8717a 100644 --- a/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs +++ b/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs @@ -42,6 +42,7 @@ namespace Umbraco.Core.Configuration SaveJson(provider, json); } + public void SaveConfigValue(string key, object value) { var provider = GetJsonConfigurationProvider(); @@ -79,6 +80,40 @@ namespace Umbraco.Core.Configuration SaveJson(provider, json); } + public void SetGlobalId(string id) + { + var provider = GetJsonConfigurationProvider(); + + var json = GetJson(provider); + + var item = GetGlobalIdItem(id); + + json.Merge(item, new JsonMergeSettings()); + + SaveJson(provider, json); + } + + private object GetGlobalIdItem(string id) + { + JTokenWriter writer = new JTokenWriter(); + + writer.WriteStartObject(); + writer.WritePropertyName("Umbraco"); + writer.WriteStartObject(); + writer.WritePropertyName("CMS"); + writer.WriteStartObject(); + writer.WritePropertyName("Global"); + writer.WriteStartObject(); + writer.WritePropertyName("Id"); + writer.WriteValue(id); + writer.WriteEndObject(); + writer.WriteEndObject(); + writer.WriteEndObject(); + writer.WriteEndObject(); + + return writer.Token; + } + private JToken GetDisableRedirectUrlItem(string value) { JTokenWriter writer = new JTokenWriter(); diff --git a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs index 94c1e3dcfa..8ce9839f6b 100644 --- a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs +++ b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs @@ -194,11 +194,12 @@ namespace Umbraco.Infrastructure.DependencyInjection var hostingEnvironment = factory.GetRequiredService(); var dbCreator = factory.GetRequiredService(); + var databaseSchemaCreatorFactory = factory.GetRequiredService(); var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var loggerFactory = factory.GetRequiredService(); return globalSettings.MainDomLock.Equals("SqlMainDomLock") || isWindows == false - ? (IMainDomLock)new SqlMainDomLock(loggerFactory.CreateLogger(), loggerFactory, globalSettings, connectionStrings, dbCreator, hostingEnvironment) + ? (IMainDomLock)new SqlMainDomLock(loggerFactory.CreateLogger(), loggerFactory, globalSettings, connectionStrings, dbCreator, hostingEnvironment, databaseSchemaCreatorFactory) : new MainDomSemaphoreLock(loggerFactory.CreateLogger(), hostingEnvironment); }); diff --git a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Installer.cs b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Installer.cs index e5bdd844d8..1e40831f75 100644 --- a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Installer.cs +++ b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Installer.cs @@ -17,6 +17,7 @@ namespace Umbraco.Infrastructure.DependencyInjection builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/src/Umbraco.Infrastructure/HostedServices/ReportSiteTask.cs b/src/Umbraco.Infrastructure/HostedServices/ReportSiteTask.cs index 95b09d5498..7ce1fffa0c 100644 --- a/src/Umbraco.Infrastructure/HostedServices/ReportSiteTask.cs +++ b/src/Umbraco.Infrastructure/HostedServices/ReportSiteTask.cs @@ -1,15 +1,14 @@ using Newtonsoft.Json; using System; -using System.IO; using System.Net.Http; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; -using Umbraco.Core.Hosting; -using Umbraco.Core.IO; +using Umbraco.Core.Configuration.Models; using Umbraco.Infrastructure.HostedServices; namespace Umbraco.Web.Telemetry @@ -17,71 +16,43 @@ namespace Umbraco.Web.Telemetry public class ReportSiteTask : RecurringHostedServiceBase { private readonly ILogger _logger; - private readonly IHostingEnvironment _hostingEnvironment; private readonly IUmbracoVersion _umbracoVersion; + private readonly IOptions _globalSettings; private static HttpClient s_httpClient; public ReportSiteTask( ILogger logger, - IHostingEnvironment hostingEnvironment, - IUmbracoVersion umbracoVersion) + IUmbracoVersion umbracoVersion, + IOptions globalSettings) : base(TimeSpan.FromDays(1), TimeSpan.FromMinutes(1)) { _logger = logger; - _hostingEnvironment = hostingEnvironment; _umbracoVersion = umbracoVersion; + _globalSettings = globalSettings; s_httpClient = new HttpClient(); } /// - /// Runs the background task to send the anynomous ID + /// Runs the background task to send the anonymous ID /// to telemetry service /// internal override async Task PerformExecuteAsync(object state) { - // Try & find file at '/umbraco/telemetrics-id.umb' - var telemetricsFilePath = _hostingEnvironment.MapPathContentRoot(SystemFiles.TelemetricsIdentifier); - - if (File.Exists(telemetricsFilePath) == false) - { - // Some users may have decided to not be tracked by deleting/removing the marker file - _logger.LogWarning("No telemetry marker file found at '{filePath}' and will not report site to telemetry service", telemetricsFilePath); - - return; - } - - - string telemetricsFileContents; - try - { - // Open file & read its contents - // It may throw due to file permissions or file locking - telemetricsFileContents = File.ReadAllText(telemetricsFilePath); - } - catch (Exception ex) - { - // Silently swallow ex - but lets log it (ReadAllText throws a ton of different types of ex) - // Hence the use of general exception type - _logger.LogError(ex, "Error in reading file contents of telemetry marker file found at '{filePath}'", telemetricsFilePath); - - // Exit out early, but mark this task to be repeated in case its a file lock so it can be rechecked the next time round - return; - } - + // Try & get a value stored in umbracoSettings.config on the backoffice XML element ID attribute + var backofficeIdentifierRaw = _globalSettings.Value.Id; // Parse as a GUID & verify its a GUID and not some random string // In case of users may have messed or decided to empty the file contents or put in something random - if (Guid.TryParse(telemetricsFileContents, out var telemetrySiteIdentifier) == false) + if (Guid.TryParse(backofficeIdentifierRaw, out var telemetrySiteIdentifier) == false) { - // Some users may have decided to mess with file contents - _logger.LogWarning("The telemetry marker file found at '{filePath}' with '{telemetrySiteId}' is not a valid identifier for the telemetry service", telemetricsFilePath, telemetrySiteIdentifier); + // Some users may have decided to mess with the XML attribute and put in something else + _logger.LogWarning("No telemetry marker found"); return; } try { - // Send data to LIVE telemetry s_httpClient.BaseAddress = new Uri("https://telemetry.umbraco.com/"); @@ -112,11 +83,10 @@ namespace Umbraco.Web.Telemetry { // Silently swallow // The user does not need the logs being polluted if our service has fallen over or is down etc - // Hence only loggigng this at a more verbose level (Which users should not be using in prod) + // Hence only logging this at a more verbose level (which users should not be using in production) _logger.LogDebug("There was a problem sending a request to the Umbraco telemetry service"); } } - [DataContract] private class TelemetryReportData { diff --git a/src/Umbraco.Infrastructure/Install/InstallHelper.cs b/src/Umbraco.Infrastructure/Install/InstallHelper.cs index 1538187528..b8b5371457 100644 --- a/src/Umbraco.Infrastructure/Install/InstallHelper.cs +++ b/src/Umbraco.Infrastructure/Install/InstallHelper.cs @@ -131,7 +131,7 @@ namespace Umbraco.Web.Install return true; } - return _databaseBuilder.HasSomeNonDefaultUser() == false; + return _databaseBuilder.IsUmbracoInstalled() == false; } } diff --git a/src/Umbraco.Infrastructure/Install/InstallStepCollection.cs b/src/Umbraco.Infrastructure/Install/InstallStepCollection.cs index 523cd35a27..4b352190b0 100644 --- a/src/Umbraco.Infrastructure/Install/InstallStepCollection.cs +++ b/src/Umbraco.Infrastructure/Install/InstallStepCollection.cs @@ -21,6 +21,7 @@ namespace Umbraco.Web.Install a.OfType().First(), a.OfType().First(), a.OfType().First(), + a.OfType().First(), a.OfType().First(), a.OfType().First(), a.OfType().First(), diff --git a/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs b/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs index b7699b7d0e..5d70338079 100644 --- a/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs +++ b/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs @@ -9,6 +9,7 @@ using Umbraco.Core; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Security; +using Umbraco.Core.Persistence; using Umbraco.Core.Services; using Umbraco.Extensions; using Umbraco.Web.Install.Models; @@ -34,6 +35,7 @@ namespace Umbraco.Web.Install.InstallSteps private readonly ConnectionStrings _connectionStrings; private readonly ICookieManager _cookieManager; private readonly IBackOfficeUserManager _userManager; + private readonly IDbProviderFactoryCreator _dbProviderFactoryCreator; public NewInstallStep( IUserService userService, @@ -42,7 +44,8 @@ namespace Umbraco.Web.Install.InstallSteps IOptions securitySettings, IOptions connectionStrings, ICookieManager cookieManager, - IBackOfficeUserManager userManager) + IBackOfficeUserManager userManager, + IDbProviderFactoryCreator dbProviderFactoryCreator) { _userService = userService ?? throw new ArgumentNullException(nameof(userService)); _databaseBuilder = databaseBuilder ?? throw new ArgumentNullException(nameof(databaseBuilder)); @@ -51,6 +54,7 @@ namespace Umbraco.Web.Install.InstallSteps _connectionStrings = connectionStrings.Value ?? throw new ArgumentNullException(nameof(connectionStrings)); _cookieManager = cookieManager; _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); + _dbProviderFactoryCreator = dbProviderFactoryCreator ?? throw new ArgumentNullException(nameof(dbProviderFactoryCreator)); } public override async Task ExecuteAsync(UserModel user) @@ -120,26 +124,89 @@ namespace Umbraco.Web.Install.InstallSteps { get { - return RequiresExecution(null) - //the user UI - ? "user" - //the continue install UI - : "continueinstall"; + return ShowView() + // the user UI + ? "user" + // continue install UI + : "continueinstall"; } } + private InstallState GetInstallState() + { + var installState = InstallState.Unknown; + + var databaseSettings = _connectionStrings.UmbracoConnectionString; + + var hasConnString = databaseSettings != null && _databaseBuilder.IsDatabaseConfigured; + if (hasConnString) + { + installState = (installState | InstallState.HasConnectionString) & ~InstallState.Unknown; + } + + var connStringConfigured = databaseSettings.IsConnectionStringConfigured(); + if (connStringConfigured) + { + installState = (installState | InstallState.ConnectionStringConfigured) & ~InstallState.Unknown; + } + + var factory = _dbProviderFactoryCreator.CreateFactory(databaseSettings.ProviderName); + var canConnect = connStringConfigured && DbConnectionExtensions.IsConnectionAvailable(databaseSettings.ConnectionString, factory); + if (canConnect) + { + installState = (installState | InstallState.CanConnect) & ~InstallState.Unknown; + } + + var umbracoInstalled = canConnect ? _databaseBuilder.IsUmbracoInstalled() : false; + if (umbracoInstalled) + { + installState = (installState | InstallState.UmbracoInstalled) & ~InstallState.Unknown; + } + + var hasNonDefaultUser = umbracoInstalled ? _databaseBuilder.HasSomeNonDefaultUser() : false; + if (hasNonDefaultUser) + { + installState = (installState | InstallState.HasNonDefaultUser) & ~InstallState.Unknown; + } + + return installState; + } + + private bool ShowView() + { + var installState = GetInstallState(); + + return installState.HasFlag(InstallState.Unknown) + || !installState.HasFlag(InstallState.UmbracoInstalled); + } + public override bool RequiresExecution(UserModel model) { - //now we have to check if this is really a new install, the db might be configured and might contain data - var databaseSettings = _connectionStrings.UmbracoConnectionString; - if (databaseSettings.IsConnectionStringConfigured() && _databaseBuilder.IsDatabaseConfigured) - return _databaseBuilder.HasSomeNonDefaultUser() == false; + var installState = GetInstallState(); - // In this one case when it's a brand new install and nothing has been configured, make sure the - // back office cookie is cleared so there's no old cookies lying around causing problems - _cookieManager.ExpireCookie(_securitySettings.AuthCookieName); + if (installState.HasFlag(InstallState.Unknown)) + { + // In this one case when it's a brand new install and nothing has been configured, make sure the + // back office cookie is cleared so there's no old cookies lying around causing problems + _cookieManager.ExpireCookie(_securitySettings.AuthCookieName); + } - return true; + return installState.HasFlag(InstallState.Unknown) + || !installState.HasFlag(InstallState.HasNonDefaultUser); + } + + [Flags] + private enum InstallState : short + { + // This is an easy way to avoid 0 enum assignment and not worry about + // manual calcs. https://www.codeproject.com/Articles/396851/Ending-the-Great-Debate-on-Enum-Flags + Unknown = 1, + HasVersion = 1 << 1, + HasConnectionString = 1 << 2, + ConnectionStringConfigured = 1 << 3, + CanConnect = 1 << 4, + UmbracoInstalled = 1 << 5, + HasNonDefaultUser = 1 << 6 } } } diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs index 98e9bcb4bb..541896548c 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs @@ -29,9 +29,9 @@ namespace Umbraco.Core.Migrations.Install private readonly IHostingEnvironment _hostingEnvironment; private readonly ILogger _logger; private readonly ILoggerFactory _loggerFactory; - private readonly IUmbracoVersion _umbracoVersion; private readonly IDbProviderFactoryCreator _dbProviderFactoryCreator; private readonly IConfigManipulator _configManipulator; + private readonly DatabaseSchemaCreatorFactory _databaseSchemaCreatorFactory; private DatabaseSchemaResult _databaseSchemaValidationResult; @@ -47,9 +47,9 @@ namespace Umbraco.Core.Migrations.Install IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, IHostingEnvironment hostingEnvironment, - IUmbracoVersion umbracoVersion, IDbProviderFactoryCreator dbProviderFactoryCreator, - IConfigManipulator configManipulator) + IConfigManipulator configManipulator, + DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory) { _scopeProvider = scopeProvider; _databaseFactory = databaseFactory; @@ -59,9 +59,9 @@ namespace Umbraco.Core.Migrations.Install _migrationBuilder = migrationBuilder; _keyValueService = keyValueService; _hostingEnvironment = hostingEnvironment; - _umbracoVersion = umbracoVersion; _dbProviderFactoryCreator = dbProviderFactoryCreator; _configManipulator = configManipulator; + _databaseSchemaCreatorFactory = databaseSchemaCreatorFactory; } #region Status @@ -133,6 +133,14 @@ namespace Umbraco.Core.Migrations.Install } } + internal bool IsUmbracoInstalled() + { + using (var scope = _scopeProvider.CreateScope(autoComplete: true)) + { + return scope.Database.IsUmbracoInstalled(); + } + } + #endregion #region Configure Connection String @@ -315,14 +323,15 @@ namespace Umbraco.Core.Migrations.Install private DatabaseSchemaResult ValidateSchema(IScope scope) { if (_databaseFactory.Initialized == false) - return new DatabaseSchemaResult(_databaseFactory.SqlContext.SqlSyntax); + return new DatabaseSchemaResult(); if (_databaseSchemaValidationResult != null) return _databaseSchemaValidationResult; - var database = scope.Database; - var dbSchema = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion); - _databaseSchemaValidationResult = dbSchema.ValidateSchema(); + _databaseSchemaValidationResult = scope.Database.ValidateSchema(); + + scope.Complete(); + return _databaseSchemaValidationResult; } @@ -361,15 +370,14 @@ namespace Umbraco.Core.Migrations.Install var schemaResult = ValidateSchema(); var hasInstalledVersion = schemaResult.DetermineHasInstalledVersion(); - //var installedSchemaVersion = schemaResult.DetermineInstalledVersion(); - //var hasInstalledVersion = !installedSchemaVersion.Equals(new Version(0, 0, 0)); + //If the determined version is "empty" its a new install - otherwise upgrade the existing if (!hasInstalledVersion) { if (_runtime.Level == RuntimeLevel.Run) throw new Exception("Umbraco is already configured!"); - var creator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion); + var creator = _databaseSchemaCreatorFactory.Create(database); creator.InitializeDatabaseSchema(); message = message + "

Installation completed!

"; diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs index 5bca64e1e1..ed6e684cc6 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs @@ -25,10 +25,15 @@ namespace Umbraco.Core.Migrations.Install public DatabaseSchemaCreator(IUmbracoDatabase database, ILogger logger, ILoggerFactory loggerFactory, IUmbracoVersion umbracoVersion) { - _database = database; - _logger = logger; - _loggerFactory = loggerFactory; - _umbracoVersion = umbracoVersion; + _database = database ?? throw new ArgumentNullException(nameof(database)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); + _umbracoVersion = umbracoVersion ?? throw new ArgumentNullException(nameof(umbracoVersion)); + + if (_database?.SqlContext?.SqlSyntax == null) + { + throw new InvalidOperationException("No SqlContext has been assigned to the database"); + } } private ISqlSyntaxProvider SqlSyntax => _database.SqlContext.SqlSyntax; @@ -149,7 +154,7 @@ namespace Umbraco.Core.Migrations.Install internal DatabaseSchemaResult ValidateSchema(IEnumerable orderedTables) { - var result = new DatabaseSchemaResult(SqlSyntax); + var result = new DatabaseSchemaResult(); result.IndexDefinitions.AddRange(SqlSyntax.GetDefinedIndexes(_database) .Select(x => new DbIndexDefinition(x))); @@ -451,14 +456,14 @@ namespace Umbraco.Core.Migrations.Install } //Execute the Create Table sql - var created = _database.Execute(new Sql(createSql)); - _logger.LogInformation("Create Table {TableName} ({Created}): \n {Sql}", tableName, created, createSql); + _database.Execute(new Sql(createSql)); + _logger.LogInformation("Create Table {TableName}: \n {Sql}", tableName, createSql); //If any statements exists for the primary key execute them here if (string.IsNullOrEmpty(createPrimaryKeySql) == false) { - var createdPk = _database.Execute(new Sql(createPrimaryKeySql)); - _logger.LogInformation("Create Primary Key ({CreatedPk}):\n {Sql}", createdPk, createPrimaryKeySql); + _database.Execute(new Sql(createPrimaryKeySql)); + _logger.LogInformation("Create Primary Key:\n {Sql}", createPrimaryKeySql); } if (SqlSyntax.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity)) @@ -475,15 +480,15 @@ namespace Umbraco.Core.Migrations.Install //Loop through index statements and execute sql foreach (var sql in indexSql) { - var createdIndex = _database.Execute(new Sql(sql)); - _logger.LogInformation("Create Index ({CreatedIndex}):\n {Sql}", createdIndex, sql); + _database.Execute(new Sql(sql)); + _logger.LogInformation("Create Index:\n {Sql}", sql); } //Loop through foreignkey statements and execute sql foreach (var sql in foreignSql) { - var createdFk = _database.Execute(new Sql(sql)); - _logger.LogInformation("Create Foreign Key ({CreatedFk}):\n {Sql}", createdFk, sql); + _database.Execute(new Sql(sql)); + _logger.LogInformation("Create Foreign Key:\n {Sql}", sql); } if (overwrite) diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreatorFactory.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreatorFactory.cs new file mode 100644 index 0000000000..935ede3ab5 --- /dev/null +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreatorFactory.cs @@ -0,0 +1,31 @@ +using Microsoft.Extensions.Logging; +using Umbraco.Core.Configuration; +using Umbraco.Core.Persistence; + +namespace Umbraco.Core.Migrations.Install +{ + /// + /// Creates the initial database schema during install. + /// + public class DatabaseSchemaCreatorFactory + { + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; + private readonly IUmbracoVersion _umbracoVersion; + + public DatabaseSchemaCreatorFactory( + ILogger logger, + ILoggerFactory loggerFactory, + IUmbracoVersion umbracoVersion) + { + _logger = logger; + _loggerFactory = loggerFactory; + _umbracoVersion = umbracoVersion; + } + + public DatabaseSchemaCreator Create(IUmbracoDatabase database) + { + return new DatabaseSchemaCreator(database, _logger, _loggerFactory, _umbracoVersion); + } + } +} diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaResult.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaResult.cs index e7b7b479ec..a153ba7b41 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaResult.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaResult.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.DatabaseModelDefinitions; -using Umbraco.Core.Persistence.SqlSyntax; namespace Umbraco.Core.Migrations.Install { @@ -12,7 +12,7 @@ namespace Umbraco.Core.Migrations.Install /// public class DatabaseSchemaResult { - public DatabaseSchemaResult(ISqlSyntaxProvider sqlSyntax) + public DatabaseSchemaResult() { Errors = new List>(); TableDefinitions = new List(); diff --git a/src/Umbraco.Infrastructure/Persistence/IUmbracoDatabase.cs b/src/Umbraco.Infrastructure/Persistence/IUmbracoDatabase.cs index 1b0d1d9c2b..3849ae6ebd 100644 --- a/src/Umbraco.Infrastructure/Persistence/IUmbracoDatabase.cs +++ b/src/Umbraco.Infrastructure/Persistence/IUmbracoDatabase.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using NPoco; +using Umbraco.Core.Migrations.Install; namespace Umbraco.Core.Persistence { @@ -25,5 +26,7 @@ namespace Umbraco.Core.Persistence bool EnableSqlCount { get; set; } int SqlCount { get; } int BulkInsertRecords(IEnumerable records); + bool IsUmbracoInstalled(); + DatabaseSchemaResult ValidateSchema(); } } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentRepositoryBase.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentRepositoryBase.cs index 7b90efd4ae..bd947260ce 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentRepositoryBase.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentRepositoryBase.cs @@ -947,7 +947,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement var template = SqlContext.Templates.Get(Constants.SqlTemplates.VersionableRepository.EnsureUniqueNodeName, tsql => tsql .Select(x => Alias(x.NodeId, "id"), x => Alias(x.Text, "name")) .From() - .Where(x => x.NodeObjectType == SqlTemplate.Arg("nodeObjectType") && x.ParentId == SqlTemplate.Arg("parentId"))); + .Where(x => x.NodeObjectType == SqlTemplate.Arg("nodeObjectType") && x.ParentId == SqlTemplate.Arg("parentId")) + ); var sql = template.Sql(NodeObjectTypeId, parentId); var names = Database.Fetch(sql); @@ -957,28 +958,43 @@ namespace Umbraco.Core.Persistence.Repositories.Implement protected virtual int GetNewChildSortOrder(int parentId, int first) { - var template = SqlContext.Templates.Get(Constants.SqlTemplates.VersionableRepository.GetSortOrder, tsql => - tsql.Select($"COALESCE(MAX(sortOrder),{first - 1})").From().Where(x => x.ParentId == SqlTemplate.Arg("parentId") && x.NodeObjectType == NodeObjectTypeId) + var template = SqlContext.Templates.Get(Constants.SqlTemplates.VersionableRepository.GetSortOrder, tsql => tsql + .Select("MAX(sortOrder)") + .From() + .Where(x => x.NodeObjectType == SqlTemplate.Arg("nodeObjectType") && x.ParentId == SqlTemplate.Arg("parentId")) ); - return Database.ExecuteScalar(template.Sql(new { parentId })) + 1; + var sql = template.Sql(NodeObjectTypeId, parentId); + var sortOrder = Database.ExecuteScalar(sql); + + return (sortOrder + 1) ?? first; } protected virtual NodeDto GetParentNodeDto(int parentId) { - var template = SqlContext.Templates.Get(Constants.SqlTemplates.VersionableRepository.GetParentNode, tsql => - tsql.Select().From().Where(x => x.NodeId == SqlTemplate.Arg("parentId")) + var template = SqlContext.Templates.Get(Constants.SqlTemplates.VersionableRepository.GetParentNode, tsql => tsql + .Select() + .From() + .Where(x => x.NodeId == SqlTemplate.Arg("parentId")) ); - return Database.Fetch(template.Sql(parentId)).First(); + var sql = template.Sql(parentId); + var nodeDto = Database.First(sql); + + return nodeDto; } protected virtual int GetReservedId(Guid uniqueId) { - var template = SqlContext.Templates.Get(Constants.SqlTemplates.VersionableRepository.GetReservedId, tsql => - tsql.Select(x => x.NodeId).From().Where(x => x.UniqueId == SqlTemplate.Arg("uniqueId") && x.NodeObjectType == Constants.ObjectTypes.IdReservation) + var template = SqlContext.Templates.Get(Constants.SqlTemplates.VersionableRepository.GetReservedId, tsql => tsql + .Select(x => x.NodeId) + .From() + .Where(x => x.UniqueId == SqlTemplate.Arg("uniqueId") && x.NodeObjectType == Constants.ObjectTypes.IdReservation) ); - var id = Database.ExecuteScalar(template.Sql(new { uniqueId = uniqueId })); + + var sql = template.Sql(new { uniqueId }); + var id = Database.ExecuteScalar(sql); + return id ?? 0; } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs index 6554782d24..c5c38d29bc 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs @@ -467,8 +467,14 @@ AND umbracoNode.id <> @id", // The composed property is only considered segment variant when the base content type is also segment variant. // Example: Culture variant content type with a Culture+Segment variant property type will become ContentVariation.Culture var target = newContentTypeVariation & composedPropertyType.Variations; + // Determine the previous variation + // We have to compare with the old content type variation because the composed property might already have changed + // Example: A property with variations in an element type with variations is used in a document without + // when you enable variations the property has already enabled variations from the element type, + // but it's still a change from nothing because the document did not have variations, but it does now. + var from = oldContentTypeVariation & composedPropertyType.Variations; - propertyTypeVariationChanges[composedPropertyType.Id] = (composedPropertyType.Variations, target); + propertyTypeVariationChanges[composedPropertyType.Id] = (from, target); } } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs index 1f614e7647..b50f46e9a6 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs @@ -313,7 +313,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private string EnsureUniqueNodeName(string nodeName, int id = 0) { - var template = SqlContext.Templates.Get("Umbraco.Core.DataTypeDefinitionRepository.EnsureUniqueNodeName", tsql => tsql + var template = SqlContext.Templates.Get(Constants.SqlTemplates.DataTypeRepository.EnsureUniqueNodeName, tsql => tsql .Select(x => Alias(x.NodeId, "id"), x => Alias(x.Text, "name")) .From() .Where(x => x.NodeObjectType == SqlTemplate.Arg("nodeObjectType"))); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/RelationRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/RelationRepository.cs index 4299d50f15..80ca2edd11 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/RelationRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/RelationRepository.cs @@ -314,17 +314,51 @@ namespace Umbraco.Core.Persistence.Repositories.Implement public void DeleteByParent(int parentId, params string[] relationTypeAliases) { - var subQuery = Sql().Select(x => x.Id) - .From() - .InnerJoin().On(x => x.RelationType, x => x.Id) - .Where(x => x.ParentId == parentId); - - if (relationTypeAliases.Length > 0) + if (Database.DatabaseType.IsSqlCe()) { - subQuery.WhereIn(x => x.Alias, relationTypeAliases); - } + var subQuery = Sql().Select(x => x.Id) + .From() + .InnerJoin().On(x => x.RelationType, x => x.Id) + .Where(x => x.ParentId == parentId); - Database.Execute(Sql().Delete().WhereIn(x => x.Id, subQuery)); + if (relationTypeAliases.Length > 0) + { + subQuery.WhereIn(x => x.Alias, relationTypeAliases); + } + + Database.Execute(Sql().Delete().WhereIn(x => x.Id, subQuery)); + + } + else + { + if (relationTypeAliases.Length > 0) + { + var template = SqlContext.Templates.Get( + Constants.SqlTemplates.RelationRepository.DeleteByParentIn, + tsql => Sql().Delete() + .From() + .InnerJoin().On(x => x.RelationType, x => x.Id) + .Where(x => x.ParentId == SqlTemplate.Arg("parentId")) + .WhereIn(x => x.Alias, SqlTemplate.ArgIn("relationTypeAliases"))); + + var sql = template.Sql(parentId, relationTypeAliases); + + Database.Execute(sql); + } + else + { + var template = SqlContext.Templates.Get( + Constants.SqlTemplates.RelationRepository.DeleteByParentAll, + tsql => Sql().Delete() + .From() + .InnerJoin().On(x => x.RelationType, x => x.Id) + .Where(x => x.ParentId == SqlTemplate.Arg("parentId"))); + + var sql = template.Sql(parentId); + + Database.Execute(sql); + } + } } /// diff --git a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabase.cs b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabase.cs index 37c47da50d..74aba854e3 100644 --- a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabase.cs +++ b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabase.cs @@ -2,14 +2,13 @@ using System.Collections.Generic; using System.Data; using System.Data.Common; -using System.Data.SqlClient; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using NPoco; using StackExchange.Profiling; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence.FaultHandling; -using Umbraco.Core.Persistence.SqlSyntax; namespace Umbraco.Core.Persistence { @@ -25,6 +24,7 @@ namespace Umbraco.Core.Persistence { private readonly ILogger _logger; private readonly IBulkSqlInsertProvider _bulkSqlInsertProvider; + private readonly DatabaseSchemaCreatorFactory _databaseSchemaCreatorFactory; private readonly RetryPolicy _connectionRetryPolicy; private readonly RetryPolicy _commandRetryPolicy; private readonly Guid _instanceGuid = Guid.NewGuid(); @@ -39,13 +39,14 @@ namespace Umbraco.Core.Persistence /// Used by UmbracoDatabaseFactory to create databases. /// Also used by DatabaseBuilder for creating databases and installing/upgrading. /// - public UmbracoDatabase(string connectionString, ISqlContext sqlContext, DbProviderFactory provider, ILogger logger, IBulkSqlInsertProvider bulkSqlInsertProvider, RetryPolicy connectionRetryPolicy = null, RetryPolicy commandRetryPolicy = null) + public UmbracoDatabase(string connectionString, ISqlContext sqlContext, DbProviderFactory provider, ILogger logger, IBulkSqlInsertProvider bulkSqlInsertProvider, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory, RetryPolicy connectionRetryPolicy = null, RetryPolicy commandRetryPolicy = null) : base(connectionString, sqlContext.DatabaseType, provider, sqlContext.SqlSyntax.DefaultIsolationLevel) { SqlContext = sqlContext; _logger = logger; _bulkSqlInsertProvider = bulkSqlInsertProvider; + _databaseSchemaCreatorFactory = databaseSchemaCreatorFactory; _connectionRetryPolicy = connectionRetryPolicy; _commandRetryPolicy = commandRetryPolicy; @@ -177,7 +178,20 @@ namespace Umbraco.Core.Persistence } + /// + /// Returns the for the database + /// + public DatabaseSchemaResult ValidateSchema() + { + var dbSchema = _databaseSchemaCreatorFactory.Create(this); + var databaseSchemaValidationResult = dbSchema.ValidateSchema(); + return databaseSchemaValidationResult; + } + /// + /// Returns true if Umbraco database tables are detected to be installed + /// + public bool IsUmbracoInstalled() => ValidateSchema().DetermineHasInstalledVersion(); #endregion diff --git a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseExtensions.cs b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseExtensions.cs index 714721ef2c..204f904f68 100644 --- a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseExtensions.cs +++ b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseExtensions.cs @@ -1,6 +1,6 @@ using System; +using System.Linq; using Umbraco.Core.Persistence.Dtos; -using Umbraco.Core.Runtime; namespace Umbraco.Core.Persistence { @@ -27,5 +27,33 @@ namespace Umbraco.Core.Persistence .Where(x => x.Key == key); return database.FirstOrDefault(sql)?.Value; } + + + /// + /// Returns true if the database contains the specified table + /// + /// + /// + /// + public static bool HasTable(this IUmbracoDatabase database, string tableName) + { + try + { + return database.SqlContext.SqlSyntax.GetTablesInSchema(database).Any(table => table.InvariantEquals(tableName)); + } + catch (Exception) + { + return false; // will occur if the database cannot connect + } + } + + /// + /// Returns true if the database contains no tables + /// + /// + /// + public static bool IsDatabaseEmpty(this IUmbracoDatabase database) + => database.SqlContext.SqlSyntax.GetTablesInSchema(database).Any() == false; + } } diff --git a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs index 5c3c984677..69c8975ed5 100644 --- a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Options; using NPoco; using NPoco.FluentMappings; using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence.FaultHandling; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.SqlSyntax; @@ -27,6 +28,7 @@ namespace Umbraco.Core.Persistence public class UmbracoDatabaseFactory : DisposableObjectSlim, IUmbracoDatabaseFactory { private readonly IDbProviderFactoryCreator _dbProviderFactoryCreator; + private readonly DatabaseSchemaCreatorFactory _databaseSchemaCreatorFactory; private readonly GlobalSettings _globalSettings; private readonly Lazy _mappers; private readonly ILogger _logger; @@ -70,8 +72,8 @@ namespace Umbraco.Core.Persistence /// Initializes a new instance of the . /// /// Used by core runtime. - public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, IOptions globalSettings, IOptions connectionStrings, Lazy mappers,IDbProviderFactoryCreator dbProviderFactoryCreator) - : this(logger, loggerFactory, globalSettings.Value, connectionStrings.Value, mappers, dbProviderFactoryCreator) + public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, IOptions globalSettings, IOptions connectionStrings, Lazy mappers,IDbProviderFactoryCreator dbProviderFactoryCreator, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory) + : this(logger, loggerFactory, globalSettings.Value, connectionStrings.Value, mappers, dbProviderFactoryCreator, databaseSchemaCreatorFactory) { } @@ -80,12 +82,13 @@ namespace Umbraco.Core.Persistence /// Initializes a new instance of the . /// /// Used by the other ctor and in tests. - public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, GlobalSettings globalSettings, ConnectionStrings connectionStrings, Lazy mappers, IDbProviderFactoryCreator dbProviderFactoryCreator) + public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, GlobalSettings globalSettings, ConnectionStrings connectionStrings, Lazy mappers, IDbProviderFactoryCreator dbProviderFactoryCreator, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory) { _globalSettings = globalSettings; _mappers = mappers ?? throw new ArgumentNullException(nameof(mappers)); _dbProviderFactoryCreator = dbProviderFactoryCreator ?? throw new ArgumentNullException(nameof(dbProviderFactoryCreator)); + _databaseSchemaCreatorFactory = databaseSchemaCreatorFactory ?? throw new ArgumentNullException(nameof(databaseSchemaCreatorFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _loggerFactory = loggerFactory; @@ -114,12 +117,13 @@ namespace Umbraco.Core.Persistence /// Initializes a new instance of the . /// /// Used in tests. - public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, string connectionString, string providerName, Lazy mappers, IDbProviderFactoryCreator dbProviderFactoryCreator) + public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, string connectionString, string providerName, Lazy mappers, IDbProviderFactoryCreator dbProviderFactoryCreator, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory) { _mappers = mappers ?? throw new ArgumentNullException(nameof(mappers)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _loggerFactory = loggerFactory; _dbProviderFactoryCreator = dbProviderFactoryCreator ?? throw new ArgumentNullException(nameof(dbProviderFactoryCreator)); + _databaseSchemaCreatorFactory = databaseSchemaCreatorFactory ?? throw new ArgumentNullException(nameof(databaseSchemaCreatorFactory)); if (string.IsNullOrWhiteSpace(connectionString) || string.IsNullOrWhiteSpace(providerName)) { @@ -312,7 +316,7 @@ namespace Umbraco.Core.Persistence // method used by NPoco's UmbracoDatabaseFactory to actually create the database instance private UmbracoDatabase CreateDatabaseInstance() { - return new UmbracoDatabase(ConnectionString, SqlContext, DbProviderFactory, _loggerFactory.CreateLogger(), _bulkSqlInsertProvider, _connectionRetryPolicy, _commandRetryPolicy); + return new UmbracoDatabase(ConnectionString, SqlContext, DbProviderFactory, _loggerFactory.CreateLogger(), _bulkSqlInsertProvider, _databaseSchemaCreatorFactory, _connectionRetryPolicy, _commandRetryPolicy); } protected override void DisposeResources() diff --git a/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs b/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs index a05c1a7f98..de0be4ca25 100644 --- a/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs @@ -78,6 +78,7 @@ namespace Umbraco.Infrastructure.Runtime AppDomain.CurrentDomain.SetData("DataDirectory", _hostingEnvironment?.MapPathContentRoot(Core.Constants.SystemDirectories.Data)); + DoUnattendedInstall(); DetermineRuntimeLevel(); if (State.Level <= RuntimeLevel.BootFailed) @@ -100,6 +101,11 @@ namespace Umbraco.Infrastructure.Runtime _components.Initialize(); } + private void DoUnattendedInstall() + { + State.DoUnattendedInstall(); + } + public async Task StopAsync(CancellationToken cancellationToken) { _components.Terminate(); diff --git a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs index c73a817327..a150afa095 100644 --- a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs +++ b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs @@ -10,10 +10,12 @@ using Microsoft.Extensions.Logging; using NPoco; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.SqlSyntax; +using MapperCollection = Umbraco.Core.Persistence.Mappers.MapperCollection; namespace Umbraco.Core.Runtime { @@ -31,19 +33,21 @@ namespace Umbraco.Core.Runtime private readonly UmbracoDatabaseFactory _dbFactory; private bool _errorDuringAcquiring; private object _locker = new object(); + private bool _hasTable = false; - public SqlMainDomLock(ILogger logger, ILoggerFactory loggerFactory, GlobalSettings globalSettings, ConnectionStrings connectionStrings, IDbProviderFactoryCreator dbProviderFactoryCreator, IHostingEnvironment hostingEnvironment) + public SqlMainDomLock(ILogger logger, ILoggerFactory loggerFactory, GlobalSettings globalSettings, ConnectionStrings connectionStrings, IDbProviderFactoryCreator dbProviderFactoryCreator, IHostingEnvironment hostingEnvironment, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory) { // unique id for our appdomain, this is more unique than the appdomain id which is just an INT counter to its safer _lockId = Guid.NewGuid().ToString(); _logger = logger; - _hostingEnvironment = hostingEnvironment; +_hostingEnvironment = hostingEnvironment; _dbFactory = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, globalSettings, connectionStrings, - new Lazy(() => new Persistence.Mappers.MapperCollection(Enumerable.Empty())), - dbProviderFactoryCreator); + new Lazy(() => new MapperCollection(Enumerable.Empty())), + dbProviderFactoryCreator, + databaseSchemaCreatorFactory); MainDomKey = MainDomKeyPrefix + "-" + (NetworkHelper.MachineName + MainDom.GetMainDomId(_hostingEnvironment)).GenerateHash(); } @@ -52,7 +56,7 @@ namespace Umbraco.Core.Runtime { if (!_dbFactory.Configured) { - // if we aren't configured, then we're in an install state, in which case we have no choice but to assume we can acquire + // if we aren't configured then we're in an install state, in which case we have no choice but to assume we can acquire return true; } @@ -72,6 +76,14 @@ namespace Umbraco.Core.Runtime try { db = _dbFactory.CreateDatabase(); + + _hasTable = db.HasTable(Constants.DatabaseSchema.Tables.KeyValue); + if (!_hasTable) + { + // the Db does not contain the required table, we must be in an install state we have no choice but to assume we can acquire + return true; + } + db.BeginTransaction(IsolationLevel.ReadCommitted); try @@ -176,11 +188,24 @@ namespace Umbraco.Core.Runtime _logger.LogDebug("Task canceled, exiting loop"); return; } - IUmbracoDatabase db = null; + try { db = _dbFactory.CreateDatabase(); + + if (!_hasTable) + { + // re-check if its still false, we don't want to re-query once we know its there since this + // loop needs to use minimal resources + _hasTable = db.HasTable(Constants.DatabaseSchema.Tables.KeyValue); + if (!_hasTable) + { + // the Db does not contain the required table, we just keep looping since we can't query the db + continue; + } + } + db.BeginTransaction(IsolationLevel.ReadCommitted); // get a read lock _sqlServerSyntax.ReadLock(db, Constants.Locks.MainDom); @@ -414,7 +439,7 @@ namespace Umbraco.Core.Runtime _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); - if (_dbFactory.Configured) + if (_dbFactory.Configured && _hasTable) { IUmbracoDatabase db = null; try diff --git a/src/Umbraco.Infrastructure/RuntimeState.cs b/src/Umbraco.Infrastructure/RuntimeState.cs index 505cf045c3..8b5e0abdc0 100644 --- a/src/Umbraco.Infrastructure/RuntimeState.cs +++ b/src/Umbraco.Infrastructure/RuntimeState.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Exceptions; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Migrations.Upgrade; using Umbraco.Core.Persistence; @@ -20,6 +21,7 @@ namespace Umbraco.Core private readonly IUmbracoVersion _umbracoVersion; private readonly IUmbracoDatabaseFactory _databaseFactory; private readonly ILogger _logger; + private readonly DatabaseSchemaCreatorFactory _databaseSchemaCreatorFactory; /// /// The initial @@ -33,12 +35,18 @@ namespace Umbraco.Core /// /// Initializes a new instance of the class. /// - public RuntimeState(IOptions globalSettings, IUmbracoVersion umbracoVersion, IUmbracoDatabaseFactory databaseFactory, ILogger logger) + public RuntimeState( + IOptions globalSettings, + IUmbracoVersion umbracoVersion, + IUmbracoDatabaseFactory databaseFactory, + ILogger logger, + DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory) { _globalSettings = globalSettings.Value; _umbracoVersion = umbracoVersion; _databaseFactory = databaseFactory; _logger = logger; + _databaseSchemaCreatorFactory = databaseSchemaCreatorFactory; } @@ -79,9 +87,119 @@ namespace Umbraco.Core return; } - // else, keep going, - // anything other than install wants a database - see if we can connect - // (since this is an already existing database, assume localdb is ready) + // Check the database state, whether we can connect or if it's in an upgrade or empty state, etc... + + switch (GetUmbracoDatabaseState(_databaseFactory)) + { + case UmbracoDatabaseState.CannotConnect: + { + // cannot connect to configured database, this is bad, fail + _logger.LogDebug("Could not connect to database."); + + if (_globalSettings.InstallMissingDatabase) + { + // ok to install on a configured but missing database + Level = RuntimeLevel.Install; + Reason = RuntimeLevelReason.InstallMissingDatabase; + return; + } + + // else it is bad enough that we want to throw + Reason = RuntimeLevelReason.BootFailedCannotConnectToDatabase; + throw new BootFailedException("A connection string is configured but Umbraco could not connect to the database."); + } + case UmbracoDatabaseState.NotInstalled: + { + // ok to install on an empty database + Level = RuntimeLevel.Install; + Reason = RuntimeLevelReason.InstallEmptyDatabase; + return; + } + case UmbracoDatabaseState.NeedsUpgrade: + { + // the db version does not match... but we do have a migration table + // so, at least one valid table, so we quite probably are installed & need to upgrade + + // although the files version matches the code version, the database version does not + // which means the local files have been upgraded but not the database - need to upgrade + _logger.LogDebug("Has not reached the final upgrade step, need to upgrade Umbraco."); + Level = RuntimeLevel.Upgrade; + Reason = RuntimeLevelReason.UpgradeMigrations; + } + break; + case UmbracoDatabaseState.Ok: + default: + { + // if we already know we want to upgrade, exit here + if (Level == RuntimeLevel.Upgrade) + return; + + // the database version matches the code & files version, all clear, can run + Level = RuntimeLevel.Run; + Reason = RuntimeLevelReason.Run; + } + break; + } + } + + private enum UmbracoDatabaseState + { + Ok, + CannotConnect, + NotInstalled, + NeedsUpgrade + } + + private UmbracoDatabaseState GetUmbracoDatabaseState(IUmbracoDatabaseFactory databaseFactory) + { + try + { + if (!TryDbConnect(databaseFactory)) + { + return UmbracoDatabaseState.CannotConnect; + } + + // no scope, no service - just directly accessing the database + using (var database = databaseFactory.CreateDatabase()) + { + if (!database.IsUmbracoInstalled()) + { + return UmbracoDatabaseState.NotInstalled; + } + + if (DoesUmbracoRequireUpgrade(database)) + { + return UmbracoDatabaseState.NeedsUpgrade; + } + } + + return UmbracoDatabaseState.Ok; + } + catch (Exception e) + { + // can connect to the database so cannot check the upgrade state... oops + _logger.LogWarning(e, "Could not check the upgrade state."); + + // else it is bad enough that we want to throw + Reason = RuntimeLevelReason.BootFailedCannotCheckUpgradeState; + throw new BootFailedException("Could not check the upgrade state.", e); + } + } + + public void Configure(RuntimeLevel level, RuntimeLevelReason reason) + { + Level = level; + Reason = reason; + } + + public void DoUnattendedInstall() + { + // unattended install is not enabled + if (_globalSettings.InstallUnattended == false) return; + + // no connection string set + if (_databaseFactory.Configured == false) return; + var connect = false; var tries = _globalSettings.InstallMissingDatabase ? 2 : 5; for (var i = 0;;) @@ -92,79 +210,37 @@ namespace Umbraco.Core Thread.Sleep(1000); } - if (connect == false) - { - // cannot connect to configured database, this is bad, fail - _logger.LogDebug("Could not connect to database."); + // could not connect to the database + if (connect == false) return; - if (_globalSettings.InstallMissingDatabase) + using (var database = _databaseFactory.CreateDatabase()) + { + var hasUmbracoTables = database.IsUmbracoInstalled(); + + // database has umbraco tables, assume Umbraco is already installed + if (hasUmbracoTables) return; + + // all conditions fulfilled, do the install + _logger.LogInformation("Starting unattended install."); + + try { - // ok to install on a configured but missing database - Level = RuntimeLevel.Install; - Reason = RuntimeLevelReason.InstallMissingDatabase; - return; + database.BeginTransaction(); + var creator = _databaseSchemaCreatorFactory.Create(database); + creator.InitializeDatabaseSchema(); + database.CompleteTransaction(); + _logger.LogInformation("Unattended install completed."); } - - // else it is bad enough that we want to throw - Reason = RuntimeLevelReason.BootFailedCannotConnectToDatabase; - throw new BootFailedException("A connection string is configured but Umbraco could not connect to the database."); - } - - // if we already know we want to upgrade, - // still run EnsureUmbracoUpgradeState to get the states - // (v7 will just get a null state, that's ok) - - // else - // look for a matching migration entry - bypassing services entirely - they are not 'up' yet - bool noUpgrade; - try - { - noUpgrade = EnsureUmbracoUpgradeState(_databaseFactory, _logger); - } - catch (Exception e) - { - // can connect to the database but cannot check the upgrade state... oops - _logger.LogWarning(e, "Could not check the upgrade state."); - - if (_globalSettings.InstallEmptyDatabase) + catch (Exception ex) { - // ok to install on an empty database - Level = RuntimeLevel.Install; - Reason = RuntimeLevelReason.InstallEmptyDatabase; - return; + _logger.LogInformation(ex, "Error during unattended install."); + database.AbortTransaction(); + + throw new UnattendedInstallException( + "The database configuration failed with the following message: " + ex.Message + + "\n Please check log file for additional information (can be found in '/App_Data/Logs/')"); } - - // else it is bad enough that we want to throw - Reason = RuntimeLevelReason.BootFailedCannotCheckUpgradeState; - throw new BootFailedException("Could not check the upgrade state.", e); } - - // if we already know we want to upgrade, exit here - if (Level == RuntimeLevel.Upgrade) - return; - - if (noUpgrade) - { - // the database version matches the code & files version, all clear, can run - Level = RuntimeLevel.Run; - Reason = RuntimeLevelReason.Run; - return; - } - - // the db version does not match... but we do have a migration table - // so, at least one valid table, so we quite probably are installed & need to upgrade - - // although the files version matches the code version, the database version does not - // which means the local files have been upgraded but not the database - need to upgrade - _logger.LogDebug("Has not reached the final upgrade step, need to upgrade Umbraco."); - Level = RuntimeLevel.Upgrade; - Reason = RuntimeLevelReason.UpgradeMigrations; - } - - public void Configure(RuntimeLevel level, RuntimeLevelReason reason) - { - Level = level; - Reason = reason; } private bool EnsureUmbracoUpgradeState(IUmbracoDatabaseFactory databaseFactory, ILogger logger) @@ -183,5 +259,36 @@ namespace Umbraco.Core return CurrentMigrationState == FinalMigrationState; } + private bool DoesUmbracoRequireUpgrade(IUmbracoDatabase database) + { + var upgrader = new Upgrader(new UmbracoPlan(_umbracoVersion)); + var stateValueKey = upgrader.StateValueKey; + + CurrentMigrationState = database.GetFromKeyValueTable(stateValueKey); + FinalMigrationState = upgrader.Plan.FinalState; + + _logger.LogDebug("Final upgrade state is {FinalMigrationState}, database contains {DatabaseState}", FinalMigrationState, CurrentMigrationState ?? ""); + + return CurrentMigrationState != FinalMigrationState; + } + + private bool TryDbConnect(IUmbracoDatabaseFactory databaseFactory) + { + // anything other than install wants a database - see if we can connect + // (since this is an already existing database, assume localdb is ready) + bool canConnect; + var tries = _globalSettings.InstallMissingDatabase ? 2 : 5; + for (var i = 0; ;) + { + canConnect = databaseFactory.CanConnect; + if (canConnect || ++i == tries) break; + _logger.LogDebug("Could not immediately connect to database, trying again."); + Thread.Sleep(1000); + } + + return canConnect; + } + + } } diff --git a/src/Umbraco.Infrastructure/WebAssets/JsInitialize.js b/src/Umbraco.Infrastructure/WebAssets/JsInitialize.js index ea9e4620c8..d7ede6dfa6 100644 --- a/src/Umbraco.Infrastructure/WebAssets/JsInitialize.js +++ b/src/Umbraco.Infrastructure/WebAssets/JsInitialize.js @@ -35,6 +35,8 @@ 'lib/umbraco/NamespaceManager.js', 'lib/umbraco/LegacySpeechBubble.js', + 'js/utilities.js', + 'js/app.js', 'js/umbraco.resources.js', @@ -44,5 +46,5 @@ 'js/umbraco.interceptors.js', 'js/umbraco.controllers.js', 'js/routes.js', - 'js/init.js' + 'js/init.js' ] diff --git a/src/Umbraco.Infrastructure/WebAssets/PreviewInitialize.js b/src/Umbraco.Infrastructure/WebAssets/PreviewInitialize.js index 45ee39eefc..c19f99c02a 100644 --- a/src/Umbraco.Infrastructure/WebAssets/PreviewInitialize.js +++ b/src/Umbraco.Infrastructure/WebAssets/PreviewInitialize.js @@ -3,6 +3,7 @@ 'lib/angular/angular.js', 'lib/underscore/underscore-min.js', 'lib/umbraco/Extensions.js', + 'js/utilities.js', 'js/app.js', 'js/umbraco.resources.js', 'js/umbraco.services.js', diff --git a/src/Umbraco.Tests.Common/Builders/ConfigurationEditorBuilder.cs b/src/Umbraco.Tests.Common/Builders/ConfigurationEditorBuilder.cs index 5c9459bf47..2d8a93e772 100644 --- a/src/Umbraco.Tests.Common/Builders/ConfigurationEditorBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/ConfigurationEditorBuilder.cs @@ -23,7 +23,7 @@ namespace Umbraco.Tests.Common.Builders public override IConfigurationEditor Build() { - IDictionary defaultConfiguration = _defaultConfiguration ?? new Dictionary(); + IDictionary defaultConfiguration = _defaultConfiguration ?? new Dictionary(); return new ConfigurationEditor() { diff --git a/src/Umbraco.Tests.Common/Builders/ContentBuilder.cs b/src/Umbraco.Tests.Common/Builders/ContentBuilder.cs index bd7e3b5b3f..715b504d71 100644 --- a/src/Umbraco.Tests.Common/Builders/ContentBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/ContentBuilder.cs @@ -220,7 +220,6 @@ namespace Umbraco.Tests.Common.Builders .WithName(name) .WithParent(parent); - if (!(culture is null)) { builder = builder.WithCultureName(culture, name); diff --git a/src/Umbraco.Tests.Common/Builders/ContentPropertyBasicBuilder.cs b/src/Umbraco.Tests.Common/Builders/ContentPropertyBasicBuilder.cs index f9ad509be4..a9ff520228 100644 --- a/src/Umbraco.Tests.Common/Builders/ContentPropertyBasicBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/ContentPropertyBasicBuilder.cs @@ -13,7 +13,8 @@ namespace Umbraco.Tests.Common.Builders private string _alias; private object _value; - public ContentPropertyBasicBuilder(TParent parentBuilder) : base(parentBuilder) + public ContentPropertyBasicBuilder(TParent parentBuilder) + : base(parentBuilder) { } diff --git a/src/Umbraco.Tests.Common/Builders/ContentTypeSortBuilder.cs b/src/Umbraco.Tests.Common/Builders/ContentTypeSortBuilder.cs index b1e3c494f1..3e7c886623 100644 --- a/src/Umbraco.Tests.Common/Builders/ContentTypeSortBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/ContentTypeSortBuilder.cs @@ -23,7 +23,8 @@ namespace Umbraco.Tests.Common.Builders { } - public ContentTypeSortBuilder(ContentTypeBuilder parentBuilder) : base(parentBuilder) + public ContentTypeSortBuilder(ContentTypeBuilder parentBuilder) + : base(parentBuilder) { } diff --git a/src/Umbraco.Tests.Common/Builders/DataEditorBuilder.cs b/src/Umbraco.Tests.Common/Builders/DataEditorBuilder.cs index a600d2d962..b4db018322 100644 --- a/src/Umbraco.Tests.Common/Builders/DataEditorBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/DataEditorBuilder.cs @@ -48,8 +48,7 @@ namespace Umbraco.Tests.Common.Builders Mock.Of(), Mock.Of(), Mock.Of(), - Mock.Of() - ) + Mock.Of()) { DefaultConfiguration = defaultConfiguration, ExplicitConfigurationEditor = explicitConfigurationEditor, diff --git a/src/Umbraco.Tests.Common/Builders/DataValueEditorBuilder.cs b/src/Umbraco.Tests.Common/Builders/DataValueEditorBuilder.cs index 61f6c3df78..70a8e2c706 100644 --- a/src/Umbraco.Tests.Common/Builders/DataValueEditorBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/DataValueEditorBuilder.cs @@ -58,8 +58,7 @@ namespace Umbraco.Tests.Common.Builders Mock.Of(), Mock.Of(), Mock.Of(), - Mock.Of() - ) + Mock.Of()) { Configuration = configuration, View = view, diff --git a/src/Umbraco.Tests.Common/Builders/Interfaces/IWithLoginBuilder.cs b/src/Umbraco.Tests.Common/Builders/Interfaces/IWithLoginBuilder.cs index 5b844869f0..8ab04bcc3f 100644 --- a/src/Umbraco.Tests.Common/Builders/Interfaces/IWithLoginBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/Interfaces/IWithLoginBuilder.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + namespace Umbraco.Tests.Common.Builders.Interfaces { public interface IWithLoginBuilder diff --git a/src/Umbraco.Tests.Common/Extensions/ContentBaseExtensions.cs b/src/Umbraco.Tests.Common/Extensions/ContentBaseExtensions.cs index c442efe334..148bd467db 100644 --- a/src/Umbraco.Tests.Common/Extensions/ContentBaseExtensions.cs +++ b/src/Umbraco.Tests.Common/Extensions/ContentBaseExtensions.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Reflection; using Umbraco.Core.Models; namespace Umbraco.Tests.Testing @@ -12,16 +16,21 @@ namespace Umbraco.Tests.Testing public static void PropertyValues(this IContentBase content, object value, string culture = null, string segment = null) { if (value == null) + { throw new Exception("No properties has been passed in"); + } - var propertyInfos = value.GetType().GetProperties(); - foreach (var propertyInfo in propertyInfos) + PropertyInfo[] propertyInfos = value.GetType().GetProperties(); + foreach (PropertyInfo propertyInfo in propertyInfos) { if (!content.Properties.TryGetValue(propertyInfo.Name, out var property)) + { throw new Exception($"The property alias {propertyInfo.Name} is not valid, because no PropertyType with this alias exists"); + } property.SetValue(propertyInfo.GetValue(value, null), culture, segment); - //Update item with newly added value + + // Update item with newly added value content.Properties.Add(property); } } diff --git a/src/Umbraco.Tests.Common/Published/PublishedSnapshotTestObjects.cs b/src/Umbraco.Tests.Common/Published/PublishedSnapshotTestObjects.cs index 1c618380a0..2fb6c305fb 100644 --- a/src/Umbraco.Tests.Common/Published/PublishedSnapshotTestObjects.cs +++ b/src/Umbraco.Tests.Common/Published/PublishedSnapshotTestObjects.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using Moq; using Umbraco.Core; using Umbraco.Core.Models.PublishedContent; @@ -7,13 +10,13 @@ namespace Umbraco.Tests.Published { public class PublishedSnapshotTestObjects { - [PublishedModel("element1")] public class TestElementModel1 : PublishedElementModel { public TestElementModel1(IPublishedElement content, IPublishedValueFallback fallback) : base(content) - { } + { + } public string Prop1 => this.Value(Mock.Of(), "prop1"); } @@ -23,7 +26,8 @@ namespace Umbraco.Tests.Published { public TestElementModel2(IPublishedElement content, IPublishedValueFallback fallback) : base(content) - { } + { + } public IEnumerable Prop2 => this.Value>(Mock.Of(), "prop2"); } @@ -33,7 +37,8 @@ namespace Umbraco.Tests.Published { public TestContentModel1(IPublishedContent content, IPublishedValueFallback fallback) : base(content) - { } + { + } public string Prop1 => this.Value(Mock.Of(), "prop1"); } @@ -43,10 +48,10 @@ namespace Umbraco.Tests.Published { public TestContentModel2(IPublishedContent content, IPublishedValueFallback fallback) : base(content) - { } + { + } public IEnumerable Prop2 => this.Value>(Mock.Of(), "prop2"); } - } } diff --git a/src/Umbraco.Tests.Common/TestClone.cs b/src/Umbraco.Tests.Common/TestClone.cs index 5fd0aa30e2..4aa957e376 100644 --- a/src/Umbraco.Tests.Common/TestClone.cs +++ b/src/Umbraco.Tests.Common/TestClone.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Umbraco.Core.Models; namespace Umbraco.Tests.Common @@ -11,18 +14,13 @@ namespace Umbraco.Tests.Common IsClone = true; } - public TestClone() - { - Id = Guid.NewGuid(); - } + public TestClone() => Id = Guid.NewGuid(); public Guid Id { get; } + public bool IsClone { get; } - public object DeepClone() - { - return new TestClone(Id); - } + public object DeepClone() => new TestClone(Id); /// /// Indicates whether the current object is equal to another object of the same type. @@ -33,8 +31,16 @@ namespace Umbraco.Tests.Common /// An object to compare with this object. public bool Equals(TestClone other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (other is null) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Id.Equals(other.Id); } @@ -47,9 +53,21 @@ namespace Umbraco.Tests.Common /// The object to compare with the current object. public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; + if (obj is null) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != GetType()) + { + return false; + } + return Equals((TestClone)obj); } @@ -59,19 +77,10 @@ namespace Umbraco.Tests.Common /// /// A hash code for the current object. /// - public override int GetHashCode() - { - return Id.GetHashCode(); - } + public override int GetHashCode() => Id.GetHashCode(); - public static bool operator ==(TestClone left, TestClone right) - { - return Equals(left, right); - } + public static bool operator ==(TestClone left, TestClone right) => Equals(left, right); - public static bool operator !=(TestClone left, TestClone right) - { - return Equals(left, right) == false; - } + public static bool operator !=(TestClone left, TestClone right) => Equals(left, right) == false; } } diff --git a/src/Umbraco.Tests.Common/TestDefaultCultureAccessor.cs b/src/Umbraco.Tests.Common/TestDefaultCultureAccessor.cs index e1bec33c94..77b3793f26 100644 --- a/src/Umbraco.Tests.Common/TestDefaultCultureAccessor.cs +++ b/src/Umbraco.Tests.Common/TestDefaultCultureAccessor.cs @@ -1,4 +1,7 @@ -using Umbraco.Web.PublishedCache; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Web.PublishedCache; namespace Umbraco.Tests.Common { diff --git a/src/Umbraco.Tests.Common/TestHelperBase.cs b/src/Umbraco.Tests.Common/TestHelperBase.cs index ed3e28ee21..b7ad1e7f52 100644 --- a/src/Umbraco.Tests.Common/TestHelperBase.cs +++ b/src/Umbraco.Tests.Common/TestHelperBase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.IO; using System.Reflection; @@ -10,21 +13,18 @@ using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Diagnostics; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; -using Umbraco.Net; using Umbraco.Core.Persistence; using Umbraco.Core.Serialization; using Umbraco.Core.Strings; +using Umbraco.Net; +using Umbraco.Tests.Common.TestHelpers; using Umbraco.Web; using Umbraco.Web.Routing; -using Umbraco.Tests.Common.Builders; -using System.Runtime.InteropServices; -using Umbraco.Tests.Common.TestHelpers; namespace Umbraco.Tests.Common { @@ -46,16 +46,14 @@ namespace Umbraco.Tests.Common public ITypeFinder GetTypeFinder() => _typeFinder; - public TypeLoader GetMockedTypeLoader() - { - return new TypeLoader(Mock.Of(), Mock.Of(), new DirectoryInfo(GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of>(), Mock.Of()); - } + public TypeLoader GetMockedTypeLoader() => + new TypeLoader(Mock.Of(), Mock.Of(), new DirectoryInfo(GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of>(), Mock.Of()); - // public Configs GetConfigs() => GetConfigsFactory().Create(); + //// public Configs GetConfigs() => GetConfigsFactory().Create(); public abstract IBackOfficeInfo GetBackOfficeInfo(); - //public IConfigsFactory GetConfigsFactory() => new ConfigsFactory(); + //// public IConfigsFactory GetConfigsFactory() => new ConfigsFactory(); /// /// Gets the working directory of the test project. @@ -64,24 +62,36 @@ namespace Umbraco.Tests.Common { get { - if (_workingDir != null) return _workingDir; + if (_workingDir != null) + { + return _workingDir; + } var dir = Path.Combine(Assembly.GetExecutingAssembly().GetRootDirectorySafe(), "TEMP"); if (!Directory.Exists(dir)) + { Directory.CreateDirectory(dir); + } + _workingDir = dir; return _workingDir; } } public IShortStringHelper ShortStringHelper { get; } = new DefaultShortStringHelper(new DefaultShortStringHelperConfig()); + public IJsonSerializer JsonSerializer { get; } = new JsonNetSerializer(); + public IVariationContextAccessor VariationContextAccessor { get; } = new TestVariationContextAccessor(); + public abstract IDbProviderFactoryCreator DbProviderFactoryCreator { get; } + public abstract IBulkSqlInsertProvider BulkSqlInsertProvider { get; } + public abstract IMarchal Marchal { get; } - public CoreDebugSettings CoreDebugSettings { get; } = new CoreDebugSettings(); + + public CoreDebugSettings CoreDebugSettings { get; } = new CoreDebugSettings(); public IIOHelper IOHelper { @@ -89,7 +99,7 @@ namespace Umbraco.Tests.Common { if (_ioHelper == null) { - var hostingEnvironment = GetHostingEnvironment(); + IHostingEnvironment hostingEnvironment = GetHostingEnvironment(); if (TestEnvironment.IsWindows) { @@ -108,29 +118,35 @@ namespace Umbraco.Tests.Common throw new NotSupportedException("Unexpected OS"); } } + return _ioHelper; } } public IMainDom MainDom { get; } + public UriUtility UriUtility { get { if (_uriUtility == null) + { _uriUtility = new UriUtility(GetHostingEnvironment()); + } + return _uriUtility; } } + /// /// Some test files are copied to the /bin (/bin/debug) on build, this is a utility to return their physical path based on a virtual path name /// - /// - /// public virtual string MapPathForTestFiles(string relativePath) { if (!relativePath.StartsWith("~/")) + { throw new ArgumentException("relativePath must start with '~/'", nameof(relativePath)); + } var codeBase = typeof(TestHelperBase).Assembly.CodeBase; var uri = new Uri(codeBase); @@ -142,20 +158,15 @@ namespace Umbraco.Tests.Common public IUmbracoVersion GetUmbracoVersion() => new UmbracoVersion(); - public IServiceCollection GetRegister() - { - return new ServiceCollection(); - } + public IServiceCollection GetRegister() => new ServiceCollection(); public abstract IHostingEnvironment GetHostingEnvironment(); + public abstract IApplicationShutdownRegistry GetHostingEnvironmentLifetime(); public abstract IIpResolver GetIpResolver(); - public IRequestCache GetRequestCache() - { - return new DictionaryAppCache(); - } + public IRequestCache GetRequestCache() => new DictionaryAppCache(); public IPublishedUrlProvider GetPublishedUrlProvider() { @@ -168,7 +179,7 @@ namespace Umbraco.Tests.Common { hostingEnv = hostingEnv ?? GetHostingEnvironment(); return new LoggingConfiguration( - Path.Combine(hostingEnv.ApplicationPhysicalPath, "umbraco","logs")); + Path.Combine(hostingEnv.ApplicationPhysicalPath, "umbraco", "logs")); } } } diff --git a/src/Umbraco.Tests.Common/TestHelpers/MockedValueEditors.cs b/src/Umbraco.Tests.Common/TestHelpers/MockedValueEditors.cs index b80a2996ca..9069bdcbf0 100644 --- a/src/Umbraco.Tests.Common/TestHelpers/MockedValueEditors.cs +++ b/src/Umbraco.Tests.Common/TestHelpers/MockedValueEditors.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using Moq; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Serialization; @@ -10,7 +13,7 @@ namespace Umbraco.Tests.TestHelpers.Entities { public static DataValueEditor CreateDataValueEditor(string name) { - var valueType = (ValueTypes.IsValue(name)) ? name : ValueTypes.String; + var valueType = ValueTypes.IsValue(name) ? name : ValueTypes.String; return new DataValueEditor( Mock.Of(), @@ -21,9 +24,7 @@ namespace Umbraco.Tests.TestHelpers.Entities new DataEditorAttribute(name, name, name) { ValueType = valueType - } - - ); + }); } } } diff --git a/src/Umbraco.Tests.Common/TestHelpers/SolidPublishedSnapshot.cs b/src/Umbraco.Tests.Common/TestHelpers/SolidPublishedSnapshot.cs index e7f6cc4442..f14b6633ba 100644 --- a/src/Umbraco.Tests.Common/TestHelpers/SolidPublishedSnapshot.cs +++ b/src/Umbraco.Tests.Common/TestHelpers/SolidPublishedSnapshot.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; @@ -28,20 +31,19 @@ namespace Umbraco.Tests.Common.PublishedContent public IDomainCache Domains => null; - public IDisposable ForcedPreview(bool forcedPreview, Action callback = null) - { - throw new NotImplementedException(); - } + public IDisposable ForcedPreview(bool forcedPreview, Action callback = null) => throw new NotImplementedException(); public void Resync() - { } + { + } public IAppCache SnapshotCache => null; public IAppCache ElementsCache => null; public void Dispose() - { } + { + } } public class SolidPublishedContentCache : PublishedCacheBase, IPublishedContentCache, IPublishedMediaCache @@ -50,121 +52,56 @@ namespace Umbraco.Tests.Common.PublishedContent public SolidPublishedContentCache() : base(false) - { } - - public void Add(SolidPublishedContent content) { - _content[content.Id] = content.CreateModel(Mock.Of()); } - public void Clear() - { - _content.Clear(); - } + public void Add(SolidPublishedContent content) => _content[content.Id] = content.CreateModel(Mock.Of()); - public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) - { - throw new NotImplementedException(); - } + public void Clear() => _content.Clear(); - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) - { - throw new NotImplementedException(); - } + public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) => throw new NotImplementedException(); - public string GetRouteById(bool preview, int contentId, string culture = null) - { - throw new NotImplementedException(); - } + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) => throw new NotImplementedException(); - public string GetRouteById(int contentId, string culture = null) - { - throw new NotImplementedException(); - } + public string GetRouteById(bool preview, int contentId, string culture = null) => throw new NotImplementedException(); - public override IPublishedContent GetById(bool preview, int contentId) - { - return _content.ContainsKey(contentId) ? _content[contentId] : null; - } + public string GetRouteById(int contentId, string culture = null) => throw new NotImplementedException(); - public override IPublishedContent GetById(bool preview, Guid contentId) - { - throw new NotImplementedException(); - } + public override IPublishedContent GetById(bool preview, int contentId) => _content.ContainsKey(contentId) ? _content[contentId] : null; - public override IPublishedContent GetById(bool preview, Udi nodeId) - => throw new NotSupportedException(); + public override IPublishedContent GetById(bool preview, Guid contentId) => throw new NotImplementedException(); - public override bool HasById(bool preview, int contentId) - { - return _content.ContainsKey(contentId); - } + public override IPublishedContent GetById(bool preview, Udi nodeId) => throw new NotSupportedException(); - public override IEnumerable GetAtRoot(bool preview, string culture = null) - { - return _content.Values.Where(x => x.Parent == null); - } + public override bool HasById(bool preview, int contentId) => _content.ContainsKey(contentId); - public override IPublishedContent GetSingleByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } + public override IEnumerable GetAtRoot(bool preview, string culture = null) => _content.Values.Where(x => x.Parent == null); - public override IPublishedContent GetSingleByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } + public override IPublishedContent GetSingleByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) => throw new NotImplementedException(); - public override IEnumerable GetByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } + public override IPublishedContent GetSingleByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) => throw new NotImplementedException(); - public override IEnumerable GetByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } + public override IEnumerable GetByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) => throw new NotImplementedException(); - public override System.Xml.XPath.XPathNavigator CreateNavigator(bool preview) - { - throw new NotImplementedException(); - } + public override IEnumerable GetByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) => throw new NotImplementedException(); - public override System.Xml.XPath.XPathNavigator CreateNodeNavigator(int id, bool preview) - { - throw new NotImplementedException(); - } + public override System.Xml.XPath.XPathNavigator CreateNavigator(bool preview) => throw new NotImplementedException(); - public override bool HasContent(bool preview) - { - return _content.Count > 0; - } + public override System.Xml.XPath.XPathNavigator CreateNodeNavigator(int id, bool preview) => throw new NotImplementedException(); - public override IPublishedContentType GetContentType(int id) - { - throw new NotImplementedException(); - } + public override bool HasContent(bool preview) => _content.Count > 0; - public override IPublishedContentType GetContentType(string alias) - { - throw new NotImplementedException(); - } + public override IPublishedContentType GetContentType(int id) => throw new NotImplementedException(); - public override IPublishedContentType GetContentType(Guid key) - { - throw new NotImplementedException(); - } + public override IPublishedContentType GetContentType(string alias) => throw new NotImplementedException(); - public override IEnumerable GetByContentType(IPublishedContentType contentType) - { - throw new NotImplementedException(); - } + public override IPublishedContentType GetContentType(Guid key) => throw new NotImplementedException(); + + public override IEnumerable GetByContentType(IPublishedContentType contentType) => throw new NotImplementedException(); } public class SolidPublishedContent : IPublishedContent { - #region Constructor - public SolidPublishedContent(IPublishedContentType contentType) { // initialize boring stuff @@ -176,68 +113,67 @@ namespace Umbraco.Tests.Common.PublishedContent ContentType = contentType; } - #endregion - - #region Content - private Dictionary _cultures; - private Dictionary GetCultures() - { - return new Dictionary { { "", new PublishedCultureInfo("", Name, UrlSegment, UpdateDate) } }; - } + private Dictionary GetCultures() => new Dictionary { { string.Empty, new PublishedCultureInfo(string.Empty, Name, UrlSegment, UpdateDate) } }; 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 IReadOnlyDictionary Cultures => _cultures ?? (_cultures = GetCultures()); + public string UrlSegment { 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 PublishedItemType ItemType => PublishedItemType.Content; + public bool IsDraft(string culture = null) => false; + public bool IsPublished(string culture = null) => true; - #endregion - - #region Tree - public int ParentId { get; set; } + public IEnumerable ChildIds { get; set; } public IPublishedContent Parent { get; set; } + public IEnumerable Children { get; set; } + public IEnumerable ChildrenForAllCultures => Children; - #endregion - - #region ContentType - public IPublishedContentType ContentType { get; set; } - #endregion - - #region Properties - public IEnumerable Properties { get; set; } - public IPublishedProperty GetProperty(string alias) - { - return Properties.FirstOrDefault(p => p.Alias.InvariantEquals(alias)); - } + public IPublishedProperty GetProperty(string alias) => Properties.FirstOrDefault(p => p.Alias.InvariantEquals(alias)); public IPublishedProperty GetProperty(string alias, bool recurse) { - var property = GetProperty(alias); - if (recurse == false) return property; + IPublishedProperty property = GetProperty(alias); + if (recurse == false) + { + return property; + } IPublishedContent content = this; while (content != null && (property == null || property.HasValue() == false)) @@ -257,22 +193,28 @@ namespace Umbraco.Tests.Common.PublishedContent return property == null || property.HasValue() == false ? null : property.GetValue(); } } - - #endregion } public class SolidPublishedProperty : IPublishedProperty { public IPublishedPropertyType PropertyType { get; set; } + public string Alias { get; set; } + public object SolidSourceValue { get; set; } + public object SolidValue { get; set; } + public bool SolidHasValue { get; set; } + public object SolidXPathValue { get; set; } public virtual object GetSourceValue(string culture = null, string segment = null) => SolidSourceValue; + public virtual object GetValue(string culture = null, string segment = null) => SolidValue; + public virtual object GetXPathValue(string culture = null, string segment = null) => SolidXPathValue; + public virtual bool HasValue(string culture = null, string segment = null) => SolidHasValue; } @@ -355,13 +297,10 @@ namespace Umbraco.Tests.Common.PublishedContent [PublishedModel("ContentType2")] public class ContentType2 : PublishedContentModel { - #region Plumbing - public ContentType2(IPublishedContent content, IPublishedValueFallback fallback) : base(content) - { } - - #endregion + { + } public int Prop1 => this.Value(Mock.Of(), "prop1"); } @@ -369,20 +308,18 @@ namespace Umbraco.Tests.Common.PublishedContent [PublishedModel("ContentType2Sub")] public class ContentType2Sub : ContentType2 { - #region Plumbing - public ContentType2Sub(IPublishedContent content, IPublishedValueFallback fallback) : base(content, fallback) - { } - - #endregion + { + } } public class PublishedContentStrong1 : PublishedContentModel { public PublishedContentStrong1(IPublishedContent content, IPublishedValueFallback fallback) : base(content) - { } + { + } public int StrongValue => this.Value(Mock.Of(), "strongValue"); } @@ -391,7 +328,8 @@ namespace Umbraco.Tests.Common.PublishedContent { public PublishedContentStrong1Sub(IPublishedContent content, IPublishedValueFallback fallback) : base(content, fallback) - { } + { + } public int AnotherValue => this.Value(Mock.Of(), "anotherValue"); } @@ -400,7 +338,8 @@ namespace Umbraco.Tests.Common.PublishedContent { public PublishedContentStrong2(IPublishedContent content, IPublishedValueFallback fallback) : base(content) - { } + { + } public int StrongValue => this.Value(Mock.Of(), "strongValue"); } @@ -415,9 +354,18 @@ namespace Umbraco.Tests.Common.PublishedContent var jsonSerializer = new JsonNetSerializer(); var dataTypeServiceMock = new Mock(); - var dataType = new DataType(new VoidEditor(Mock.Of(), dataTypeServiceMock.Object, - Mock.Of(), Mock.Of(), Mock.Of(), jsonSerializer), configurationEditorJsonSerializer) - { Id = 666 }; + var dataType = new DataType( + new VoidEditor( + Mock.Of(), + dataTypeServiceMock.Object, + Mock.Of(), + Mock.Of(), + Mock.Of(), + jsonSerializer), + configurationEditorJsonSerializer) + { + Id = 666 + }; dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield); var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeServiceMock.Object); @@ -426,23 +374,27 @@ namespace Umbraco.Tests.Common.PublishedContent public AutoPublishedContentType(Guid key, int id, string alias, IEnumerable propertyTypes) : base(key, id, alias, PublishedItemType.Content, Enumerable.Empty(), propertyTypes, ContentVariation.Nothing) - { } + { + } public AutoPublishedContentType(Guid key, int id, string alias, Func> propertyTypes) : base(key, id, alias, PublishedItemType.Content, Enumerable.Empty(), propertyTypes, ContentVariation.Nothing) - { } + { + } public AutoPublishedContentType(Guid key, int id, string alias, IEnumerable compositionAliases, IEnumerable propertyTypes) : base(key, id, alias, PublishedItemType.Content, compositionAliases, propertyTypes, ContentVariation.Nothing) - { } + { + } public AutoPublishedContentType(Guid key, int id, string alias, IEnumerable compositionAliases, Func> propertyTypes) : base(key, id, alias, PublishedItemType.Content, compositionAliases, propertyTypes, ContentVariation.Nothing) - { } + { + } public override IPublishedPropertyType GetPropertyType(string alias) { - var propertyType = base.GetPropertyType(alias); + IPublishedPropertyType propertyType = base.GetPropertyType(alias); return propertyType ?? Default; } } diff --git a/src/Umbraco.Tests.Common/TestHelpers/StringNewlineExtensions.cs b/src/Umbraco.Tests.Common/TestHelpers/StringNewlineExtensions.cs index 6de58f84b2..70e84a41c2 100644 --- a/src/Umbraco.Tests.Common/TestHelpers/StringNewlineExtensions.cs +++ b/src/Umbraco.Tests.Common/TestHelpers/StringNewlineExtensions.cs @@ -1,4 +1,7 @@ -namespace Umbraco.Tests +// Copyright (c) Umbraco. +// See LICENSE for more details. + +namespace Umbraco.Tests { public static class StringNewLineExtensions { @@ -9,8 +12,12 @@ /// The filtered text. public static string Lf(this string text) { - if (string.IsNullOrEmpty(text)) return text; - text = text.Replace("\r", ""); // remove CR + if (string.IsNullOrEmpty(text)) + { + return text; + } + + text = text.Replace("\r", string.Empty); // remove CR return text; } @@ -21,8 +28,12 @@ /// The filtered text. public static string CrLf(this string text) { - if (string.IsNullOrEmpty(text)) return text; - text = text.Replace("\r", ""); // remove CR + if (string.IsNullOrEmpty(text)) + { + return text; + } + + text = text.Replace("\r", string.Empty); // remove CR text = text.Replace("\n", "\r\n"); // add CRLF everywhere return text; } @@ -34,7 +45,11 @@ /// The filtered text. public static string NoCrLf(this string text) { - if (string.IsNullOrEmpty(text)) return text; + if (string.IsNullOrEmpty(text)) + { + return text; + } + text = text.Replace("\r\n", " "); // remove CRLF text = text.Replace("\r", " "); // remove CR text = text.Replace("\n", " "); // remove LF diff --git a/src/Umbraco.Tests.Common/TestHelpers/Stubs/TestProfiler.cs b/src/Umbraco.Tests.Common/TestHelpers/Stubs/TestProfiler.cs index ea0f9cc44f..478fde32d4 100644 --- a/src/Umbraco.Tests.Common/TestHelpers/Stubs/TestProfiler.cs +++ b/src/Umbraco.Tests.Common/TestHelpers/Stubs/TestProfiler.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using StackExchange.Profiling; using StackExchange.Profiling.SqlFormatters; using Umbraco.Core.Logging; @@ -7,41 +10,37 @@ namespace Umbraco.Tests.TestHelpers.Stubs { public class TestProfiler : IProfiler { - public static void Enable() - { - _enabled = true; - } + public static void Enable() => s_enabled = true; - public static void Disable() - { - _enabled = false; - } + public static void Disable() => s_enabled = false; - private static bool _enabled; + private static bool s_enabled; - public IDisposable Step(string name) - { - return _enabled ? MiniProfiler.Current.Step(name) : null; - } + public IDisposable Step(string name) => s_enabled ? MiniProfiler.Current.Step(name) : null; public void Start() { - if (_enabled == false) return; + if (s_enabled == false) + { + return; + } - //see https://miniprofiler.com/dotnet/AspDotNet + // See https://miniprofiler.com/dotnet/AspDotNet MiniProfiler.Configure(new MiniProfilerOptions { SqlFormatter = new SqlServerFormatter(), StackMaxLength = 5000, }); - + MiniProfiler.StartNew(); } public void Stop(bool discardResults = false) { - if (_enabled) + if (s_enabled) + { MiniProfiler.Current.Stop(discardResults); + } } } } diff --git a/src/Umbraco.Tests.Common/TestHelpers/TestDatabase.cs b/src/Umbraco.Tests.Common/TestHelpers/TestDatabase.cs index d1e5669100..3f388c8612 100644 --- a/src/Umbraco.Tests.Common/TestHelpers/TestDatabase.cs +++ b/src/Umbraco.Tests.Common/TestHelpers/TestDatabase.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections; using System.Collections.Generic; using System.Data; @@ -9,6 +12,7 @@ using Moq; using NPoco; using NPoco.DatabaseTypes; using NPoco.Linq; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.SqlSyntax; @@ -41,22 +45,13 @@ namespace Umbraco.Tests.Testing /// public class Operation { - public Operation(string text) - { - Text = text; - } + public Operation(string text) => Text = text; public Operation(string text, string sql) - : this(text) - { - Sql = sql; - } + : this(text) => Sql = sql; public Operation(string text, string sql, params object[] args) - : this(text, sql) - { - Args = args; - } + : this(text, sql) => Args = args; /// /// Gets the operation text. @@ -79,89 +74,68 @@ namespace Umbraco.Tests.Testing /// public List Operations { get; } = new List(); - #region Connection, Transaction and Stuff - public void Dispose() - { } - - public IDatabase OpenSharedConnection() { - return this; } + public IDatabase OpenSharedConnection() => this; + public void CloseSharedConnection() - { } + { + } public int OneTimeCommandTimeout { get; set; } + public MapperCollection Mappers { get; set; } + public IPocoDataFactory PocoDataFactory { get; set; } + public DatabaseType DatabaseType { get; } + public List Interceptors { get; } + public string ConnectionString { get; } public DbConnection Connection { get; } + public DbTransaction Transaction { get; } + public IDictionary Data { get; } + public ISqlContext SqlContext { get; } + public string InstanceId { get; } + public bool InTransaction { get; } + public bool EnableSqlCount { get; set; } + public int SqlCount { get; } + public int BulkInsertRecords(IEnumerable records) => throw new NotImplementedException(); + public bool IsUmbracoInstalled() => true; - public DbParameter CreateParameter() - { - throw new NotImplementedException(); - } + public DatabaseSchemaResult ValidateSchema() => throw new NotImplementedException(); - public void AddParameter(DbCommand cmd, object value) - { - throw new NotImplementedException(); - } + public DbParameter CreateParameter() => throw new NotImplementedException(); - public DbCommand CreateCommand(DbConnection connection, CommandType commandType, string sql, params object[] args) - { - throw new NotImplementedException(); - } + public void AddParameter(DbCommand cmd, object value) => throw new NotImplementedException(); - public ITransaction GetTransaction() - { - throw new NotImplementedException(); - } + public DbCommand CreateCommand(DbConnection connection, CommandType commandType, string sql, params object[] args) => throw new NotImplementedException(); - public ITransaction GetTransaction(IsolationLevel isolationLevel) - { - throw new NotImplementedException(); - } + public ITransaction GetTransaction() => throw new NotImplementedException(); - public void SetTransaction(DbTransaction tran) - { - throw new NotImplementedException(); - } + public ITransaction GetTransaction(IsolationLevel isolationLevel) => throw new NotImplementedException(); - public void BeginTransaction() - { - Operations.Add(new Operation("BEGIN")); - } + public void SetTransaction(DbTransaction tran) => throw new NotImplementedException(); - public void BeginTransaction(IsolationLevel isolationLevel) - { - Operations.Add(new Operation("BEGIN " + isolationLevel)); - } + public void BeginTransaction() => Operations.Add(new Operation("BEGIN")); - public void AbortTransaction() - { - Operations.Add(new Operation("ABORT")); - } + public void BeginTransaction(IsolationLevel isolationLevel) => Operations.Add(new Operation("BEGIN " + isolationLevel)); - public void CompleteTransaction() - { - Operations.Add(new Operation("COMMIT")); - } + public void AbortTransaction() => Operations.Add(new Operation("ABORT")); - #endregion - - #region Writes + public void CompleteTransaction() => Operations.Add(new Operation("COMMIT")); public int Execute(string sql, params object[] args) { @@ -199,578 +173,238 @@ namespace Umbraco.Tests.Testing return default; } - public Task ExecuteScalarAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } + public Task ExecuteScalarAsync(string sql, params object[] args) => throw new NotImplementedException(); - public Task ExecuteScalarAsync(Sql sql) - { - throw new NotImplementedException(); - } + public Task ExecuteScalarAsync(Sql sql) => throw new NotImplementedException(); - public Task ExecuteAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } + public Task ExecuteAsync(string sql, params object[] args) => throw new NotImplementedException(); - public Task ExecuteAsync(Sql sql) - { - throw new NotImplementedException(); - } + public Task ExecuteAsync(Sql sql) => throw new NotImplementedException(); - public object Insert(string tableName, string primaryKeyName, bool autoIncrement, T poco) - { - throw new NotImplementedException(); - } + public object Insert(string tableName, string primaryKeyName, bool autoIncrement, T poco) => throw new NotImplementedException(); - public object Insert(string tableName, string primaryKeyName, T poco) - { - throw new NotImplementedException(); - } + public object Insert(string tableName, string primaryKeyName, T poco) => throw new NotImplementedException(); - public object Insert(T poco) - { - throw new NotImplementedException(); - } + public object Insert(T poco) => throw new NotImplementedException(); - public Task InsertAsync(T poco) - { - throw new NotImplementedException(); - } + public Task InsertAsync(T poco) => throw new NotImplementedException(); public Task InsertBatchAsync(IEnumerable pocos, BatchOptions options = null) => throw new NotImplementedException(); - public Task UpdateAsync(object poco) - { - throw new NotImplementedException(); - } + public Task UpdateAsync(object poco) => throw new NotImplementedException(); - public Task UpdateAsync(object poco, IEnumerable columns) - { - throw new NotImplementedException(); - } + public Task UpdateAsync(object poco, IEnumerable columns) => throw new NotImplementedException(); - public Task UpdateAsync(T poco, Expression> fields) - { - throw new NotImplementedException(); - } + public Task UpdateAsync(T poco, Expression> fields) => throw new NotImplementedException(); public Task UpdateBatchAsync(IEnumerable> pocos, BatchOptions options = null) => throw new NotImplementedException(); - public Task DeleteAsync(object poco) - { - throw new NotImplementedException(); - } + public Task DeleteAsync(object poco) => throw new NotImplementedException(); public IAsyncUpdateQueryProvider UpdateManyAsync() => throw new NotImplementedException(); public IAsyncDeleteQueryProvider DeleteManyAsync() => throw new NotImplementedException(); - public void InsertBulk(IEnumerable pocos) - { - throw new NotImplementedException(); - } + public void InsertBulk(IEnumerable pocos) => throw new NotImplementedException(); int IDatabase.InsertBatch(IEnumerable pocos, BatchOptions options) => throw new NotImplementedException(); - public void InsertBatch(IEnumerable pocos, BatchOptions options = null) - { - throw new NotImplementedException(); - } + public void InsertBatch(IEnumerable pocos, BatchOptions options = null) => throw new NotImplementedException(); - public int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue) - { - throw new NotImplementedException(); - } + public int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue) => throw new NotImplementedException(); - public int Update(string tableName, string primaryKeyName, object poco) - { - throw new NotImplementedException(); - } + public int Update(string tableName, string primaryKeyName, object poco) => throw new NotImplementedException(); - public int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue, IEnumerable columns) - { - throw new NotImplementedException(); - } + public int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue, IEnumerable columns) => throw new NotImplementedException(); - public int Update(string tableName, string primaryKeyName, object poco, IEnumerable columns) - { - throw new NotImplementedException(); - } + public int Update(string tableName, string primaryKeyName, object poco, IEnumerable columns) => throw new NotImplementedException(); - public int Update(object poco, IEnumerable columns) - { - throw new NotImplementedException(); - } + public int Update(object poco, IEnumerable columns) => throw new NotImplementedException(); - public int Update(object poco, object primaryKeyValue, IEnumerable columns) - { - throw new NotImplementedException(); - } + public int Update(object poco, object primaryKeyValue, IEnumerable columns) => throw new NotImplementedException(); - public int Update(object poco) - { - throw new NotImplementedException(); - } + public int Update(object poco) => throw new NotImplementedException(); - public int Update(T poco, Expression> fields) - { - throw new NotImplementedException(); - } + public int Update(T poco, Expression> fields) => throw new NotImplementedException(); - public int Update(object poco, object primaryKeyValue) - { - throw new NotImplementedException(); - } + public int Update(object poco, object primaryKeyValue) => throw new NotImplementedException(); - public int Update(string sql, params object[] args) - { - throw new NotImplementedException(); - } + public int Update(string sql, params object[] args) => throw new NotImplementedException(); - public int Update(Sql sql) - { - throw new NotImplementedException(); - } + public int Update(Sql sql) => throw new NotImplementedException(); public int UpdateBatch(IEnumerable> pocos, BatchOptions options = null) => throw new NotImplementedException(); - public IUpdateQueryProvider UpdateMany() - { - throw new NotImplementedException(); - } - - public int Delete(string tableName, string primaryKeyName, object poco) - { - throw new NotImplementedException(); - } - - public int Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue) - { - throw new NotImplementedException(); - } - - public int Delete(object poco) - { - throw new NotImplementedException(); - } - - public int Delete(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public int Delete(Sql sql) - { - throw new NotImplementedException(); - } - - public int Delete(object pocoOrPrimaryKey) - { - throw new NotImplementedException(); - } - - public IDeleteQueryProvider DeleteMany() - { - throw new NotImplementedException(); - } - - public void Save(T poco) - { - throw new NotImplementedException(); - } - - public bool IsNew(T poco) - { - throw new NotImplementedException(); - } - - #endregion - - #region Reads (not implemented) - - public List Fetch(Type type, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public List Fetch(Type type, Sql Sql) - { - throw new NotImplementedException(); - } - - public IEnumerable Query(Type type, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public IEnumerable Query(Type type, Sql Sql) - { - throw new NotImplementedException(); - } - - public List Fetch() - { - throw new NotImplementedException(); - } - - public List Fetch(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public List Fetch(Sql sql) - { - throw new NotImplementedException(); - } - - public List Fetch(long page, long itemsPerPage, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public List Fetch(long page, long itemsPerPage, Sql sql) - { - throw new NotImplementedException(); - } - - public Page Page(long page, long itemsPerPage, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Page Page(long page, long itemsPerPage, Sql sql) - { - throw new NotImplementedException(); - } - - public List SkipTake(long skip, long take, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public List SkipTake(long skip, long take, Sql sql) - { - throw new NotImplementedException(); - } - - public List FetchOneToMany(Expression> many, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public List FetchOneToMany(Expression> many, Sql sql) - { - throw new NotImplementedException(); - } - - public List FetchOneToMany(Expression> many, Func idFunc, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public List FetchOneToMany(Expression> many, Func idFunc, Sql sql) - { - throw new NotImplementedException(); - } - - public IEnumerable Query(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public IEnumerable Query(Sql sql) - { - throw new NotImplementedException(); - } - - public IQueryProviderWithIncludes Query() - { - throw new NotImplementedException(); - } - - public T SingleById(object primaryKey) - { - throw new NotImplementedException(); - } - - public T Single(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T SingleInto(T instance, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T SingleOrDefaultById(object primaryKey) - { - throw new NotImplementedException(); - } - - public T SingleOrDefault(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T SingleOrDefaultInto(T instance, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T First(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T FirstInto(T instance, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T FirstOrDefault(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T FirstOrDefaultInto(T instance, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public T Single(Sql sql) - { - throw new NotImplementedException(); - } - - public T SingleInto(T instance, Sql sql) - { - throw new NotImplementedException(); - } - - public T SingleOrDefault(Sql sql) - { - throw new NotImplementedException(); - } - - public T SingleOrDefaultInto(T instance, Sql sql) - { - throw new NotImplementedException(); - } - - public T First(Sql sql) - { - throw new NotImplementedException(); - } - - public T FirstInto(T instance, Sql sql) - { - throw new NotImplementedException(); - } - - public T FirstOrDefault(Sql sql) - { - throw new NotImplementedException(); - } - - public T FirstOrDefaultInto(T instance, Sql sql) - { - throw new NotImplementedException(); - } - - public Dictionary Dictionary(Sql Sql) - { - throw new NotImplementedException(); - } - - public Dictionary Dictionary(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public bool Exists(object primaryKey) - { - throw new NotImplementedException(); - } - - public TRet FetchMultiple(Func, List, TRet> cb, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public TRet FetchMultiple(Func, List, List, TRet> cb, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public TRet FetchMultiple(Func, List, List, List, TRet> cb, string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public TRet FetchMultiple(Func, List, TRet> cb, Sql sql) - { - throw new NotImplementedException(); - } - - public TRet FetchMultiple(Func, List, List, TRet> cb, Sql sql) - { - throw new NotImplementedException(); - } - - public TRet FetchMultiple(Func, List, List, List, TRet> cb, Sql sql) - { - throw new NotImplementedException(); - } - - public Tuple, List> FetchMultiple(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Tuple, List, List> FetchMultiple(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Tuple, List, List, List> FetchMultiple(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Tuple, List> FetchMultiple(Sql sql) - { - throw new NotImplementedException(); - } - - public Tuple, List, List> FetchMultiple(Sql sql) - { - throw new NotImplementedException(); - } - - public Tuple, List, List, List> FetchMultiple(Sql sql) - { - throw new NotImplementedException(); - } - - public Task SingleAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Task SingleAsync(Sql sql) - { - throw new NotImplementedException(); - } - - public Task SingleOrDefaultAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Task SingleOrDefaultAsync(Sql sql) - { - throw new NotImplementedException(); - } - - public Task SingleByIdAsync(object primaryKey) - { - throw new NotImplementedException(); - } - - public Task SingleOrDefaultByIdAsync(object primaryKey) - { - throw new NotImplementedException(); - } - - public Task FirstAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Task FirstAsync(Sql sql) - { - throw new NotImplementedException(); - } - - public Task FirstOrDefaultAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Task FirstOrDefaultAsync(Sql sql) - { - throw new NotImplementedException(); - } - - public Task> QueryAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } - - public Task> QueryAsync(Sql sql) - { - throw new NotImplementedException(); - } + public IUpdateQueryProvider UpdateMany() => throw new NotImplementedException(); + + public int Delete(string tableName, string primaryKeyName, object poco) => throw new NotImplementedException(); + + public int Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue) => throw new NotImplementedException(); + + public int Delete(object poco) => throw new NotImplementedException(); + + public int Delete(string sql, params object[] args) => throw new NotImplementedException(); + + public int Delete(Sql sql) => throw new NotImplementedException(); + + public int Delete(object pocoOrPrimaryKey) => throw new NotImplementedException(); + + public IDeleteQueryProvider DeleteMany() => throw new NotImplementedException(); + + public void Save(T poco) => throw new NotImplementedException(); + + public bool IsNew(T poco) => throw new NotImplementedException(); + + public List Fetch(Type type, string sql, params object[] args) => throw new NotImplementedException(); + + public List Fetch(Type type, Sql sql) => throw new NotImplementedException(); + + public IEnumerable Query(Type type, string sql, params object[] args) => throw new NotImplementedException(); + + public IEnumerable Query(Type type, Sql sql) => throw new NotImplementedException(); + + public List Fetch() => throw new NotImplementedException(); + + public List Fetch(string sql, params object[] args) => throw new NotImplementedException(); + + public List Fetch(Sql sql) => throw new NotImplementedException(); + + public List Fetch(long page, long itemsPerPage, string sql, params object[] args) => throw new NotImplementedException(); + + public List Fetch(long page, long itemsPerPage, Sql sql) => throw new NotImplementedException(); + + public Page Page(long page, long itemsPerPage, string sql, params object[] args) => throw new NotImplementedException(); + + public Page Page(long page, long itemsPerPage, Sql sql) => throw new NotImplementedException(); + + public List SkipTake(long skip, long take, string sql, params object[] args) => throw new NotImplementedException(); + + public List SkipTake(long skip, long take, Sql sql) => throw new NotImplementedException(); + + public List FetchOneToMany(Expression> many, string sql, params object[] args) => throw new NotImplementedException(); + + public List FetchOneToMany(Expression> many, Sql sql) => throw new NotImplementedException(); + + public List FetchOneToMany(Expression> many, Func idFunc, string sql, params object[] args) => throw new NotImplementedException(); + + public List FetchOneToMany(Expression> many, Func idFunc, Sql sql) => throw new NotImplementedException(); + + public IEnumerable Query(string sql, params object[] args) => throw new NotImplementedException(); + + public IEnumerable Query(Sql sql) => throw new NotImplementedException(); + + public IQueryProviderWithIncludes Query() => throw new NotImplementedException(); + + public T SingleById(object primaryKey) => throw new NotImplementedException(); + + public T Single(string sql, params object[] args) => throw new NotImplementedException(); + + public T SingleInto(T instance, string sql, params object[] args) => throw new NotImplementedException(); + + public T SingleOrDefaultById(object primaryKey) => throw new NotImplementedException(); + + public T SingleOrDefault(string sql, params object[] args) => throw new NotImplementedException(); + + public T SingleOrDefaultInto(T instance, string sql, params object[] args) => throw new NotImplementedException(); + + public T First(string sql, params object[] args) => throw new NotImplementedException(); + + public T FirstInto(T instance, string sql, params object[] args) => throw new NotImplementedException(); + + public T FirstOrDefault(string sql, params object[] args) => throw new NotImplementedException(); + + public T FirstOrDefaultInto(T instance, string sql, params object[] args) => throw new NotImplementedException(); + + public T Single(Sql sql) => throw new NotImplementedException(); + + public T SingleInto(T instance, Sql sql) => throw new NotImplementedException(); + + public T SingleOrDefault(Sql sql) => throw new NotImplementedException(); + + public T SingleOrDefaultInto(T instance, Sql sql) => throw new NotImplementedException(); + + public T First(Sql sql) => throw new NotImplementedException(); + + public T FirstInto(T instance, Sql sql) => throw new NotImplementedException(); + + public T FirstOrDefault(Sql sql) => throw new NotImplementedException(); + + public T FirstOrDefaultInto(T instance, Sql sql) => throw new NotImplementedException(); + + public Dictionary Dictionary(Sql sql) => throw new NotImplementedException(); + + public Dictionary Dictionary(string sql, params object[] args) => throw new NotImplementedException(); + + public bool Exists(object primaryKey) => throw new NotImplementedException(); + + public TRet FetchMultiple(Func, List, TRet> cb, string sql, params object[] args) => throw new NotImplementedException(); + + public TRet FetchMultiple(Func, List, List, TRet> cb, string sql, params object[] args) => throw new NotImplementedException(); + + public TRet FetchMultiple(Func, List, List, List, TRet> cb, string sql, params object[] args) => throw new NotImplementedException(); + + public TRet FetchMultiple(Func, List, TRet> cb, Sql sql) => throw new NotImplementedException(); + + public TRet FetchMultiple(Func, List, List, TRet> cb, Sql sql) => throw new NotImplementedException(); + + public TRet FetchMultiple(Func, List, List, List, TRet> cb, Sql sql) => throw new NotImplementedException(); + + public Tuple, List> FetchMultiple(string sql, params object[] args) => throw new NotImplementedException(); + + public Tuple, List, List> FetchMultiple(string sql, params object[] args) => throw new NotImplementedException(); + + public Tuple, List, List, List> FetchMultiple(string sql, params object[] args) => throw new NotImplementedException(); + + public Tuple, List> FetchMultiple(Sql sql) => throw new NotImplementedException(); + + public Tuple, List, List> FetchMultiple(Sql sql) => throw new NotImplementedException(); + + public Tuple, List, List, List> FetchMultiple(Sql sql) => throw new NotImplementedException(); + + public Task SingleAsync(string sql, params object[] args) => throw new NotImplementedException(); + + public Task SingleAsync(Sql sql) => throw new NotImplementedException(); + + public Task SingleOrDefaultAsync(string sql, params object[] args) => throw new NotImplementedException(); + + public Task SingleOrDefaultAsync(Sql sql) => throw new NotImplementedException(); + + public Task SingleByIdAsync(object primaryKey) => throw new NotImplementedException(); + + public Task SingleOrDefaultByIdAsync(object primaryKey) => throw new NotImplementedException(); + + public Task FirstAsync(string sql, params object[] args) => throw new NotImplementedException(); + + public Task FirstAsync(Sql sql) => throw new NotImplementedException(); + + public Task FirstOrDefaultAsync(string sql, params object[] args) => throw new NotImplementedException(); + + public Task FirstOrDefaultAsync(Sql sql) => throw new NotImplementedException(); + + public Task> QueryAsync(string sql, params object[] args) => throw new NotImplementedException(); + + public Task> QueryAsync(Sql sql) => throw new NotImplementedException(); public IAsyncQueryProviderWithIncludes QueryAsync() => throw new NotImplementedException(); - public Task> FetchAsync(string sql, params object[] args) - { - throw new NotImplementedException(); - } + public Task> FetchAsync(string sql, params object[] args) => throw new NotImplementedException(); - public Task> FetchAsync(Sql sql) - { - throw new NotImplementedException(); - } + public Task> FetchAsync(Sql sql) => throw new NotImplementedException(); - public Task> FetchAsync() - { - throw new NotImplementedException(); - } + public Task> FetchAsync() => throw new NotImplementedException(); - public Task> PageAsync(long page, long itemsPerPage, string sql, params object[] args) - { - throw new NotImplementedException(); - } + public Task> PageAsync(long page, long itemsPerPage, string sql, params object[] args) => throw new NotImplementedException(); - public Task> PageAsync(long page, long itemsPerPage, Sql sql) - { - throw new NotImplementedException(); - } + public Task> PageAsync(long page, long itemsPerPage, Sql sql) => throw new NotImplementedException(); - public Task> FetchAsync(long page, long itemsPerPage, string sql, params object[] args) - { - throw new NotImplementedException(); - } + public Task> FetchAsync(long page, long itemsPerPage, string sql, params object[] args) => throw new NotImplementedException(); - public Task> FetchAsync(long page, long itemsPerPage, Sql sql) - { - throw new NotImplementedException(); - } + public Task> FetchAsync(long page, long itemsPerPage, Sql sql) => throw new NotImplementedException(); - public Task> SkipTakeAsync(long skip, long take, string sql, params object[] args) - { - throw new NotImplementedException(); - } + public Task> SkipTakeAsync(long skip, long take, string sql, params object[] args) => throw new NotImplementedException(); - public Task> SkipTakeAsync(long skip, long take, Sql sql) - { - throw new NotImplementedException(); - } + public Task> SkipTakeAsync(long skip, long take, Sql sql) => throw new NotImplementedException(); - #endregion - - #region Stuff - - public void BuildPageQueries(long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage) - { - throw new NotImplementedException(); - } - - #endregion + public void BuildPageQueries(long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage) => throw new NotImplementedException(); } } diff --git a/src/Umbraco.Tests.Common/TestHelpers/TestEnvironment.cs b/src/Umbraco.Tests.Common/TestHelpers/TestEnvironment.cs index e5d5d2650e..d0e9fe879f 100644 --- a/src/Umbraco.Tests.Common/TestHelpers/TestEnvironment.cs +++ b/src/Umbraco.Tests.Common/TestHelpers/TestEnvironment.cs @@ -1,4 +1,7 @@ -using System.Runtime.InteropServices; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Runtime.InteropServices; namespace Umbraco.Tests.Common.TestHelpers { @@ -6,8 +9,8 @@ namespace Umbraco.Tests.Common.TestHelpers { public static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); - public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } diff --git a/src/Umbraco.Tests.Common/TestPublishedSnapshotAccessor.cs b/src/Umbraco.Tests.Common/TestPublishedSnapshotAccessor.cs index ed1ba0b5b9..6b2bc69e24 100644 --- a/src/Umbraco.Tests.Common/TestPublishedSnapshotAccessor.cs +++ b/src/Umbraco.Tests.Common/TestPublishedSnapshotAccessor.cs @@ -1,4 +1,7 @@ -using Umbraco.Web.PublishedCache; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Web.PublishedCache; namespace Umbraco.Tests.Common { diff --git a/src/Umbraco.Tests.Common/TestUmbracoContextAccessor.cs b/src/Umbraco.Tests.Common/TestUmbracoContextAccessor.cs index feaf8eafa5..3c88765f44 100644 --- a/src/Umbraco.Tests.Common/TestUmbracoContextAccessor.cs +++ b/src/Umbraco.Tests.Common/TestUmbracoContextAccessor.cs @@ -1,4 +1,7 @@ -using Umbraco.Web; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Web; namespace Umbraco.Tests.Common { diff --git a/src/Umbraco.Tests.Common/TestVariationContextAccessor.cs b/src/Umbraco.Tests.Common/TestVariationContextAccessor.cs index b2a07b74f2..c1ff438b8c 100644 --- a/src/Umbraco.Tests.Common/TestVariationContextAccessor.cs +++ b/src/Umbraco.Tests.Common/TestVariationContextAccessor.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Models.PublishedContent; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Tests.Common { diff --git a/src/Umbraco.Tests.Common/Testing/TestOptionAttributeBase.cs b/src/Umbraco.Tests.Common/Testing/TestOptionAttributeBase.cs index bbfa68778f..9520532eaa 100644 --- a/src/Umbraco.Tests.Common/Testing/TestOptionAttributeBase.cs +++ b/src/Umbraco.Tests.Common/Testing/TestOptionAttributeBase.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -14,41 +17,40 @@ namespace Umbraco.Tests.Testing public static TOptions GetTestOptions(MethodInfo method) where TOptions : TestOptionAttributeBase, new() { - var attr = ((TOptions[]) method.GetCustomAttributes(typeof (TOptions), true)).FirstOrDefault(); - var type = method.DeclaringType; + TOptions attr = ((TOptions[])method.GetCustomAttributes(typeof(TOptions), true)).FirstOrDefault(); + Type type = method.DeclaringType; return Get(type, attr); } public static TOptions GetFixtureOptions(Type type) - where TOptions : TestOptionAttributeBase, new() - { - return Get(type, null); - } + where TOptions : TestOptionAttributeBase, new() => Get(type, null); public static TOptions GetTestOptions() where TOptions : TestOptionAttributeBase, new() { - var test = TestContext.CurrentContext.Test; + TestContext.TestAdapter test = TestContext.CurrentContext.Test; var typeName = test.ClassName; var methodName = test.MethodName; - // this will only get types from whatever is already loaded in the app domain + + // This will only get types from whatever is already loaded in the app domain. var type = Type.GetType(typeName, false); if (type == null) { // automatically add the executing and calling assemblies to the list to scan for this type - var scanAssemblies = ScanAssemblies.Union(new[] {Assembly.GetExecutingAssembly(), Assembly.GetCallingAssembly()}).ToList(); + var scanAssemblies = ScanAssemblies.Union(new[] { Assembly.GetExecutingAssembly(), Assembly.GetCallingAssembly() }).ToList(); type = scanAssemblies .Select(assembly => assembly.GetType(typeName, false)) .FirstOrDefault(x => x != null); if (type == null) - { + { throw new PanicException($"Could not resolve the running test fixture from type name {typeName}.\n" + $"To use base classes from Umbraco.Tests, add your test assembly to TestOptionAttributeBase.ScanAssemblies"); } } - var methodInfo = type.GetMethod(methodName); // what about overloads? - var options = GetTestOptions(methodInfo); + + MethodInfo methodInfo = type.GetMethod(methodName); // what about overloads? + TOptions options = GetTestOptions(methodInfo); return options; } @@ -57,26 +59,34 @@ namespace Umbraco.Tests.Testing { while (type != null && type != typeof(object)) { - var attr2 = ((TOptions[]) type.GetCustomAttributes(typeof (TOptions), true)).FirstOrDefault(); + TOptions attr2 = ((TOptions[])type.GetCustomAttributes(typeof(TOptions), true)).FirstOrDefault(); if (attr2 != null) + { attr = attr == null ? attr2 : attr2.Merge(attr); + } + type = type.BaseType; } + return attr ?? new TOptions(); } private TOptions Merge(TOptions other) where TOptions : TestOptionAttributeBase { - if (other == null) throw new ArgumentNullException(nameof(other)); - if (!(Merge((TestOptionAttributeBase) other) is TOptions merged)) + if (other == null) + { + throw new ArgumentNullException(nameof(other)); + } + + if (!(Merge((TestOptionAttributeBase)other) is TOptions merged)) + { throw new PanicException("Could not merge test options"); + } + return merged; } - protected virtual TestOptionAttributeBase Merge(TestOptionAttributeBase other) - { - return this; - } + protected virtual TestOptionAttributeBase Merge(TestOptionAttributeBase other) => this; } } diff --git a/src/Umbraco.Tests.Common/Testing/UmbracoTestAttribute.cs b/src/Umbraco.Tests.Common/Testing/UmbracoTestAttribute.cs index 4c1101d6f1..b21d8b0614 100644 --- a/src/Umbraco.Tests.Common/Testing/UmbracoTestAttribute.cs +++ b/src/Umbraco.Tests.Common/Testing/UmbracoTestAttribute.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Umbraco.Core; namespace Umbraco.Tests.Testing @@ -15,6 +18,7 @@ namespace Umbraco.Tests.Testing /// Implies Mapper = true (, ResetPluginManager = false). /// public bool WithApplication { get => _withApplication.ValueOrDefault(false); set => _withApplication.Set(value); } + private readonly Settable _withApplication = new Settable(); /// @@ -22,12 +26,14 @@ namespace Umbraco.Tests.Testing /// /// Default is false unless WithApplication is true, in which case default is true. public bool Mapper { get => _mapper.ValueOrDefault(WithApplication); set => _mapper.Set(value); } + private readonly Settable _mapper = new Settable(); /// /// Gets or sets a value indicating whether the LEGACY XML Cache used in tests should bind to repository events /// public bool PublishedRepositoryEvents { get => _publishedRepositoryEvents.ValueOrDefault(false); set => _publishedRepositoryEvents.Set(value); } + private readonly Settable _publishedRepositoryEvents = new Settable(); /// @@ -35,6 +41,7 @@ namespace Umbraco.Tests.Testing /// /// Default is to mock logging. public UmbracoTestOptions.Logger Logger { get => _logger.ValueOrDefault(UmbracoTestOptions.Logger.Mock); set => _logger.Set(value); } + private readonly Settable _logger = new Settable(); /// @@ -42,6 +49,7 @@ namespace Umbraco.Tests.Testing /// /// Default is no database support. public UmbracoTestOptions.Database Database { get => _database.ValueOrDefault(UmbracoTestOptions.Database.None); set => _database.Set(value); } + private readonly Settable _database = new Settable(); /// @@ -49,16 +57,19 @@ namespace Umbraco.Tests.Testing /// /// Default is to use the global tests plugin manager. public UmbracoTestOptions.TypeLoader TypeLoader { get => _typeLoader.ValueOrDefault(UmbracoTestOptions.TypeLoader.Default); set => _typeLoader.Set(value); } - public bool Boot { get => _boot.ValueOrDefault(false); set => _boot.Set(value); } - private readonly Settable _boot = new Settable(); + public bool Boot { get => _boot.ValueOrDefault(false); set => _boot.Set(value); } + + private readonly Settable _boot = new Settable(); private readonly Settable _typeLoader = new Settable(); protected override TestOptionAttributeBase Merge(TestOptionAttributeBase other) { if (!(other is UmbracoTestAttribute attr)) + { throw new ArgumentException(nameof(other)); + } base.Merge(other); _boot.Set(attr.Boot); diff --git a/src/Umbraco.Tests.Common/Testing/UmbracoTestOptions.cs b/src/Umbraco.Tests.Common/Testing/UmbracoTestOptions.cs index eef6e45d7e..477148e300 100644 --- a/src/Umbraco.Tests.Common/Testing/UmbracoTestOptions.cs +++ b/src/Umbraco.Tests.Common/Testing/UmbracoTestOptions.cs @@ -1,4 +1,7 @@ -namespace Umbraco.Tests.Testing +// Copyright (c) Umbraco. +// See LICENSE for more details. + +namespace Umbraco.Tests.Testing { public static class UmbracoTestOptions { @@ -8,10 +11,12 @@ /// pure mocks /// Mock, + /// /// Serilog for tests /// Serilog, + /// /// console logger /// @@ -24,18 +29,22 @@ /// no database /// None, + /// /// new empty database file for the entire fixture /// NewEmptyPerFixture, + /// /// new empty database file per test /// NewEmptyPerTest, + /// /// new database file with schema for the entire fixture /// NewSchemaPerFixture, + /// /// new database file with schema per test /// @@ -48,10 +57,12 @@ /// the default, global type loader for tests /// Default, + /// /// create one type loader for the feature /// PerFixture, + /// /// create one type loader for each test /// diff --git a/src/Umbraco.Tests.Integration/DependencyInjection/UmbracoBuilderExtensions.cs b/src/Umbraco.Tests.Integration/DependencyInjection/UmbracoBuilderExtensions.cs index c1bdf19069..6af99086c8 100644 --- a/src/Umbraco.Tests.Integration/DependencyInjection/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Tests.Integration/DependencyInjection/UmbracoBuilderExtensions.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.IO; using System.Linq; @@ -8,6 +11,7 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration.Models; using Umbraco.Core.DependencyInjection; using Umbraco.Core.Hosting; @@ -66,9 +70,9 @@ namespace Umbraco.Tests.Integration.DependencyInjection /// private static ILocalizedTextService GetLocalizedTextService(IServiceProvider factory) { - var globalSettings = factory.GetRequiredService>(); - var loggerFactory = factory.GetRequiredService(); - var appCaches = factory.GetRequiredService(); + IOptions globalSettings = factory.GetRequiredService>(); + ILoggerFactory loggerFactory = factory.GetRequiredService(); + AppCaches appCaches = factory.GetRequiredService(); var localizedTextService = new LocalizedTextService( new Lazy(() => @@ -79,14 +83,14 @@ namespace Umbraco.Tests.Integration.DependencyInjection { currFolder = currFolder.Parent; } - var netcoreUI = currFolder.GetDirectories("Umbraco.Web.UI.NetCore", SearchOption.TopDirectoryOnly).First(); + + DirectoryInfo netcoreUI = currFolder.GetDirectories("Umbraco.Web.UI.NetCore", SearchOption.TopDirectoryOnly).First(); var mainLangFolder = new DirectoryInfo(Path.Combine(netcoreUI.FullName, globalSettings.Value.UmbracoPath.TrimStart("~/"), "config", "lang")); return new LocalizedTextServiceFileSources( loggerFactory.CreateLogger(), appCaches, mainLangFolder); - }), loggerFactory.CreateLogger()); @@ -110,52 +114,44 @@ namespace Umbraco.Tests.Integration.DependencyInjection private class NoopServerMessenger : IServerMessenger { public NoopServerMessenger() - { } + { + } public void QueueRefresh(ICacheRefresher refresher, TPayload[] payload) { - } public void QueueRefresh(ICacheRefresher refresher, Func getNumericId, params T[] instances) { - } public void QueueRefresh(ICacheRefresher refresher, Func getGuidId, params T[] instances) { - } public void QueueRemove(ICacheRefresher refresher, Func getNumericId, params T[] instances) { - } public void QueueRemove(ICacheRefresher refresher, params int[] numericIds) { - } public void QueueRefresh(ICacheRefresher refresher, params int[] numericIds) { - } public void QueueRefresh(ICacheRefresher refresher, params Guid[] guidIds) { - } public void QueueRefreshAll(ICacheRefresher refresher) { - } public void Sync() { } public void SendMessages() { } } - } } diff --git a/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs b/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs index dc58d3e9e6..cc01a08287 100644 --- a/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs +++ b/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs @@ -1,4 +1,7 @@ -using Microsoft.AspNetCore.Hosting; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -11,15 +14,14 @@ namespace Umbraco.Tests.Integration.Extensions /// /// These services need to be manually added because they do not get added by the generic host /// - /// - /// - /// public static void AddRequiredNetCoreServices(this IServiceCollection services, TestHelper testHelper, IWebHostEnvironment webHostEnvironment) { services.AddSingleton(x => testHelper.GetHttpContextAccessor()); - // the generic host does add IHostEnvironment but not this one because we are not actually in a web context + + // The generic host does add IHostEnvironment but not this one because we are not actually in a web context services.AddSingleton(x => webHostEnvironment); - // replace the IHostEnvironment that generic host created too + + // Replace the IHostEnvironment that generic host created too services.AddSingleton(x => webHostEnvironment); } } diff --git a/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs b/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs index 6e86e97770..4aca5ff98a 100644 --- a/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs +++ b/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Diagnostics; @@ -5,12 +8,16 @@ using System.Text; using NUnit.Framework; using Umbraco.Tests.Integration.Testing; -// this class has NO NAMESPACE -// it applies to the whole assembly - -[SetUpFixture] // ReSharper disable once CheckNamespace -public class TestsSetup + +/// +/// Global setup and teardown. +/// +/// +/// This class has NO NAMESPACE so it applies to the whole assembly. +/// +[SetUpFixture] +public class GlobalSetupTeardown { private Stopwatch _stopwatch; diff --git a/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs b/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs index 9c2da39076..4c698b221d 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections; using System.ComponentModel; using System.Data.Common; @@ -44,22 +47,25 @@ namespace Umbraco.Tests.Integration.Implementations private readonly IHttpContextAccessor _httpContextAccessor; private string _tempWorkingDir; - public TestHelper() : base(typeof(TestHelper).Assembly) + public TestHelper() + : base(typeof(TestHelper).Assembly) { var httpContext = new DefaultHttpContext(); httpContext.Connection.RemoteIpAddress = IPAddress.Parse("127.0.0.1"); _httpContextAccessor = Mock.Of(x => x.HttpContext == httpContext); _ipResolver = new AspNetCoreIpResolver(_httpContextAccessor); - var contentRoot = Assembly.GetExecutingAssembly().GetRootDirectorySafe(); + string contentRoot = Assembly.GetExecutingAssembly().GetRootDirectorySafe(); var hostEnvironment = new Mock(); - // this must be the assembly name for the WebApplicationFactory to work + + // This must be the assembly name for the WebApplicationFactory to work. hostEnvironment.Setup(x => x.ApplicationName).Returns(GetType().Assembly.GetName().Name); hostEnvironment.Setup(x => x.ContentRootPath).Returns(() => contentRoot); hostEnvironment.Setup(x => x.ContentRootFileProvider).Returns(() => new PhysicalFileProvider(contentRoot)); hostEnvironment.Setup(x => x.WebRootPath).Returns(() => WorkingDirectory); hostEnvironment.Setup(x => x.WebRootFileProvider).Returns(() => new PhysicalFileProvider(WorkingDirectory)); - // we also need to expose it as the obsolete interface since netcore's WebApplicationFactory casts it + + // We also need to expose it as the obsolete interface since netcore's WebApplicationFactory casts it. hostEnvironment.As(); _hostEnvironment = hostEnvironment.Object; @@ -69,25 +75,24 @@ namespace Umbraco.Tests.Integration.Implementations ProfilingLogger = new ProfilingLogger(ConsoleLoggerFactory.CreateLogger(), Profiler); } - public override string WorkingDirectory { get { // For Azure Devops we can only store a database in certain locations so we will need to detect if we are running // on a build server and if so we'll use the %temp% path. - if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("System_DefaultWorkingDirectory"))) { - // we are using Azure Devops! + // We are using Azure Devops! + if (_tempWorkingDir != null) + { + return _tempWorkingDir; + } - if (_tempWorkingDir != null) return _tempWorkingDir; - - var temp = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoTemp"); + string temp = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoTemp"); Directory.CreateDirectory(temp); _tempWorkingDir = temp; return _tempWorkingDir; - } else { @@ -99,10 +104,13 @@ namespace Umbraco.Tests.Integration.Implementations public IUmbracoBootPermissionChecker UmbracoBootPermissionChecker { get; } = new TestUmbracoBootPermissionChecker(); - public AppCaches AppCaches { get; } = new AppCaches(NoAppCache.Instance, NoAppCache.Instance, + public AppCaches AppCaches { get; } = new AppCaches( + NoAppCache.Instance, + NoAppCache.Instance, new IsolatedCaches(type => NoAppCache.Instance)); public ILoggerFactory ConsoleLoggerFactory { get; private set; } + public IProfilingLogger ProfilingLogger { get; private set; } public IProfiler Profiler { get; } = new NoopProfiler(); @@ -123,7 +131,7 @@ namespace Umbraco.Tests.Integration.Implementations if (_backOfficeInfo == null) { var globalSettings = new GlobalSettings(); - var mockedOptionsMonitorOfGlobalSettings = Mock.Of>(x => x.CurrentValue == globalSettings); + IOptionsMonitor mockedOptionsMonitorOfGlobalSettings = Mock.Of>(x => x.CurrentValue == globalSettings); _backOfficeInfo = new AspNetCoreBackOfficeInfo(mockedOptionsMonitorOfGlobalSettings); } @@ -148,39 +156,43 @@ namespace Umbraco.Tests.Integration.Implementations /// /// Some test files are copied to the /bin (/bin/debug) on build, this is a utility to return their physical path based on a virtual path name /// - /// - /// public override string MapPathForTestFiles(string relativePath) { if (!relativePath.StartsWith("~/")) + { throw new ArgumentException("relativePath must start with '~/'", nameof(relativePath)); + } - var codeBase = typeof(TestHelperBase).Assembly.CodeBase; + string codeBase = typeof(TestHelperBase).Assembly.CodeBase; var uri = new Uri(codeBase); - var path = uri.LocalPath; - var bin = Path.GetDirectoryName(path); + string path = uri.LocalPath; + string bin = Path.GetDirectoryName(path); return relativePath.Replace("~/", bin + "/"); } - public void AssertPropertyValuesAreEqual(object actual, object expected, string dateTimeFormat = null, Func sorter = null, string[] ignoreProperties = null) + public void AssertPropertyValuesAreEqual(object actual, object expected, Func sorter = null, string[] ignoreProperties = null) { const int dateDeltaMilliseconds = 1000; // 1s - var properties = expected.GetType().GetProperties(); - foreach (var property in properties) + PropertyInfo[] properties = expected.GetType().GetProperties(); + foreach (PropertyInfo property in properties) { - // ignore properties that are attributed with EditorBrowsableState.Never - var att = property.GetCustomAttribute(false); + // Ignore properties that are attributed with EditorBrowsableState.Never. + EditorBrowsableAttribute att = property.GetCustomAttribute(false); if (att != null && att.State == EditorBrowsableState.Never) + { continue; + } - // ignore explicitly ignored properties + // Ignore explicitly ignored properties. if (ignoreProperties != null && ignoreProperties.Contains(property.Name)) + { continue; + } - var actualValue = property.GetValue(actual, null); - var expectedValue = property.GetValue(expected, null); + object actualValue = property.GetValue(actual, null); + object expectedValue = property.GetValue(expected, null); AssertAreEqual(property, expectedValue, actualValue, sorter, dateDeltaMilliseconds); } @@ -188,8 +200,6 @@ namespace Umbraco.Tests.Integration.Implementations private static void AssertListsAreEqual(PropertyInfo property, IEnumerable expected, IEnumerable actual, Func sorter = null, int dateDeltaMilliseconds = 0) { - - if (sorter == null) { // this is pretty hackerific but saves us some code to write @@ -197,7 +207,7 @@ namespace Umbraco.Tests.Integration.Implementations { // semi-generic way of ensuring any collection of IEntity are sorted by Ids for comparison var entities = enumerable.OfType().ToList(); - return entities.Count > 0 ? (IEnumerable) entities.OrderBy(x => x.Id) : entities; + return entities.Count > 0 ? (IEnumerable)entities.OrderBy(x => x.Id) : entities; }; } @@ -205,46 +215,55 @@ namespace Umbraco.Tests.Integration.Implementations var actualListEx = sorter(actual).Cast().ToList(); if (actualListEx.Count != expectedListEx.Count) + { Assert.Fail("Collection {0}.{1} does not match. Expected IEnumerable containing {2} elements but was IEnumerable containing {3} elements", property.PropertyType.Name, property.Name, expectedListEx.Count, actualListEx.Count); + } - for (var i = 0; i < actualListEx.Count; i++) + for (int i = 0; i < actualListEx.Count; i++) + { AssertAreEqual(property, expectedListEx[i], actualListEx[i], sorter, dateDeltaMilliseconds); + } } private static void AssertAreEqual(PropertyInfo property, object expected, object actual, Func sorter = null, int dateDeltaMilliseconds = 0) { - if (!(expected is string) && expected is IEnumerable) + if (!(expected is string) && expected is IEnumerable enumerable) { // sort property collection by alias, not by property ids // on members, built-in properties don't have ids (always zero) if (expected is PropertyCollection) - sorter = e => ((PropertyCollection) e).OrderBy(x => x.Alias); + { + sorter = e => ((PropertyCollection)e).OrderBy(x => x.Alias); + } // compare lists - AssertListsAreEqual(property, (IEnumerable) actual, (IEnumerable) expected, sorter, dateDeltaMilliseconds); + AssertListsAreEqual(property, (IEnumerable)actual, enumerable, sorter, dateDeltaMilliseconds); } else if (expected is DateTime expectedDateTime) { // compare date & time with delta - var actualDateTime = (DateTime) actual; - var delta = (actualDateTime - expectedDateTime).TotalMilliseconds; + var actualDateTime = (DateTime)actual; + double delta = (actualDateTime - expectedDateTime).TotalMilliseconds; Assert.IsTrue(Math.Abs(delta) <= dateDeltaMilliseconds, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expected, actual); } else if (expected is Property expectedProperty) { // compare values - var actualProperty = (Property) actual; - var expectedPropertyValues = expectedProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray(); - var actualPropertyValues = actualProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray(); + var actualProperty = (Property)actual; + IPropertyValue[] expectedPropertyValues = expectedProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray(); + IPropertyValue[] actualPropertyValues = actualProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray(); if (expectedPropertyValues.Length != actualPropertyValues.Length) + { Assert.Fail($"{property.DeclaringType.Name}.{property.Name}: Expected {expectedPropertyValues.Length} but got {actualPropertyValues.Length}."); - for (var i = 0; i < expectedPropertyValues.Length; i++) + } + + for (int i = 0; i < expectedPropertyValues.Length; i++) { // This is not pretty, but since a property value can be a datetime we can't just always compare them as is. // This is made worse by the fact that PublishedValue is not always set, meaning we can't lump it all into the same if block if (expectedPropertyValues[i].EditedValue is DateTime expectedEditDateTime) { - var actualEditDateTime = (DateTime) actualPropertyValues[i].EditedValue; + var actualEditDateTime = (DateTime)actualPropertyValues[i].EditedValue; AssertDateTime(expectedEditDateTime, actualEditDateTime, $"{property.DeclaringType.Name}.{property.Name}: Expected draft value \"{expectedPropertyValues[i].EditedValue}\" but got \"{actualPropertyValues[i].EditedValue}\".", dateDeltaMilliseconds); } else @@ -254,7 +273,7 @@ namespace Umbraco.Tests.Integration.Implementations if (expectedPropertyValues[i].PublishedValue is DateTime expectedPublishDateTime) { - var actualPublishedDateTime = (DateTime) actualPropertyValues[i].PublishedValue; + var actualPublishedDateTime = (DateTime)actualPropertyValues[i].PublishedValue; AssertDateTime(expectedPublishDateTime, actualPublishedDateTime, $"{property.DeclaringType.Name}.{property.Name}: Expected published value \"{expectedPropertyValues[i].PublishedValue}\" but got \"{actualPropertyValues[i].PublishedValue}\".", dateDeltaMilliseconds); } else @@ -266,22 +285,28 @@ namespace Umbraco.Tests.Integration.Implementations else if (expected is IDataEditor expectedEditor) { Assert.IsInstanceOf(actual); - var actualEditor = (IDataEditor) actual; + var actualEditor = (IDataEditor)actual; Assert.AreEqual(expectedEditor.Alias, actualEditor.Alias); + // what else shall we test? } else { // directly compare values - Assert.AreEqual(expected, actual, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, - expected?.ToString() ?? "", actual?.ToString() ?? ""); + Assert.AreEqual( + expected, + actual, + "Property {0}.{1} does not match. Expected: {2} but was: {3}", + property.DeclaringType.Name, + property.Name, + expected?.ToString() ?? "", + actual?.ToString() ?? ""); } } - private static void AssertDateTime(DateTime expected, DateTime actual, string failureMessage, - int dateDeltaMiliseconds = 0) + private static void AssertDateTime(DateTime expected, DateTime actual, string failureMessage, int dateDeltaMiliseconds = 0) { - var delta = (actual - expected).TotalMilliseconds; + double delta = (actual - expected).TotalMilliseconds; Assert.IsTrue(Math.Abs(delta) <= dateDeltaMiliseconds, failureMessage); } @@ -289,32 +314,38 @@ namespace Umbraco.Tests.Integration.Implementations { Try(() => { - if (Directory.Exists(path) == false) return; - foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) + if (Directory.Exists(path) == false) + { + return; + } + + foreach (string file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) + { File.Delete(file); + } }); Try(() => { - if (Directory.Exists(path) == false) return; + if (Directory.Exists(path) == false) + { + return; + } + Directory.Delete(path, true); }); } - public static void TryAssert(Action action, int maxTries = 5, int waitMilliseconds = 200) - { + public static void TryAssert(Action action, int maxTries = 5, int waitMilliseconds = 200) => Try(action, maxTries, waitMilliseconds); - } - public static void Try(Action action, int maxTries = 5, int waitMilliseconds = 200) - { + public static void Try(Action action, int maxTries = 5, int waitMilliseconds = 200) => Try(action, maxTries, waitMilliseconds); - } public static void Try(Action action, int maxTries = 5, int waitMilliseconds = 200) where T : Exception { - var tries = 0; + int tries = 0; while (true) { try @@ -325,7 +356,10 @@ namespace Umbraco.Tests.Integration.Implementations catch (T) { if (tries++ > maxTries) + { throw; + } + Thread.Sleep(waitMilliseconds); } } diff --git a/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs b/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs index 1a3415634b..2a91b6db83 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs @@ -1,4 +1,7 @@ -using Microsoft.AspNetCore.Hosting; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Options; using Umbraco.Core.Configuration.Models; using Umbraco.Web.Common.AspNetCore; @@ -14,10 +17,11 @@ namespace Umbraco.Tests.Integration.Implementations } /// - /// Override for tests since we are not hosted + /// Gets a value indicating whether we are hosted. /// /// - /// This is specifically used by IOHelper and we want this to return false so that the root path is manually calcualted which is what we want for tests. + /// This is specifically used by IOHelper and we want this to return false so that the root path is manually + /// calculated which is what we want for tests. /// bool IHostingEnvironment.IsHosted { get; } = false; } diff --git a/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs b/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs index a18360eff9..07f517e710 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs @@ -1,4 +1,7 @@ -using System.Threading; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; @@ -13,6 +16,4 @@ namespace Umbraco.Tests.Integration.Implementations public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask; } - - } diff --git a/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs b/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs index b4f876fc66..c032ad5551 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Runtime; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Runtime; namespace Umbraco.Tests.Integration.Implementations { diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs index 9d49ec22fa..f519d939b8 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs @@ -1,7 +1,10 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Net; +using System.Net.Http; using System.Threading.Tasks; using NUnit.Framework; -using Umbraco.Tests.Testing; using Umbraco.Web.BackOffice.Controllers; namespace Umbraco.Tests.Integration.TestServerTest.Controllers @@ -13,10 +16,10 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers public async Task EnsureSuccessStatusCode() { // Arrange - var url = PrepareUrl(x=>x.GetSupportedLocales()); + string url = PrepareUrl(x => x.GetSupportedLocales()); // Act - var response = await Client.GetAsync(url); + HttpResponseMessage response = await Client.GetAsync(url); // Assert Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs index f9d5d9f7da..cd7095ba75 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Linq; using System.Net; using System.Net.Http; @@ -18,14 +21,13 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [TestFixture] public class ContentControllerTests : UmbracoTestServerTestBase { - /// /// Returns 404 if the content wasn't found based on the ID specified /// [Test] public async Task PostSave_Validate_Existing_Content() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); // Add another language localizationService.Save(new LanguageBuilder() @@ -33,12 +35,12 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -51,7 +53,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -61,31 +63,29 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .WithId(-1337) // HERE We overwrite the Id, so we don't expect to find it on the server .Build(); // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - // Assert.AreEqual(")]}',\n{\"Message\":\"content was not found\"}", response.Item1.Content.ReadAsStringAsync().Result); - // - // //var obj = JsonConvert.DeserializeObject>(response.Item2); - // //Assert.AreEqual(0, obj.TotalItems); + //// Assert.AreEqual(")]}',\n{\"Message\":\"content was not found\"}", response.Item1.Content.ReadAsStringAsync().Result); + //// + //// //var obj = JsonConvert.DeserializeObject>(response.Item2); + //// //Assert.AreEqual(0, obj.TotalItems); } [Test] public async Task PostSave_Validate_At_Least_One_Variant_Flagged_For_Saving() { - - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); // Add another language localizationService.Save(new LanguageBuilder() @@ -93,11 +93,11 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentTypeService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -110,8 +110,8 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var contentService = GetRequiredService(); - var content = new ContentBuilder() + IContentService contentService = GetRequiredService(); + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -121,7 +121,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); @@ -133,20 +133,19 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers }); // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); Assert.AreEqual(AngularJsonMediaTypeFormatter.XsrfPrefix + "{\"Message\":\"No variants flagged for saving\"}", body); }); - } /// @@ -155,7 +154,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostSave_Validate_Properties_Exist() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); // Add another language localizationService.Save(new LanguageBuilder() @@ -163,12 +162,12 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -181,7 +180,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -191,7 +190,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithId(content.Id) .WithContentTypeAlias(content.ContentType.Alias) .AddVariant() @@ -203,15 +202,14 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Done() .Build(); - // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); @@ -221,20 +219,20 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostSave_Simple_Invariant() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - //Add another language + // Add another language localizationService.Save(new LanguageBuilder() .WithCultureInfo("da-DK") .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -247,7 +245,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -256,49 +254,46 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Done() .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); - // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, body); - var display = JsonConvert.DeserializeObject(body); + ContentItemDisplay display = JsonConvert.DeserializeObject(body); Assert.AreEqual(1, display.Variants.Count()); }); - } [Test] public async Task PostSave_Validate_Empty_Name() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - //Add another language + // Add another language localizationService.Save(new LanguageBuilder() .WithCultureInfo("da-DK") .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -311,7 +306,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -322,27 +317,25 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentService.SaveAndPublish(content); content.Name = null; // Removes the name of one of the variants to force an error - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); - // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); - var display = JsonConvert.DeserializeObject(body); + ContentItemDisplay display = JsonConvert.DeserializeObject(body); Assert.AreEqual(1, display.Errors.Count(), string.Join(",", display.Errors)); CollectionAssert.Contains(display.Errors.Keys, "Variants[0].Name"); }); @@ -351,20 +344,20 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostSave_Validate_Variants_Empty_Name() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - //Add another language + // Add another language localizationService.Save(new LanguageBuilder() .WithCultureInfo("da-DK") .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -377,7 +370,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithCultureName("en-US", "English") .WithCultureName("da-DK", "Danish") @@ -389,30 +382,27 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentService.SaveAndPublish(content); content.CultureInfos[0].Name = null; // Removes the name of one of the variants to force an error - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); - var display = JsonConvert.DeserializeObject(body); + ContentItemDisplay display = JsonConvert.DeserializeObject(body); Assert.AreEqual(2, display.Errors.Count()); CollectionAssert.Contains(display.Errors.Keys, "Variants[0].Name"); CollectionAssert.Contains(display.Errors.Keys, "_content_variant_en-US_null_"); }); - - } - } } diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs index 747e99191b..8a558c53d4 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using System.Net; +using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -20,12 +24,12 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task GetContentTypes__Ensure_camel_case() { - var url = PrepareUrl(x => x.GetContentTypes()); + string url = PrepareUrl(x => x.GetContentTypes()); // Act - var response = await Client.GetAsync(url); + HttpResponseMessage response = await Client.GetAsync(url); - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); @@ -36,17 +40,15 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers Assert.DoesNotThrow(() => JsonConvert.DeserializeObject(body)); - var jtokens = JsonConvert.DeserializeObject(body); - foreach (var jToken in jtokens) + JToken[] jtokens = JsonConvert.DeserializeObject(body); + foreach (JToken jToken in jtokens) { - var alias = nameof(ContentTypeModel.Alias); - var camelCaseAlias = alias.ToCamelCase(); + string alias = nameof(ContentTypeModel.Alias); + string camelCaseAlias = alias.ToCamelCase(); Assert.IsNotNull(jToken.Value(camelCaseAlias), $"'{jToken}' do not contain the key '{camelCaseAlias}' in the expected casing"); Assert.IsNull(jToken.Value(alias), $"'{jToken}' do contain the key '{alias}', which was not expect in that casing"); } }); - - } } } diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.cs index c001eb2d92..fbba385cdc 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Net; @@ -28,11 +31,11 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task Save_User() { - var url = PrepareUrl(x => x.PostSaveUser(null)); + string url = PrepareUrl(x => x.PostSaveUser(null)); - var userService = GetRequiredService(); + IUserService userService = GetRequiredService(); - var user = new UserBuilder() + User user = new UserBuilder() .AddUserGroup() .WithAlias("writer") // Needs to be an existing alias .Done() @@ -49,101 +52,102 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers Name = user.Name, UserGroups = user.Groups.Select(x => x.Alias).ToArray() }; + // Act - var response = await Client.PostAsync(url, - new StringContent(JsonConvert.SerializeObject(userSave), Encoding.UTF8, - MediaTypeNames.Application.Json)); + HttpResponseMessage response = await Client.PostAsync( + url, + new StringContent(JsonConvert.SerializeObject(userSave), Encoding.UTF8, MediaTypeNames.Application.Json)); // Assert - Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + string body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + UserDisplay actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); Assert.AreEqual(userSave.Name, actual.Name); Assert.AreEqual(userSave.Id, actual.Id); Assert.AreEqual(userSave.Email, actual.Email); - var userGroupAliases = actual.UserGroups.Select(x => x.Alias).ToArray(); + string[] userGroupAliases = actual.UserGroups.Select(x => x.Alias).ToArray(); CollectionAssert.AreEquivalent(userSave.UserGroups, userGroupAliases); }); } [Test] - public async Task GetPagedUsers_Empty() - { - //We get page 2 to force an empty response because there always in the useradmin user - var url = PrepareUrl(x => x.GetPagedUsers(2, 10, "username", Direction.Ascending, null, null, string.Empty)); + public async Task GetPagedUsers_Empty() + { + // We get page 2 to force an empty response because there always in the useradmin user + string url = PrepareUrl(x => x.GetPagedUsers(2, 10, "username", Direction.Ascending, null, null, string.Empty)); - // Act - var response = await Client.GetAsync(url); + // Act + HttpResponseMessage response = await Client.GetAsync(url); - var body = await response.Content.ReadAsStringAsync(); - body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings - { - ContractResolver = new IgnoreRequiredAttributesResolver() - }); - Assert.Multiple(() => - { - Assert.IsNotNull(actual); - Assert.AreEqual(1, actual.TotalItems); - CollectionAssert.IsEmpty(actual.Items); - }); - } + string body = await response.Content.ReadAsStringAsync(); + body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + PagedResult actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings + { + ContractResolver = new IgnoreRequiredAttributesResolver() + }); + Assert.Multiple(() => + { + Assert.IsNotNull(actual); + Assert.AreEqual(1, actual.TotalItems); + CollectionAssert.IsEmpty(actual.Items); + }); + } - [Test] - public async Task GetPagedUsers_multiple_pages() - { - var totalNumberOfUsers = 11; - var pageSize = totalNumberOfUsers - 1; - var url = PrepareUrl(x => x.GetPagedUsers(1, pageSize, "username", Direction.Ascending, null, null, string.Empty)); + [Test] + public async Task GetPagedUsers_multiple_pages() + { + int totalNumberOfUsers = 11; + int pageSize = totalNumberOfUsers - 1; + string url = PrepareUrl(x => x.GetPagedUsers(1, pageSize, "username", Direction.Ascending, null, null, string.Empty)); - var userService = GetRequiredService(); + IUserService userService = GetRequiredService(); - for (int i = 1; i < totalNumberOfUsers; i++) // We already has admin user = -1, so we start from 1 - { - var user = new UserBuilder() + // We already has admin user = -1, so we start from 1. + for (int i = 1; i < totalNumberOfUsers; i++) + { + User user = new UserBuilder() .WithName($"Test user {i}") .AddUserGroup() .WithAlias("writer") // Needs to be an existing alias .Done() .Build(); - userService.Save(user); - } - - // Act - var response = await Client.GetAsync(url); - - var body = await response.Content.ReadAsStringAsync(); - body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings - { - ContractResolver = new IgnoreRequiredAttributesResolver() - }); - Assert.Multiple(() => - { - Assert.IsNotNull(actual); - Assert.AreEqual(totalNumberOfUsers, actual.TotalItems); - Assert.AreEqual(pageSize, actual.Items.Count()); - }); - } - - [Test] - public async Task PostUnlockUsers_When_UserIds_Not_Supplied_Expect_Ok_Response() - { - var url = PrepareUrl(x => x.PostUnlockUsers(Array.Empty())); + userService.Save(user); + } // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); + HttpResponseMessage response = await Client.GetAsync(url); + + string body = await response.Content.ReadAsStringAsync(); + body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + PagedResult actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings + { + ContractResolver = new IgnoreRequiredAttributesResolver() + }); + Assert.Multiple(() => + { + Assert.IsNotNull(actual); + Assert.AreEqual(totalNumberOfUsers, actual.TotalItems); + Assert.AreEqual(pageSize, actual.Items.Count()); + }); + } + + [Test] + public async Task PostUnlockUsers_When_UserIds_Not_Supplied_Expect_Ok_Response() + { + string url = PrepareUrl(x => x.PostUnlockUsers(Array.Empty())); + + // Act + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } @@ -151,31 +155,28 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostUnlockUsers_When_User_Does_Not_Exist_Expect_Zero_Users_Message() { - var userId = 42; // Must not exist - var url = PrepareUrl(x => x.PostUnlockUsers(new []{userId})); + int userId = 42; // Must not exist + string url = PrepareUrl(x => x.PostUnlockUsers(new[] { userId })); // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); - var body = await response.Content.ReadAsStringAsync(); + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + SimpleNotificationModel actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); - Assert.Multiple(() => - { - Assert.AreEqual($"Unlocked 0 users", actual.Message); - }); + Assert.Multiple(() => Assert.AreEqual($"Unlocked 0 users", actual.Message)); } [Test] public async Task PostUnlockUsers_When_One_UserId_Supplied_Expect_User_Locked_Out_With_Correct_Response_Message() { - var userService = GetRequiredService(); + IUserService userService = GetRequiredService(); - var user = new UserBuilder() + User user = new UserBuilder() .AddUserGroup() .WithAlias("writer") // Needs to be an existing alias .Done() @@ -183,14 +184,14 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); userService.Save(user); - var url = PrepareUrl(x => x.PostUnlockUsers(new []{user.Id})); + string url = PrepareUrl(x => x.PostUnlockUsers(new[] { user.Id })); // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); - var body = await response.Content.ReadAsStringAsync(); + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + SimpleNotificationModel actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); @@ -205,8 +206,8 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostUnlockUsers_When_Multiple_UserIds_Supplied_Expect_User_Locked_Out_With_Correct_Response_Message() { - var numberOfUsers = 3; - var userService = GetRequiredService(); + int numberOfUsers = 3; + IUserService userService = GetRequiredService(); var users = new List(); for (int i = 0; i < numberOfUsers; i++) @@ -222,19 +223,19 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build()); } - foreach (var user in users) + foreach (IUser user in users) { userService.Save(user); } - var url = PrepareUrl(x => x.PostUnlockUsers(users.Select(x=>x.Id).ToArray())); + string url = PrepareUrl(x => x.PostUnlockUsers(users.Select(x => x.Id).ToArray())); // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); - var body = await response.Content.ReadAsStringAsync(); + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + SimpleNotificationModel actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs b/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs index ab5821c81c..22f4b7e989 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs @@ -1,4 +1,8 @@ -using System.Text.Encodings.Web; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Security.Claims; +using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; @@ -19,21 +23,27 @@ namespace Umbraco.Tests.Integration.TestServerTest private readonly IBackOfficeSignInManager _backOfficeSignInManager; private readonly BackOfficeIdentityUser _fakeUser; - public TestAuthHandler(IOptionsMonitor options, - ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IBackOfficeSignInManager backOfficeSignInManager, IUserService userService, UmbracoMapper umbracoMapper) + + public TestAuthHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock, + IBackOfficeSignInManager backOfficeSignInManager, + IUserService userService, + UmbracoMapper umbracoMapper) : base(options, logger, encoder, clock) { _backOfficeSignInManager = backOfficeSignInManager; - var user = userService.GetUserById(Constants.Security.SuperUserId); + IUser user = userService.GetUserById(Constants.Security.SuperUserId); _fakeUser = umbracoMapper.Map(user); _fakeUser.SecurityStamp = "Needed"; } protected override async Task HandleAuthenticateAsync() { - - var principal = await _backOfficeSignInManager.CreateUserPrincipalAsync(_fakeUser); + ClaimsPrincipal principal = await _backOfficeSignInManager.CreateUserPrincipalAsync(_fakeUser); var ticket = new AuthenticationTicket(principal, TestAuthenticationScheme); return AuthenticateResult.Success(ticket); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs index 5a704c2b5d..eb5d4bca3d 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Linq.Expressions; using System.Net.Http; @@ -13,6 +16,7 @@ using Microsoft.Extensions.Hosting; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Composing; using Umbraco.Core.DependencyInjection; using Umbraco.Extensions; using Umbraco.Infrastructure.PublishedCache.DependencyInjection; @@ -44,15 +48,13 @@ namespace Umbraco.Tests.Integration.TestServerTest // additional host configuration for web server integration tests Factory = factory.WithWebHostBuilder(builder => - { + // Executes after the standard ConfigureServices method builder.ConfigureTestServices(services => - { + // Add a test auth scheme with a test auth handler to authn and assign the user services.AddAuthentication(TestAuthHandler.TestAuthenticationScheme) - .AddScheme(TestAuthHandler.TestAuthenticationScheme, options => { }); - }); - }); + .AddScheme(TestAuthHandler.TestAuthenticationScheme, options => { }))); Client = Factory.CreateClient(new WebApplicationFactoryClientOptions { @@ -64,21 +66,14 @@ namespace Umbraco.Tests.Integration.TestServerTest public override IHostBuilder CreateHostBuilder() { - var builder = base.CreateHostBuilder(); + IHostBuilder builder = base.CreateHostBuilder(); builder.ConfigureWebHost(builder => { // need to configure the IWebHostEnvironment too - builder.ConfigureServices((c, s) => - { - c.HostingEnvironment = TestHelper.GetWebHostEnvironment(); - }); + builder.ConfigureServices((c, s) => c.HostingEnvironment = TestHelper.GetWebHostEnvironment()); // call startup - builder.Configure(app => - { - Configure(app); - }); - + builder.Configure(app => Configure(app)); }).UseEnvironment(Environments.Development); return builder; @@ -92,11 +87,11 @@ namespace Umbraco.Tests.Integration.TestServerTest protected string PrepareUrl(Expression> methodSelector) where T : UmbracoApiController { - var url = LinkGenerator.GetUmbracoApiService(methodSelector); + string url = LinkGenerator.GetUmbracoApiService(methodSelector); - var backofficeSecurityFactory = GetRequiredService(); - var umbracoContextFactory = GetRequiredService(); - var httpContextAccessor = GetRequiredService(); + IBackOfficeSecurityFactory backofficeSecurityFactory = GetRequiredService(); + IUmbracoContextFactory umbracoContextFactory = GetRequiredService(); + IHttpContextAccessor httpContextAccessor = GetRequiredService(); httpContextAccessor.HttpContext = new DefaultHttpContext { @@ -124,7 +119,7 @@ namespace Umbraco.Tests.Integration.TestServerTest public override void ConfigureServices(IServiceCollection services) { services.AddTransient(); - var typeLoader = services.AddTypeLoader( + TypeLoader typeLoader = services.AddTypeLoader( GetType().Assembly, TestHelper.GetWebHostEnvironment(), TestHelper.GetHostingEnvironment(), diff --git a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs index 256c5c59a9..5d923e583e 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs @@ -1,11 +1,14 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.Hosting; namespace Umbraco.Tests.Integration.TestServerTest { - - public class UmbracoWebApplicationFactory : WebApplicationFactory where TStartup : class + public class UmbracoWebApplicationFactory : WebApplicationFactory + where TStartup : class { private readonly Func _createHostBuilder; private readonly Action _beforeStart; diff --git a/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs index 52a0778a59..25fbc6ef59 100644 --- a/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -19,7 +22,7 @@ namespace Umbraco.Tests.Integration.Testing protected IUmbracoDatabaseFactory _databaseFactory; protected IList _testDatabases; - protected const int _threadCount = 2; + protected const int ThreadCount = 2; protected UmbracoDatabase.CommandInfo[] _cachedDatabaseInitCommands = new UmbracoDatabase.CommandInfo[0]; @@ -54,45 +57,43 @@ namespace Umbraco.Tests.Integration.Testing _prepareQueue.TryAdd(meta); } - protected void PrepareDatabase() - { + protected void PrepareDatabase() => Retry(10, () => - { - while (_prepareQueue.IsCompleted == false) { - TestDbMeta meta; - try + while (_prepareQueue.IsCompleted == false) { - meta = _prepareQueue.Take(); - } - catch (InvalidOperationException) - { - continue; - } + TestDbMeta meta; + try + { + meta = _prepareQueue.Take(); + } + catch (InvalidOperationException) + { + continue; + } - using (var conn = new SqlConnection(meta.ConnectionString)) - using (var cmd = conn.CreateCommand()) - { - conn.Open(); - ResetTestDatabase(cmd); + using (var conn = new SqlConnection(meta.ConnectionString)) + using (SqlCommand cmd = conn.CreateCommand()) + { + conn.Open(); + ResetTestDatabase(cmd); + + if (!meta.IsEmpty) + { + RebuildSchema(cmd, meta); + } + } if (!meta.IsEmpty) { - RebuildSchema(cmd, meta); + _readySchemaQueue.TryAdd(meta); + } + else + { + _readyEmptyQueue.TryAdd(meta); } } - - if (!meta.IsEmpty) - { - _readySchemaQueue.TryAdd(meta); - } - else - { - _readyEmptyQueue.TryAdd(meta); - } - } - }); - } + }); private void RebuildSchema(IDbCommand command, TestDbMeta meta) { @@ -100,12 +101,12 @@ namespace Umbraco.Tests.Integration.Testing { if (!_cachedDatabaseInitCommands.Any()) { - RebuildSchemaFirstTime(command, meta); + RebuildSchemaFirstTime(meta); return; } } - foreach (var dbCommand in _cachedDatabaseInitCommands) + foreach (UmbracoDatabase.CommandInfo dbCommand in _cachedDatabaseInitCommands) { if (dbCommand.Text.StartsWith("SELECT ")) { @@ -115,7 +116,7 @@ namespace Umbraco.Tests.Integration.Testing command.CommandText = dbCommand.Text; command.Parameters.Clear(); - foreach (var parameterInfo in dbCommand.Parameters) + foreach (UmbracoDatabase.ParameterInfo parameterInfo in dbCommand.Parameters) { AddParameter(command, parameterInfo); } @@ -124,7 +125,7 @@ namespace Umbraco.Tests.Integration.Testing } } - private void RebuildSchemaFirstTime(IDbCommand command, TestDbMeta meta) + private void RebuildSchemaFirstTime(TestDbMeta meta) { _databaseFactory.Configure(meta.ConnectionString, Core.Constants.DatabaseProviders.SqlServer); @@ -132,7 +133,7 @@ namespace Umbraco.Tests.Integration.Testing { database.LogCommands = true; - using (var transaction = database.GetTransaction()) + using (NPoco.ITransaction transaction = database.GetTransaction()) { var schemaCreator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, new UmbracoVersion()); schemaCreator.InitializeDatabaseSchema(); @@ -150,7 +151,7 @@ namespace Umbraco.Tests.Integration.Testing command.CommandText = sql; command.Parameters.Clear(); - for (var i = 0; i < args.Length; i++) + for (int i = 0; i < args.Length; i++) { command.Parameters.AddWithValue("@" + i, args[i]); } @@ -158,7 +159,7 @@ namespace Umbraco.Tests.Integration.Testing protected static void AddParameter(IDbCommand cmd, UmbracoDatabase.ParameterInfo parameterInfo) { - var p = cmd.CreateParameter(); + IDbDataParameter p = cmd.CreateParameter(); p.ParameterName = parameterInfo.Name; p.Value = parameterInfo.Value; p.DbType = parameterInfo.DbType; @@ -169,7 +170,6 @@ namespace Umbraco.Tests.Integration.Testing protected static void ResetTestDatabase(IDbCommand cmd) { // https://stackoverflow.com/questions/536350 - cmd.CommandType = CommandType.Text; cmd.CommandText = @" declare @n char(1); @@ -196,7 +196,7 @@ namespace Umbraco.Tests.Integration.Testing protected static void Retry(int maxIterations, Action action) { - for (var i = 0; i < maxIterations; i++) + for (int i = 0; i < maxIterations; i++) { try { @@ -205,8 +205,7 @@ namespace Umbraco.Tests.Integration.Testing } catch (SqlException) { - - //Console.Error.WriteLine($"SqlException occured, but we try again {i+1}/{maxIterations}.\n{e}"); + // Console.Error.WriteLine($"SqlException occured, but we try again {i+1}/{maxIterations}.\n{e}"); // This can occur when there's a transaction deadlock which means (i think) that the database is still in use and hasn't been closed properly yet // so we need to just wait a little bit Thread.Sleep(100 * i); diff --git a/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs index 28d7e9c8bc..bdfde8d93b 100644 --- a/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs @@ -1,9 +1,14 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + namespace Umbraco.Tests.Integration.Testing { public interface ITestDatabase { TestDbMeta AttachEmpty(); + TestDbMeta AttachSchema(); + void Detach(TestDbMeta id); } } diff --git a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs index 69819c9bef..4950f87bd9 100644 --- a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs +++ b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs @@ -1,4 +1,7 @@ -using Examine; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Examine; using Examine.LuceneEngine.Providers; using Umbraco.Core.Composing; using Umbraco.Examine; @@ -12,15 +15,9 @@ namespace Umbraco.Tests.Integration.Testing { private readonly IExamineManager _examineManager; - public IntegrationTestComponent(IExamineManager examineManager) - { - _examineManager = examineManager; - } + public IntegrationTestComponent(IExamineManager examineManager) => _examineManager = examineManager; - public void Initialize() - { - ConfigureExamineIndexes(); - } + public void Initialize() => ConfigureExamineIndexes(); public void Terminate() { @@ -31,7 +28,7 @@ namespace Umbraco.Tests.Integration.Testing /// private void ConfigureExamineIndexes() { - foreach (var index in _examineManager.Indexes) + foreach (IIndex index in _examineManager.Indexes) { if (index is LuceneIndex luceneIndex) { diff --git a/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs index 59a9b00215..5ae889d8fb 100644 --- a/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Concurrent; using System.IO; @@ -16,19 +19,19 @@ namespace Umbraco.Tests.Integration.Testing public const string DatabaseName = "UmbracoTests"; private readonly LocalDb _localDb; - private static LocalDb.Instance _localDbInstance; - private static string _filesPath; + private static LocalDb.Instance s_localDbInstance; + private static string s_filesPath; public static LocalDbTestDatabase Instance { get; private set; } - //It's internal because `Umbraco.Core.Persistence.LocalDb` is internal + // It's internal because `Umbraco.Core.Persistence.LocalDb` is internal internal LocalDbTestDatabase(ILoggerFactory loggerFactory, LocalDb localDb, string filesPath, IUmbracoDatabaseFactory dbFactory) { _loggerFactory = loggerFactory; _databaseFactory = dbFactory; _localDb = localDb; - _filesPath = filesPath; + s_filesPath = filesPath; Instance = this; // For GlobalSetupTeardown.cs @@ -43,8 +46,8 @@ namespace Umbraco.Tests.Integration.Testing TestDbMeta.CreateWithoutConnectionString($"{DatabaseName}-4", true), }; - _localDbInstance = _localDb.GetInstance(InstanceName); - if (_localDbInstance != null) + s_localDbInstance = _localDb.GetInstance(InstanceName); + if (s_localDbInstance != null) { return; } @@ -54,30 +57,30 @@ namespace Umbraco.Tests.Integration.Testing throw new Exception("Failed to create a LocalDb instance."); } - _localDbInstance = _localDb.GetInstance(InstanceName); + s_localDbInstance = _localDb.GetInstance(InstanceName); } protected override void Initialize() { - var tempName = Guid.NewGuid().ToString("N"); - _localDbInstance.CreateDatabase(tempName, _filesPath); - _localDbInstance.DetachDatabase(tempName); + string tempName = Guid.NewGuid().ToString("N"); + s_localDbInstance.CreateDatabase(tempName, s_filesPath); + s_localDbInstance.DetachDatabase(tempName); _prepareQueue = new BlockingCollection(); _readySchemaQueue = new BlockingCollection(); _readyEmptyQueue = new BlockingCollection(); - for (var i = 0; i < _testDatabases.Count; i++) + for (int i = 0; i < _testDatabases.Count; i++) { - var meta = _testDatabases[i]; - var isLast = i == _testDatabases.Count - 1; + TestDbMeta meta = _testDatabases[i]; + bool isLast = i == _testDatabases.Count - 1; - _localDb.CopyDatabaseFiles(tempName, _filesPath, targetDatabaseName: meta.Name, overwrite: true, delete: isLast); - meta.ConnectionString = _localDbInstance.GetAttachedConnectionString(meta.Name, _filesPath); + _localDb.CopyDatabaseFiles(tempName, s_filesPath, targetDatabaseName: meta.Name, overwrite: true, delete: isLast); + meta.ConnectionString = s_localDbInstance.GetAttachedConnectionString(meta.Name, s_filesPath); _prepareQueue.Add(meta); } - for (var i = 0; i < _threadCount; i++) + for (int i = 0; i < ThreadCount; i++) { var thread = new Thread(PrepareDatabase); thread.Start(); @@ -93,34 +96,41 @@ namespace Umbraco.Tests.Integration.Testing _prepareQueue.CompleteAdding(); while (_prepareQueue.TryTake(out _)) - { } + { + } _readyEmptyQueue.CompleteAdding(); while (_readyEmptyQueue.TryTake(out _)) - { } + { + } _readySchemaQueue.CompleteAdding(); while (_readySchemaQueue.TryTake(out _)) - { } + { + } - if (_filesPath == null) + if (s_filesPath == null) { return; } - var filename = Path.Combine(_filesPath, DatabaseName).ToUpper(); + string filename = Path.Combine(s_filesPath, DatabaseName).ToUpper(); - foreach (var database in _localDbInstance.GetDatabases()) + foreach (string database in s_localDbInstance.GetDatabases()) { if (database.StartsWith(filename)) { - _localDbInstance.DropDatabase(database); + s_localDbInstance.DropDatabase(database); } } - foreach (var file in Directory.EnumerateFiles(_filesPath)) + foreach (string file in Directory.EnumerateFiles(s_filesPath)) { - if (file.EndsWith(".mdf") == false && file.EndsWith(".ldf") == false) continue; + if (file.EndsWith(".mdf") == false && file.EndsWith(".ldf") == false) + { + continue; + } + try { File.Delete(file); diff --git a/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs index 2e1f75cd45..7ab65c1e74 100644 --- a/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Concurrent; using System.Data.SqlClient; @@ -6,7 +9,6 @@ using Microsoft.Extensions.Logging; using Umbraco.Core.Persistence; // ReSharper disable ConvertToUsingDeclaration - namespace Umbraco.Tests.Integration.Testing { /// @@ -46,13 +48,13 @@ namespace Umbraco.Tests.Integration.Testing _readySchemaQueue = new BlockingCollection(); _readyEmptyQueue = new BlockingCollection(); - foreach (var meta in _testDatabases) + foreach (TestDbMeta meta in _testDatabases) { CreateDatabase(meta); _prepareQueue.Add(meta); } - for (var i = 0; i < _threadCount; i++) + for (int i = 0; i < ThreadCount; i++) { var thread = new Thread(PrepareDatabase); thread.Start(); @@ -64,7 +66,7 @@ namespace Umbraco.Tests.Integration.Testing using (var connection = new SqlConnection(_masterConnectionString)) { connection.Open(); - using (var command = connection.CreateCommand()) + using (SqlCommand command = connection.CreateCommand()) { SetCommand(command, $@"CREATE DATABASE {LocalDb.QuotedName(meta.Name)}"); command.ExecuteNonQuery(); @@ -77,13 +79,13 @@ namespace Umbraco.Tests.Integration.Testing using (var connection = new SqlConnection(_masterConnectionString)) { connection.Open(); - using (var command = connection.CreateCommand()) + using (SqlCommand command = connection.CreateCommand()) { - SetCommand(command, $@" + string sql = $@" ALTER DATABASE{LocalDb.QuotedName(meta.Name)} SET SINGLE_USER - WITH ROLLBACK IMMEDIATE - "); + WITH ROLLBACK IMMEDIATE"; + SetCommand(command, sql); command.ExecuteNonQuery(); SetCommand(command, $@"DROP DATABASE {LocalDb.QuotedName(meta.Name)}"); @@ -95,18 +97,26 @@ namespace Umbraco.Tests.Integration.Testing public void Finish() { if (_prepareQueue == null) + { return; + } _prepareQueue.CompleteAdding(); - while (_prepareQueue.TryTake(out _)) { } + while (_prepareQueue.TryTake(out _)) + { + } _readyEmptyQueue.CompleteAdding(); - while (_readyEmptyQueue.TryTake(out _)) { } + while (_readyEmptyQueue.TryTake(out _)) + { + } _readySchemaQueue.CompleteAdding(); - while (_readySchemaQueue.TryTake(out _)) { } + while (_readySchemaQueue.TryTake(out _)) + { + } - foreach (var testDatabase in _testDatabases) + foreach (TestDbMeta testDatabase in _testDatabases) { Drop(testDatabase); } diff --git a/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs b/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs index 60c767e17e..6d7e88b5b0 100644 --- a/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs +++ b/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.IO; using Microsoft.Extensions.Logging; @@ -9,7 +12,7 @@ namespace Umbraco.Tests.Integration.Testing { public static ITestDatabase Create(string filesPath, ILoggerFactory loggerFactory, TestUmbracoDatabaseFactoryProvider dbFactory) { - var connectionString = Environment.GetEnvironmentVariable("UmbracoIntegrationTestConnectionString"); + string connectionString = Environment.GetEnvironmentVariable("UmbracoIntegrationTestConnectionString"); return string.IsNullOrEmpty(connectionString) ? CreateLocalDb(filesPath, loggerFactory, dbFactory) diff --git a/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs b/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs index 83702db8e5..ea6f7d1c72 100644 --- a/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs +++ b/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs @@ -1,10 +1,12 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Text.RegularExpressions; namespace Umbraco.Tests.Integration.Testing { public class TestDbMeta { - public string Name { get; } public bool IsEmpty { get; } @@ -20,20 +22,16 @@ namespace Umbraco.Tests.Integration.Testing private static string ConstructConnectionString(string masterConnectionString, string databaseName) { - var prefix = Regex.Replace(masterConnectionString, "Database=.+?;", string.Empty); - var connectionString = $"{prefix};Database={databaseName};"; + string prefix = Regex.Replace(masterConnectionString, "Database=.+?;", string.Empty); + string connectionString = $"{prefix};Database={databaseName};"; return connectionString.Replace(";;", ";"); } - public static TestDbMeta CreateWithMasterConnectionString(string name, bool isEmpty, string masterConnectionString) - { - return new TestDbMeta(name, isEmpty, ConstructConnectionString(masterConnectionString, name)); - } + public static TestDbMeta CreateWithMasterConnectionString(string name, bool isEmpty, string masterConnectionString) => + new TestDbMeta(name, isEmpty, ConstructConnectionString(masterConnectionString, name)); // LocalDb mdf funtimes - public static TestDbMeta CreateWithoutConnectionString(string name, bool isEmpty) - { - return new TestDbMeta(name, isEmpty, null); - } + public static TestDbMeta CreateWithoutConnectionString(string name, bool isEmpty) => + new TestDbMeta(name, isEmpty, null); } } diff --git a/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs b/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs index 3eb3757207..9b27f4cfba 100644 --- a/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs +++ b/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs @@ -1,7 +1,11 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; @@ -18,19 +22,22 @@ namespace Umbraco.Tests.Integration.Testing private readonly IOptions _connectionStrings; private readonly Lazy _mappers; private readonly IDbProviderFactoryCreator _dbProviderFactoryCreator; + private readonly DatabaseSchemaCreatorFactory _databaseSchemaCreatorFactory; public TestUmbracoDatabaseFactoryProvider( ILoggerFactory loggerFactory, IOptions globalSettings, IOptions connectionStrings, Lazy mappers, - IDbProviderFactoryCreator dbProviderFactoryCreator) + IDbProviderFactoryCreator dbProviderFactoryCreator, + DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory) { _loggerFactory = loggerFactory; _globalSettings = globalSettings; _connectionStrings = connectionStrings; _mappers = mappers; _dbProviderFactoryCreator = dbProviderFactoryCreator; + _databaseSchemaCreatorFactory = databaseSchemaCreatorFactory; } public IUmbracoDatabaseFactory Create() @@ -42,7 +49,8 @@ namespace Umbraco.Tests.Integration.Testing _globalSettings.Value, _connectionStrings.Value, _mappers, - _dbProviderFactoryCreator); + _dbProviderFactoryCreator, + _databaseSchemaCreatorFactory); } } } diff --git a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs index 885668acca..ca62668493 100644 --- a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs +++ b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Data.Common; @@ -5,6 +8,7 @@ using System.Data.SqlClient; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -39,7 +43,6 @@ using Umbraco.Web.Common.DependencyInjection; namespace Umbraco.Tests.Integration.Testing { - /// /// Abstract class for integration tests /// @@ -51,7 +54,7 @@ namespace Umbraco.Tests.Integration.Testing public abstract class UmbracoIntegrationTest { private List _testTeardown = null; - private List _fixtureTeardown = new List(); + private readonly List _fixtureTeardown = new List(); public void OnTestTearDown(Action tearDown) { @@ -68,7 +71,7 @@ namespace Umbraco.Tests.Integration.Testing [OneTimeTearDown] public void FixtureTearDown() { - foreach (var a in _fixtureTeardown) + foreach (Action a in _fixtureTeardown) { a(); } @@ -79,7 +82,7 @@ namespace Umbraco.Tests.Integration.Testing { if (_testTeardown != null) { - foreach (var a in _testTeardown) + foreach (Action a in _testTeardown) { a(); } @@ -96,22 +99,18 @@ namespace Umbraco.Tests.Integration.Testing } [TearDown] - public virtual void TearDown_Logging() - { + public virtual void TearDown_Logging() => TestContext.Progress.Write($" {TestContext.CurrentContext.Result.Outcome.Status}"); - } [SetUp] - public virtual void SetUp_Logging() - { + public virtual void SetUp_Logging() => TestContext.Progress.Write($"Start test {TestCount++}: {TestContext.CurrentContext.Test.Name}"); - } [SetUp] public virtual void Setup() { - InMemoryConfiguration[Constants.Configuration.ConfigGlobal + ":" + nameof(GlobalSettings.InstallEmptyDatabase)] = "true"; - var hostBuilder = CreateHostBuilder(); + InMemoryConfiguration[Constants.Configuration.ConfigGlobal + ":" + nameof(GlobalSettings.InstallUnattended)] = "true"; + IHostBuilder hostBuilder = CreateHostBuilder(); IHost host = hostBuilder.Build(); BeforeHostStart(host); @@ -127,8 +126,6 @@ namespace Umbraco.Tests.Integration.Testing UseTestDatabase(Services); } - #region Generic Host Builder and Runtime - private ILoggerFactory CreateLoggerFactory() { try @@ -140,7 +137,7 @@ namespace Umbraco.Tests.Integration.Testing case UmbracoTestOptions.Logger.Serilog: return Microsoft.Extensions.Logging.LoggerFactory.Create(builder => { - var path = Path.Combine(TestHelper.WorkingDirectory, "logs", "umbraco_integration_tests_.txt"); + string path = Path.Combine(TestHelper.WorkingDirectory, "logs", "umbraco_integration_tests_.txt"); Log.Logger = new LoggerConfiguration() .WriteTo.File(path, rollingInterval: RollingInterval.Day) @@ -149,7 +146,7 @@ namespace Umbraco.Tests.Integration.Testing builder.AddSerilog(Log.Logger); }); case UmbracoTestOptions.Logger.Console: - return Microsoft.Extensions.Logging.LoggerFactory.Create(builder => { builder.AddConsole(); }); + return Microsoft.Extensions.Logging.LoggerFactory.Create(builder => builder.AddConsole()); } } catch @@ -165,12 +162,13 @@ namespace Umbraco.Tests.Integration.Testing /// public virtual IHostBuilder CreateHostBuilder() { - var hostBuilder = Host.CreateDefaultBuilder() + IHostBuilder hostBuilder = Host.CreateDefaultBuilder() + // IMPORTANT: We Cannot use UseStartup, there's all sorts of threads about this with testing. Although this can work // if you want to setup your tests this way, it is a bit annoying to do that as the WebApplicationFactory will // create separate Host instances. So instead of UseStartup, we just call ConfigureServices/Configure ourselves, // and in the case of the UmbracoTestServerTestBase it will use the ConfigureWebHost to Configure the IApplicationBuilder directly. - //.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(GetType()); }) + // .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(GetType()); }) .ConfigureAppConfiguration((context, configBuilder) => { context.HostingEnvironment = TestHelper.GetWebHostEnvironment(); @@ -194,18 +192,15 @@ namespace Umbraco.Tests.Integration.Testing return hostBuilder; } - #endregion - public virtual void ConfigureServices(IServiceCollection services) { services.AddSingleton(TestHelper.DbProviderFactoryCreator); services.AddTransient(); - var webHostEnvironment = TestHelper.GetWebHostEnvironment(); + IWebHostEnvironment webHostEnvironment = TestHelper.GetWebHostEnvironment(); services.AddRequiredNetCoreServices(TestHelper, webHostEnvironment); // Add it! - - var typeLoader = services.AddTypeLoader( + Core.Composing.TypeLoader typeLoader = services.AddTypeLoader( GetType().Assembly, webHostEnvironment, TestHelper.GetHostingEnvironment(), @@ -241,11 +236,10 @@ namespace Umbraco.Tests.Integration.Testing builder.Build(); } - protected virtual AppCaches GetAppCaches() - { + protected virtual AppCaches GetAppCaches() => + // Disable caches for integration tests - return AppCaches.NoCache; - } + AppCaches.NoCache; public virtual void Configure(IApplicationBuilder app) { @@ -258,18 +252,16 @@ namespace Umbraco.Tests.Integration.Testing app.UseUmbracoCore(); // This no longer starts CoreRuntime, it's very fast } - #region LocalDb - - private static readonly object _dbLocker = new object(); - private static ITestDatabase _dbInstance; - private static TestDbMeta _fixtureDbMeta; + private static readonly object s_dbLocker = new object(); + private static ITestDatabase s_dbInstance; + private static TestDbMeta s_fixtureDbMeta; protected void UseTestDatabase(IServiceProvider serviceProvider) { - var state = serviceProvider.GetRequiredService(); - var testDatabaseFactoryProvider = serviceProvider.GetRequiredService(); - var databaseFactory = serviceProvider.GetRequiredService(); - var loggerFactory = serviceProvider.GetRequiredService(); + IRuntimeState state = serviceProvider.GetRequiredService(); + TestUmbracoDatabaseFactoryProvider testDatabaseFactoryProvider = serviceProvider.GetRequiredService(); + IUmbracoDatabaseFactory databaseFactory = serviceProvider.GetRequiredService(); + ILoggerFactory loggerFactory = serviceProvider.GetRequiredService(); // This will create a db, install the schema and ensure the app is configured to run SetupTestDatabase(testDatabaseFactoryProvider, databaseFactory, loggerFactory, state, TestHelper.WorkingDirectory); @@ -283,16 +275,16 @@ namespace Umbraco.Tests.Integration.Testing /// private static ITestDatabase GetOrCreateDatabase(string filesPath, ILoggerFactory loggerFactory, TestUmbracoDatabaseFactoryProvider dbFactory) { - lock (_dbLocker) + lock (s_dbLocker) { - if (_dbInstance != null) + if (s_dbInstance != null) { - return _dbInstance; + return s_dbInstance; } - _dbInstance = TestDatabaseFactory.Create(filesPath, loggerFactory, dbFactory); + s_dbInstance = TestDatabaseFactory.Create(filesPath, loggerFactory, dbFactory); - return _dbInstance; + return s_dbInstance; } } @@ -314,9 +306,9 @@ namespace Umbraco.Tests.Integration.Testing // need to manually register this factory DbProviderFactories.RegisterFactory(Constants.DbProviderNames.SqlServer, SqlClientFactory.Instance); - var dbFilePath = Path.Combine(workingDirectory, "LocalDb"); + string dbFilePath = Path.Combine(workingDirectory, "LocalDb"); - var db = GetOrCreateDatabase(dbFilePath, loggerFactory, testUmbracoDatabaseFactoryProvider); + ITestDatabase db = GetOrCreateDatabase(dbFilePath, loggerFactory, testUmbracoDatabaseFactoryProvider); switch (TestOptions.Database) { @@ -352,13 +344,13 @@ namespace Umbraco.Tests.Integration.Testing { // New DB + Schema TestDbMeta newSchemaFixtureDbMeta = db.AttachSchema(); - _fixtureDbMeta = newSchemaFixtureDbMeta; + s_fixtureDbMeta = newSchemaFixtureDbMeta; // Add teardown callback OnFixtureTearDown(() => db.Detach(newSchemaFixtureDbMeta)); } - ConfigureTestDatabaseFactory(_fixtureDbMeta, databaseFactory, runtimeState); + ConfigureTestDatabaseFactory(s_fixtureDbMeta, databaseFactory, runtimeState); break; case UmbracoTestOptions.Database.NewEmptyPerFixture: @@ -369,13 +361,13 @@ namespace Umbraco.Tests.Integration.Testing { // New DB + Schema TestDbMeta newEmptyFixtureDbMeta = db.AttachEmpty(); - _fixtureDbMeta = newEmptyFixtureDbMeta; + s_fixtureDbMeta = newEmptyFixtureDbMeta; // Add teardown callback OnFixtureTearDown(() => db.Detach(newEmptyFixtureDbMeta)); } - ConfigureTestDatabaseFactory(_fixtureDbMeta, databaseFactory, runtimeState); + ConfigureTestDatabaseFactory(s_fixtureDbMeta, databaseFactory, runtimeState); break; default: @@ -396,8 +388,6 @@ namespace Umbraco.Tests.Integration.Testing log.LogInformation($"ConfigureTestDatabaseFactory - Determined RuntimeLevel: [{state.Level}]"); } - #endregion - protected UmbracoTestAttribute TestOptions => TestOptionAttributeBase.GetTestOptions(); protected virtual T GetRequiredService() => Services.GetRequiredService(); @@ -411,22 +401,22 @@ namespace Umbraco.Tests.Integration.Testing protected virtual void CustomTestSetup(IUmbracoBuilder builder) { } /// - /// Returns the DI container + /// Gets or sets the DI container. /// protected IServiceProvider Services { get; set; } /// - /// Returns the + /// Gets the /// protected IScopeProvider ScopeProvider => Services.GetRequiredService(); /// - /// Returns the + /// Gets the /// protected IScopeAccessor ScopeAccessor => Services.GetRequiredService(); /// - /// Returns the + /// Gets the /// protected ILoggerFactory LoggerFactory => Services.GetRequiredService(); @@ -440,13 +430,9 @@ namespace Umbraco.Tests.Integration.Testing protected IMapperCollection Mappers => Services.GetRequiredService(); - #region Builders - protected UserBuilder UserBuilderInstance = new UserBuilder(); protected UserGroupBuilder UserGroupBuilderInstance = new UserGroupBuilder(); - #endregion - protected static bool FirstTestInSession = true; protected bool FirstTestInFixture = true; diff --git a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs index 2feccbcccb..af8822ad19 100644 --- a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs +++ b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using NUnit.Framework; using Umbraco.Core.Models; @@ -21,8 +24,7 @@ namespace Umbraco.Tests.Integration.Testing public virtual void CreateTestData() { // NOTE Maybe not the best way to create/save test data as we are using the services, which are being tested. - - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // Create and Save ContentType "umbTextpage" -> 1051 (template), 1052 (content type) diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs index 314a50ce75..11773b157e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.IO; using System.Text; @@ -17,30 +20,30 @@ namespace Umbraco.Tests.IO [Test] public void Can_Get_MediaFileSystem() { - var fileSystem = GetRequiredService(); + IMediaFileSystem fileSystem = GetRequiredService(); Assert.NotNull(fileSystem); } [Test] public void Can_Get_IMediaFileSystem() { - var fileSystem = GetRequiredService(); + IMediaFileSystem fileSystem = GetRequiredService(); Assert.NotNull(fileSystem); } [Test] public void IMediaFileSystem_Is_Singleton() { - var fileSystem1 = GetRequiredService(); - var fileSystem2 = GetRequiredService(); + IMediaFileSystem fileSystem1 = GetRequiredService(); + IMediaFileSystem fileSystem2 = GetRequiredService(); Assert.AreSame(fileSystem1, fileSystem2); } [Test] public void Can_Unwrap_MediaFileSystem() { - var fileSystem = GetRequiredService(); - var unwrapped = fileSystem.Unwrap(); + IMediaFileSystem fileSystem = GetRequiredService(); + IFileSystem unwrapped = fileSystem.Unwrap(); Assert.IsNotNull(unwrapped); var physical = unwrapped as PhysicalFileSystem; Assert.IsNotNull(physical); @@ -49,21 +52,21 @@ namespace Umbraco.Tests.IO [Test] public void Can_Delete_MediaFiles() { - var fs = GetRequiredService(); + IMediaFileSystem fs = GetRequiredService(); var ms = new MemoryStream(Encoding.UTF8.GetBytes("test")); - var virtPath = fs.GetMediaPath("file.txt", Guid.NewGuid(), Guid.NewGuid()); + string virtPath = fs.GetMediaPath("file.txt", Guid.NewGuid(), Guid.NewGuid()); fs.AddFile(virtPath, ms); // ~/media/1234/file.txt exists - var hostingEnvironment = GetRequiredService(); - var physPath = hostingEnvironment.MapPathWebRoot(Path.Combine("media", virtPath)); + IHostingEnvironment hostingEnvironment = GetRequiredService(); + string physPath = hostingEnvironment.MapPathWebRoot(Path.Combine("media", virtPath)); Assert.IsTrue(File.Exists(physPath)); // ~/media/1234/file.txt is gone fs.DeleteMediaFiles(new[] { virtPath }); Assert.IsFalse(File.Exists(physPath)); - var scheme = GetRequiredService(); + IMediaPathScheme scheme = GetRequiredService(); if (scheme is UniqueMediaPathScheme) { // ~/media/1234 is *not* gone @@ -82,7 +85,6 @@ namespace Umbraco.Tests.IO Assert.IsTrue(Directory.Exists(physPath)); } - // FIXME: don't make sense anymore /* [Test] diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs index fb34c7b467..77b82a22bf 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs @@ -1,4 +1,8 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; +using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; @@ -37,23 +41,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void MemberTypeSave_To_IMemberType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); - var display = CreateMemberTypeSave(dataType.Id); + MemberTypeSave display = CreateMemberTypeSave(dataType.Id); + // Act + IMemberType result = _sut.Map(display); - //Act - - var result = _sut.Map(display); - - //Assert - + // Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); @@ -69,13 +70,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); - for (var i = 0; i < display.Groups.Count(); i++) + for (int i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); - var propTypes = display.Groups.ElementAt(i).Properties; + IEnumerable propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); @@ -86,7 +87,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < display.AllowedContentTypes.Count(); i++) + for (int i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } @@ -95,22 +96,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void MediaTypeSave_To_IMediaType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); - var display = CreateMediaTypeSave(dataType.Id); + MediaTypeSave display = CreateMediaTypeSave(dataType.Id); - //Act - - var result = _sut.Map(display); - - //Assert + // Act + IMediaType result = _sut.Map(display); + // Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); @@ -126,13 +125,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); - for (var i = 0; i < display.Groups.Count(); i++) + for (int i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); - var propTypes = display.Groups.ElementAt(i).Properties; + IEnumerable propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); @@ -140,7 +139,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < display.AllowedContentTypes.Count(); i++) + for (int i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } @@ -149,8 +148,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void ContentTypeSave_To_IContentType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -159,25 +158,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping var templates = new ITemplate[] { - //Note the aliases is important - TODO use builder + // Note the aliases is important - TODO use builder new Template(Services.GetRequiredService(), "Name 1", "test"), new Template(Services.GetRequiredService(), "Name 2", "template1"), new Template(Services.GetRequiredService(), "Name 3", "template2"), }; - foreach (var template in templates) + foreach (ITemplate template in templates) { _fileService.SaveTemplate(template); } - var display = CreateContentTypeSave(dataType.Id); + DocumentTypeSave display = CreateContentTypeSave(dataType.Id); - //Act - - var result = _sut.Map(display); - - //Assert + // Act + IContentType result = _sut.Map(display); + // Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); @@ -193,13 +190,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); - for (var i = 0; i < display.Groups.Count(); i++) + for (int i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); - var propTypes = display.Groups.ElementAt(i).Properties; + IEnumerable propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); @@ -207,18 +204,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } } - var allowedTemplateAliases = display.AllowedTemplates - .Concat(new[] {display.DefaultTemplate}) + IEnumerable allowedTemplateAliases = display.AllowedTemplates + .Concat(new[] { display.DefaultTemplate }) .Distinct(); Assert.AreEqual(allowedTemplateAliases.Count(), result.AllowedTemplates.Count()); - for (var i = 0; i < display.AllowedTemplates.Count(); i++) + for (int i = 0; i < display.AllowedTemplates.Count(); i++) { Assert.AreEqual(display.AllowedTemplates.ElementAt(i), result.AllowedTemplates.ElementAt(i).Alias); } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < display.AllowedContentTypes.Count(); i++) + for (int i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } @@ -227,47 +224,43 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void MediaTypeSave_With_Composition_To_IMediaType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); + MediaTypeSave display = CreateCompositionMediaTypeSave(dataType.Id); - var display = CreateCompositionMediaTypeSave(dataType.Id); + // Act + IMediaType result = _sut.Map(display); - //Act - - var result = _sut.Map(display); - - //Assert + // Assert + Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void ContentTypeSave_With_Composition_To_IContentType() { - //Arrange + // Arrange - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); - var display = CreateCompositionContentTypeSave(dataType.Id); + DocumentTypeSave display = CreateCompositionContentTypeSave(dataType.Id); - //Act - - var result = _sut.Map(display); - - //Assert + // Act + IContentType result = _sut.Map(display); + // Assert // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } @@ -275,20 +268,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void IMemberType_To_MemberTypeDisplay() { - //Arrange - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); - var alias = memberType.PropertyTypes.Last().Alias; + // Arrange + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); + string alias = memberType.PropertyTypes.Last().Alias; memberType.SetIsSensitiveProperty(alias, true); memberType.SetMemberCanEditProperty(alias, true); memberType.SetMemberCanViewProperty(alias, true); MemberTypeBuilder.EnsureAllIds(memberType, 8888); - //Act - - var result = _sut.Map(memberType); - - //Assert + // Act + MemberTypeDisplay result = _sut.Map(memberType); + // Assert Assert.AreEqual(memberType.Alias, result.Alias); Assert.AreEqual(memberType.Description, result.Description); Assert.AreEqual(memberType.Icon, result.Icon); @@ -301,17 +292,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(memberType.CreateDate, result.CreateDate); Assert.AreEqual(memberType.UpdateDate, result.UpdateDate); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(memberType.PropertyGroups.Count(), result.Groups.Count()); - for (var i = 0; i < memberType.PropertyGroups.Count(); i++) + for (int i = 0; i < memberType.PropertyGroups.Count(); i++) { Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); - var propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes; + PropertyTypeCollection propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); @@ -322,28 +311,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(memberType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < memberType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < memberType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(memberType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } - [Test] public void IMediaType_To_MediaTypeDisplay() { - //Arrange - - var mediaType = MediaTypeBuilder.CreateImageMediaType(); + // Arrange + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType(); MediaTypeBuilder.EnsureAllIds(mediaType, 8888); - //Act - - var result = _sut.Map(mediaType); - - //Assert + // Act + MediaTypeDisplay result = _sut.Map(mediaType); + // Assert Assert.AreEqual(mediaType.Alias, result.Alias); Assert.AreEqual(mediaType.Description, result.Description); Assert.AreEqual(mediaType.Icon, result.Icon); @@ -356,17 +340,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(mediaType.CreateDate, result.CreateDate); Assert.AreEqual(mediaType.UpdateDate, result.UpdateDate); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(mediaType.PropertyGroups.Count(), result.Groups.Count()); - for (var i = 0; i < mediaType.PropertyGroups.Count(); i++) + for (int i = 0; i < mediaType.PropertyGroups.Count(); i++) { Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); - var propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes; + PropertyTypeCollection propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); @@ -374,31 +356,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(mediaType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < mediaType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < mediaType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(mediaType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } [Test] public void IContentType_To_ContentTypeDisplay() { - //Arrange - // _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) - // .Returns(new DataType(new VoidEditor(Mock.Of(), Mock.Of(), Mock.Of(),Mock.Of(), Mock.Of()))); + // Arrange + //// _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) + //// .Returns(new DataType(new VoidEditor(Mock.Of(), Mock.Of(), Mock.Of(),Mock.Of(), Mock.Of()))); // - // // setup the mocks to return the data we want to test against... - - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + // setup the mocks to return the data we want to test against... + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); ContentTypeBuilder.EnsureAllIds(contentType, 8888); - //Act - - var result = _sut.Map(contentType); - - //Assert + // Act + DocumentTypeDisplay result = _sut.Map(contentType); + // Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); @@ -412,17 +390,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(contentType.PropertyGroups.Count, result.Groups.Count()); - for (var i = 0; i < contentType.PropertyGroups.Count; i++) + for (int i = 0; i < contentType.PropertyGroups.Count; i++) { Assert.AreEqual(contentType.PropertyGroups[i].Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(contentType.PropertyGroups[i].Name, result.Groups.ElementAt(i).Name); - var propTypes = contentType.PropertyGroups[i].PropertyTypes; + PropertyTypeCollection propTypes = contentType.PropertyGroups[i].PropertyTypes; Assert.AreEqual(propTypes.Count, result.Groups.ElementAt(i).Properties.Count()); - for (var j = 0; j < propTypes.Count; j++) + for (int j = 0; j < propTypes.Count; j++) { Assert.AreEqual(propTypes[j].Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes[j].DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); @@ -431,23 +407,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); - for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) + for (int i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } [Test] public void MemberPropertyGroupBasic_To_MemberPropertyGroup() { - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -510,8 +485,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such - //var result = Mapper.Map(basic); - var result = _sut.Map(contentType).PropertyGroups[0]; + // var result = Mapper.Map(basic); + PropertyGroup result = _sut.Map(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); @@ -579,8 +554,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such - //var result = Mapper.Map(basic); - var result = _sut.Map(contentType).PropertyGroups[0]; + // var result = Mapper.Map(basic); + PropertyGroup result = _sut.Map(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); @@ -609,7 +584,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + IPropertyType result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -627,7 +602,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void PropertyTypeBasic_To_PropertyType() { - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -652,7 +627,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + IPropertyType result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -670,50 +645,50 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void IMediaTypeComposition_To_MediaTypeDisplay() { - //Arrange - var ctMain = MediaTypeBuilder.CreateSimpleMediaType("parent", "Parent"); - //not assigned to tab + // Arrange + MediaType ctMain = MediaTypeBuilder.CreateSimpleMediaType("parent", "Parent"); + + // not assigned to tab ctMain.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MediaTypeBuilder.EnsureAllIds(ctMain, 8888); - var ctChild1 = MediaTypeBuilder.CreateSimpleMediaType("child1", "Child 1", ctMain, true); - ctChild1.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) - { - Alias = "someProperty", - Name = "Some Property", - Description = "", - Mandatory = false, - SortOrder = 1, - DataTypeId = -88 - }, "Another tab"); + MediaType ctChild1 = MediaTypeBuilder.CreateSimpleMediaType("child1", "Child 1", ctMain, true); + ctChild1.AddPropertyType( + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) + { + Alias = "someProperty", + Name = "Some Property", + Description = string.Empty, + Mandatory = false, + SortOrder = 1, + DataTypeId = -88 + }, "Another tab"); MediaTypeBuilder.EnsureAllIds(ctChild1, 7777); - var contentType = MediaTypeBuilder.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup"); - //not assigned to tab + MediaType contentType = MediaTypeBuilder.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup"); + + // not assigned to tab contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MediaTypeBuilder.EnsureAllIds(contentType, 6666); + // Act + MediaTypeDisplay result = _sut.Map(contentType); - //Act - - var result = _sut.Map(contentType); - - //Assert - + // Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); @@ -726,15 +701,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); - var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); - var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); - var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); + PropertyTypeDisplay[] allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); + int[] allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); + int[] allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); @@ -743,9 +716,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id })); - Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } @@ -754,41 +726,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void IContentTypeComposition_To_ContentTypeDisplay() { - //Arrange + // Arrange + ContentType ctMain = ContentTypeBuilder.CreateSimpleContentType(); - var ctMain = ContentTypeBuilder.CreateSimpleContentType(); - //not assigned to tab + // not assigned to tab ctMain.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { - Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Alias = "umbracoUrlName", Name = "Slug", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); ContentTypeBuilder.EnsureAllIds(ctMain, 8888); - var ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true); - ctChild1.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) - { - Alias = "someProperty", - Name = "Some Property", - Description = "", - Mandatory = false, - SortOrder = 1, - DataTypeId = -88 - }, "Another tab"); + ContentType ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true); + ctChild1.AddPropertyType( + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) + { + Alias = "someProperty", + Name = "Some Property", + Description = string.Empty, + Mandatory = false, + SortOrder = 1, + DataTypeId = -88 + }, "Another tab"); ContentTypeBuilder.EnsureAllIds(ctChild1, 7777); - var contentType = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, propertyGroupName: "CustomGroup"); - //not assigned to tab + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, propertyGroupName: "CustomGroup"); + + // not assigned to tab contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { - Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Alias = "umbracoUrlAlias", Name = "AltUrl", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); ContentTypeBuilder.EnsureAllIds(contentType, 6666); + // Act + DocumentTypeDisplay result = _sut.Map(contentType); - //Act - - var result = _sut.Map(contentType); - - //Assert - + // Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); @@ -802,35 +773,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); - var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); - var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); - var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); + PropertyTypeDisplay[] allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); + int[] allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); + int[] allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); - Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] {ctMain.Id, ctChild1.Id})); + Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id })); Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); - for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) + for (int i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } [Test] @@ -855,7 +823,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + MemberPropertyTypeDisplay result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -873,7 +841,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void PropertyTypeBasic_To_PropertyTypeDisplay() { - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -895,7 +863,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + PropertyTypeDisplay result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -907,9 +875,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(basic.Validation, result.Validation); } - private MemberTypeSave CreateMemberTypeSave(int dataTypeId) - { - return new MemberTypeSave + private MemberTypeSave CreateMemberTypeSave(int dataTypeId) => + new MemberTypeSave { Alias = "test", AllowAsRoot = true, @@ -924,41 +891,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] - { - new PropertyGroupBasic() { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] + new PropertyGroupBasic() { - new MemberPropertyTypeBasic + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] { - MemberCanEditProperty = true, - MemberCanViewProperty = true, - IsSensitiveData = true, - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation + new MemberPropertyTypeBasic { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - DataTypeId = dataTypeId + MemberCanEditProperty = true, + MemberCanViewProperty = true, + IsSensitiveData = true, + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + DataTypeId = dataTypeId + } } } } - } }; - } - private MediaTypeSave CreateMediaTypeSave(int dataTypeId) - { - return new MediaTypeSave + private MediaTypeSave CreateMediaTypeSave(int dataTypeId) => + new MediaTypeSave { Alias = "test", AllowAsRoot = true, @@ -973,173 +938,44 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] - { - new PropertyGroupBasic() { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] + new PropertyGroupBasic() { - new PropertyTypeBasic + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation + new PropertyTypeBasic { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - DataTypeId = dataTypeId + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + DataTypeId = dataTypeId + } } } } - } }; - } - private DocumentTypeSave CreateContentTypeSave(int dataTypeId) - { - return new DocumentTypeSave - { - Alias = "test", - AllowAsRoot = true, - AllowedTemplates = new [] - { - "template1", - "template2" - }, - AllowedContentTypes = new [] {666, 667}, - DefaultTemplate = "test", - Description = "hello world", - Icon = "tree-icon", - Id = 1234, - Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), - Name = "My content type", - Path = "-1,1234", - ParentId = -1, - Thumbnail = "tree-thumb", - IsContainer = true, - Groups = new [] - { - new PropertyGroupBasic() - { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = true, - DataTypeId = dataTypeId - } - } - } - } - }; - } - - private MediaTypeSave CreateCompositionMediaTypeSave(int dataTypeId) - { - return new MediaTypeSave - { - Alias = "test", - AllowAsRoot = true, - AllowedContentTypes = new[] { 666, 667 }, - Description = "hello world", - Icon = "tree-icon", - Id = 1234, - Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), - Name = "My content type", - Path = "-1,1234", - ParentId = -1, - Thumbnail = "tree-thumb", - IsContainer = true, - Groups = new[] - { - new PropertyGroupBasic() - { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = true, - DataTypeId = dataTypeId - } - } - }, - new PropertyGroupBasic() - { - Id = 894, - Name = "Tab 2", - SortOrder = 0, - Inherited = true, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "parentProperty", - Description = "this is a property from the parent", - Inherited = true, - Label = "Parent property", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = false, - DataTypeId = dataTypeId - } - } - - } - } - - }; - } - - private DocumentTypeSave CreateCompositionContentTypeSave(int dataTypeId) - { - return new DocumentTypeSave + private DocumentTypeSave CreateContentTypeSave(int dataTypeId) => + new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new[] - { - "template1", - "template2" - }, + { + "template1", + "template2" + }, AllowedContentTypes = new[] { 666, 667 }, DefaultTemplate = "test", Description = "hello world", @@ -1152,61 +988,179 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] - { - new PropertyGroupBasic() { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] + new PropertyGroupBasic() { - new PropertyTypeBasic + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation + new PropertyTypeBasic { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = true, - DataTypeId = dataTypeId + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = true, + DataTypeId = dataTypeId + } + } + } + } + }; + + private MediaTypeSave CreateCompositionMediaTypeSave(int dataTypeId) => + new MediaTypeSave + { + Alias = "test", + AllowAsRoot = true, + AllowedContentTypes = new[] { 666, 667 }, + Description = "hello world", + Icon = "tree-icon", + Id = 1234, + Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), + Name = "My content type", + Path = "-1,1234", + ParentId = -1, + Thumbnail = "tree-thumb", + IsContainer = true, + Groups = new[] + { + new PropertyGroupBasic() + { + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = true, + DataTypeId = dataTypeId + } + } + }, + new PropertyGroupBasic() + { + Id = 894, + Name = "Tab 2", + SortOrder = 0, + Inherited = true, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "parentProperty", + Description = "this is a property from the parent", + Inherited = true, + Label = "Parent property", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = false, + DataTypeId = dataTypeId + } + } + } + } + }; + + private DocumentTypeSave CreateCompositionContentTypeSave(int dataTypeId) => + new DocumentTypeSave + { + Alias = "test", + AllowAsRoot = true, + AllowedTemplates = new[] + { + "template1", + "template2" + }, + AllowedContentTypes = new[] { 666, 667 }, + DefaultTemplate = "test", + Description = "hello world", + Icon = "tree-icon", + Id = 1234, + Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), + Name = "My content type", + Path = "-1,1234", + ParentId = -1, + Thumbnail = "tree-thumb", + IsContainer = true, + Groups = new[] + { + new PropertyGroupBasic() + { + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = true, + DataTypeId = dataTypeId + } + } + }, + new PropertyGroupBasic() + { + Id = 894, + Name = "Tab 2", + SortOrder = 0, + Inherited = true, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "parentProperty", + Description = "this is a property from the parent", + Inherited = true, + Label = "Parent property", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = false, + DataTypeId = dataTypeId + } } } - }, - new PropertyGroupBasic() - { - Id = 894, - Name = "Tab 2", - SortOrder = 0, - Inherited = true, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "parentProperty", - Description = "this is a property from the parent", - Inherited = true, - Label = "Parent property", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = false, - DataTypeId = dataTypeId - } - } - } - } - }; - } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs index 244e8c8d1a..a7152e7a3c 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Globalization; using System.Linq; using Microsoft.Extensions.DependencyInjection; @@ -42,11 +45,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping private IContentTypeService _contentTypeService; private ILocalizedTextService _localizedTextService; - [Test] public void To_Media_Item_Simple() { - var content = _mediaBuilder + Media content = _mediaBuilder .AddMediaType() .AddPropertyGroup() .AddPropertyType() @@ -56,11 +58,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map>(content); + ContentItemBasic result = _sut.Map>(content); AssertBasics(result, content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertBasicProperty(result, p); } @@ -69,7 +71,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Content_Item_Simple() { - var content = _contentBuilder + Content content = _contentBuilder .AddContentType() .AddPropertyGroup() .AddPropertyType() @@ -79,11 +81,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map>(content); + ContentItemBasic result = _sut.Map>(content); AssertBasics(result, content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertBasicProperty(result, p); } @@ -92,7 +94,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Content_Item_Dto() { - var content = _contentBuilder + Content content = _contentBuilder .AddContentType() .AddPropertyGroup() .AddPropertyType() @@ -102,9 +104,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentPropertyCollectionDto result = _sut.Map(content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertProperty(result, p); } @@ -113,7 +115,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Media_Item_Dto() { - var content = _mediaBuilder + Media content = _mediaBuilder .AddMediaType() .AddPropertyGroup() .AddPropertyType() @@ -122,35 +124,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .Done() .Build(); - var result = _sut.Map(content); + ContentPropertyCollectionDto result = _sut.Map(content); Assert.GreaterOrEqual(result.Properties.Count(), 1); Assert.AreEqual(content.Properties.Count, result.Properties.Count()); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertProperty(result, p); } } - #region Assertions - private void AssertDisplayProperty(IContentProperties result, IProperty p) where T : ContentPropertyBasic { - var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); + T pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); Assert.IsNotNull(pDto); - //pDto.Alias = p.Alias; - //pDto.Description = p.PropertyType.Description; - //pDto.Label = p.PropertyType.Name; - //pDto.Config = applicationContext.Services.DataTypeService.GetPreValuesByDataTypeId(p.PropertyType.DataTypeDefinitionId); - + // pDto.Alias = p.Alias; + // pDto.Description = p.PropertyType.Description; + // pDto.Label = p.PropertyType.Name; + // pDto.Config = applicationContext.Services.DataTypeService.GetPreValuesByDataTypeId(p.PropertyType.DataTypeDefinitionId); } [Test] public void To_Display_Model() { - var contentType = _contentTypeBuilder + IContentType contentType = _contentTypeBuilder .WithId(0) .AddPropertyGroup() .WithId(1) @@ -175,17 +174,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .Build(); _contentTypeService.Save(contentType); - var content = _contentBuilder + Content content = _contentBuilder .WithContentType(contentType) .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentItemDisplay result = _sut.Map(content); AssertBasics(result, content); - var invariantContent = result.Variants.First(); - foreach (var p in content.Properties) + ContentVariantDisplay invariantContent = result.Variants.First(); + foreach (IProperty p in content.Properties) { AssertBasicProperty(invariantContent, p); AssertDisplayProperty(invariantContent, p); @@ -199,22 +198,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Display_Model_No_Tabs() { - var contentType = _contentTypeBuilder + IContentType contentType = _contentTypeBuilder .WithId(0) .Build(); _contentTypeService.Save(contentType); - var content = _contentBuilder + Content content = _contentBuilder .WithContentType(contentType) .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentItemDisplay result = _sut.Map(content); AssertBasics(result, content); - var invariantContent = result.Variants.First(); - foreach (var p in content.Properties) + ContentVariantDisplay invariantContent = result.Variants.First(); + foreach (IProperty p in content.Properties) { AssertBasicProperty(invariantContent, p); AssertDisplayProperty(invariantContent, p); @@ -226,7 +225,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Display_Model_With_Non_Grouped_Properties() { - var contentType = _contentTypeBuilder + IContentType contentType = _contentTypeBuilder .WithId(0) .AddPropertyType() .WithId(1) @@ -243,17 +242,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .Build(); _contentTypeService.Save(contentType); - var content = _contentBuilder + Content content = _contentBuilder .WithContentType(contentType) .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentItemDisplay result = _sut.Map(content); AssertBasics(result, content); - var invariantContent = result.Variants.First(); - foreach (var p in content.Properties) + ContentVariantDisplay invariantContent = result.Variants.First(); + foreach (IProperty p in content.Properties) { AssertBasicProperty(invariantContent, p); AssertDisplayProperty(invariantContent, p); @@ -268,7 +267,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { Assert.AreEqual(content.Id, result.Id); - var ownerId = content.CreatorId; + int ownerId = content.CreatorId; if (ownerId != 0) { Assert.IsNotNull(result.Owner); @@ -280,13 +279,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.IsNull(result.Owner); // because, 0 is no user } - var invariantContent = result.Variants.First(); + ContentVariantDisplay invariantContent = result.Variants.First(); Assert.AreEqual(content.ParentId, result.ParentId); Assert.AreEqual(content.UpdateDate, invariantContent.UpdateDate); Assert.AreEqual(content.CreateDate, invariantContent.CreateDate); Assert.AreEqual(content.Name, invariantContent.Name); - Assert.AreEqual(content.Properties.Count(), + Assert.AreEqual( + content.Properties.Count(), ((IContentProperties)invariantContent).Properties.Count(x => x.Alias.StartsWith("_umb_") == false)); } @@ -296,7 +296,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { Assert.AreEqual(content.Id, result.Id); - var ownerId = content.CreatorId; + int ownerId = content.CreatorId; if (ownerId != 0) { Assert.IsNotNull(result.Owner); @@ -318,24 +318,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping private void AssertBasicProperty(IContentProperties result, IProperty p) where T : ContentPropertyBasic { - var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); + T pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); Assert.IsNotNull(pDto); Assert.AreEqual(p.Alias, pDto.Alias); Assert.AreEqual(p.Id, pDto.Id); if (p.GetValue() == null) + { Assert.AreEqual(pDto.Value, string.Empty); - else if (p.GetValue() is decimal) - Assert.AreEqual(pDto.Value, ((decimal) p.GetValue()).ToString(NumberFormatInfo.InvariantInfo)); + } + else if (p.GetValue() is decimal decimalValue) + { + Assert.AreEqual(pDto.Value, decimalValue.ToString(NumberFormatInfo.InvariantInfo)); + } else + { Assert.AreEqual(pDto.Value, p.GetValue().ToString()); + } } private void AssertProperty(IContentProperties result, IProperty p) { AssertBasicProperty(result, p); - var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); + ContentPropertyDto pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); Assert.IsNotNull(pDto); Assert.AreEqual(p.PropertyType.Mandatory, pDto.IsRequired); Assert.AreEqual(p.PropertyType.ValidationRegExp, pDto.ValidationRegExp); @@ -350,11 +356,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { AssertBasics(result, content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertProperty(result, p); } } - #endregion } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs index f8c276d429..ac7c248058 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using NUnit.Framework; @@ -12,29 +15,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { [TestFixture] [UmbracoTest(Mapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class UserModelMapperTests: UmbracoIntegrationTest + public class UserModelMapperTests : UmbracoIntegrationTest { private UmbracoMapper _sut; [SetUp] - public void Setup() - { - _sut = Services.GetRequiredService(); - } + public void Setup() => _sut = Services.GetRequiredService(); [Test] public void Map_UserGroupSave_To_IUserGroup() { - IUserGroup userGroup = new UserGroup(ShortStringHelper, 0, "alias", "name", new List { "c" }, "icon"); - userGroup.Id = 42; + IUserGroup userGroup = new UserGroup(ShortStringHelper, 0, "alias", "name", new List { "c" }, "icon") + { + Id = 42 + }; - // userGroup.permissions is System.Collections.Generic.List`1[System.String] + // userGroup.permissions is List`1[System.String] // userGroup.permissions is System.Linq.Enumerable+WhereSelectArrayIterator`2[System.Char, System.String] - // fixed: now System.Collections.Generic.List`1[System.String] - + // fixed: now List`1[System.String] const string json = "{\"id\":@@@ID@@@,\"alias\":\"perm1\",\"name\":\"Perm1\",\"icon\":\"icon-users\",\"sections\":[\"content\"],\"users\":[],\"defaultPermissions\":[\"F\",\"C\",\"A\"],\"assignedPermissions\":{},\"startContentId\":-1,\"startMediaId\":-1,\"action\":\"save\",\"parentId\":-1}"; - var userGroupSave = JsonConvert.DeserializeObject(json.Replace("@@@ID@@@", userGroup.Id.ToString())); + UserGroupSave userGroupSave = JsonConvert.DeserializeObject(json.Replace("@@@ID@@@", userGroup.Id.ToString())); // failed, AutoMapper complained, "Unable to cast object of type 'WhereSelectArrayIterator`2[System.Char,System.String]' to type 'System.Collections.IList'". // FIXME: added ToList() in UserGroupFactory diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs index e3ec2d872b..603d5a87b3 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; @@ -24,41 +27,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging private Guid _testBaseFolder; [SetUp] - public void SetupTestData() - { - _testBaseFolder = Guid.NewGuid(); - } + public void SetupTestData() => _testBaseFolder = Guid.NewGuid(); [TearDown] - public void DeleteTestFolder() - { - //clear out files/folders + public void DeleteTestFolder() => Directory.Delete(HostingEnvironment.MapPathContentRoot("~/" + _testBaseFolder), true); - } private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IMacroService MacroService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IEntityXmlSerializer EntityXmlSerializer => GetRequiredService(); + private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IUmbracoVersion UmbracoVersion => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); public ICreatedPackagesRepository PackageBuilder => new PackagesRepository( - ContentService, ContentTypeService, DataTypeService, - FileService, MacroService, LocalizationService, + ContentService, + ContentTypeService, + DataTypeService, + FileService, + MacroService, + LocalizationService, HostingEnvironment, - EntityXmlSerializer, LoggerFactory, + EntityXmlSerializer, + LoggerFactory, UmbracoVersion, Microsoft.Extensions.Options.Options.Create(new GlobalSettings()), MediaService, MediaTypeService, "createdPackages.config", - //temp paths + + // temp paths tempFolderPath: "~/" + _testBaseFolder + "/temp", packagesFolderPath: "~/" + _testBaseFolder + "/packages", mediaFolderPath: "~/" + _testBaseFolder + "/media"); @@ -74,7 +87,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def1); + bool result = PackageBuilder.SavePackage(def1); Assert.IsTrue(result); PackageBuilder.Delete(def1.Id); @@ -94,7 +107,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def1); + bool result = PackageBuilder.SavePackage(def1); Assert.IsTrue(result); Assert.AreEqual(1, def1.Id); @@ -120,14 +133,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging { var def = new PackageDefinition { - Id = 3, //doesn't exist + Id = 3, // doesn't exist Name = "test", Url = "http://test.com", Author = "Someone", AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def); + bool result = PackageBuilder.SavePackage(def); Assert.IsFalse(result); } @@ -142,28 +155,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging Author = "Someone", AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def); + bool result = PackageBuilder.SavePackage(def); def.Name = "updated"; - def.Files = new List {"hello.txt", "world.png"}; + def.Files = new List { "hello.txt", "world.png" }; result = PackageBuilder.SavePackage(def); Assert.IsTrue(result); - //re-get + // re-get def = PackageBuilder.GetById(def.Id); Assert.AreEqual("updated", def.Name); Assert.AreEqual(2, def.Files.Count); - // TODO: There's a whole lot more assertions to be done + // TODO: There's a whole lot more assertions to be done } [Test] public void Export() { - var file1 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/package.manifest"; - var file2 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/styles.css"; - var mappedFile1 = HostingEnvironment.MapPathContentRoot(file1); - var mappedFile2 = HostingEnvironment.MapPathContentRoot(file2); + string file1 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/package.manifest"; + string file2 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/styles.css"; + string mappedFile1 = HostingEnvironment.MapPathContentRoot(file1); + string mappedFile2 = HostingEnvironment.MapPathContentRoot(file2); Directory.CreateDirectory(Path.GetDirectoryName(mappedFile1)); Directory.CreateDirectory(Path.GetDirectoryName(mappedFile2)); File.WriteAllText(mappedFile1, "hello world"); @@ -178,28 +191,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging Files = new List { file1, file2 }, Actions = "" }; - var result = PackageBuilder.SavePackage(def); + bool result = PackageBuilder.SavePackage(def); Assert.IsTrue(result); Assert.IsTrue(def.PackagePath.IsNullOrWhiteSpace()); - var zip = PackageBuilder.ExportPackage(def); + string zip = PackageBuilder.ExportPackage(def); - def = PackageBuilder.GetById(def.Id); //re-get + def = PackageBuilder.GetById(def.Id); // re-get Assert.IsNotNull(def.PackagePath); - using (var archive = ZipFile.OpenRead(HostingEnvironment.MapPathWebRoot(zip))) + using (ZipArchive archive = ZipFile.OpenRead(HostingEnvironment.MapPathWebRoot(zip))) { Assert.AreEqual(3, archive.Entries.Count); - //the 2 files we manually added + // the 2 files we manually added Assert.IsNotNull(archive.Entries.Where(x => x.Name == "package.manifest")); Assert.IsNotNull(archive.Entries.Where(x => x.Name == "styles.css")); - //this is the actual package definition/manifest (not the developer manifest!) - var packageXml = archive.Entries.FirstOrDefault(x => x.Name == "package.xml"); + // this is the actual package definition/manifest (not the developer manifest!) + ZipArchiveEntry packageXml = archive.Entries.FirstOrDefault(x => x.Name == "package.xml"); Assert.IsNotNull(packageXml); - using (var stream = packageXml.Open()) + using (Stream stream = packageXml.Open()) { var xml = XDocument.Load(stream); Assert.AreEqual("umbPackage", xml.Root.Name.ToString()); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.cs index f250a43b7f..defdf1b25c 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Xml.Linq; @@ -13,6 +16,7 @@ using Umbraco.Core.Models.Packaging; using Umbraco.Core.Packaging; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Core.Strings; @@ -29,6 +33,7 @@ namespace Umbraco.Tests.Packaging public class PackageDataInstallationTests : UmbracoIntegrationTestWithContent { private ILocalizationService LocalizationService => GetRequiredService(); + private IMacroService MacroService => GetRequiredService(); [HideFromTypeFinder] @@ -46,40 +51,39 @@ namespace Umbraco.Tests.Packaging public class Editor2 : DataEditor { public Editor2(ILoggerFactory loggerFactory) - : base(loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(),Mock.Of(), new JsonNetSerializer()) + : base(loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()) { } } - // protected override void Compose() - // { - // base.Compose(); - // - // // the packages that are used by these tests reference totally bogus property - // // editors that must exist - so they are defined here - and in order not to - // // pollute everything, they are ignored by the type finder and explicitely - // // added to the editors collection - // - // Builder.WithCollectionBuilder() - // .Add() - // .Add(); - // } - // - // protected override void ComposeApplication(bool withApplication) - // { - // base.ComposeApplication(withApplication); - // - // if (!withApplication) return; - // - // // re-register with actual media fs - // Builder.ComposeFileSystems(); - // } + //// protected override void Compose() + //// { + //// base.Compose(); + //// + //// // the packages that are used by these tests reference totally bogus property + //// // editors that must exist - so they are defined here - and in order not to + //// // pollute everything, they are ignored by the type finder and explicitely + //// // added to the editors collection + //// + //// Builder.WithCollectionBuilder() + //// .Add() + //// .Add(); + //// } + //// + //// protected override void ComposeApplication(bool withApplication) + //// { + //// base.ComposeApplication(withApplication); + //// + //// if (!withApplication) return; + //// + //// // re-register with actual media fs + //// Builder.ComposeFileSystems(); + //// } private PackageDataInstallation PackageDataInstallation => GetRequiredService(); - private IContentService ContentService => GetRequiredService(); - private IContentTypeService ContentTypeService => GetRequiredService(); private IMediaService MediaService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); [Test] @@ -88,17 +92,17 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.uBlogsy_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + int numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(dataTypes.Any(), Is.True); @@ -107,11 +111,11 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Any(), Is.True); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); - var uBlogsyBaseDocType = contentTypes.First(x => x.Alias == "uBlogsyBaseDocType"); + IContentType uBlogsyBaseDocType = contentTypes.First(x => x.Alias == "uBlogsyBaseDocType"); Assert.That(uBlogsyBaseDocType.PropertyTypes.Count(), Is.EqualTo(5)); Assert.That(uBlogsyBaseDocType.PropertyGroups.Any(), Is.False); - var uBlogsyBasePage = contentTypes.First(x => x.Alias == "uBlogsyBasePage"); + IContentType uBlogsyBasePage = contentTypes.First(x => x.Alias == "uBlogsyBasePage"); Assert.That(uBlogsyBasePage.ContentTypeCompositionExists("uBlogsyBaseDocType"), Is.True); Assert.That(uBlogsyBasePage.PropertyTypes.Count(), Is.EqualTo(7)); Assert.That(uBlogsyBasePage.PropertyGroups.Count, Is.EqualTo(3)); @@ -120,7 +124,7 @@ namespace Umbraco.Tests.Packaging Assert.That(uBlogsyBasePage.PropertyGroups["Navigation"].PropertyTypes.Count(), Is.EqualTo(1)); Assert.That(uBlogsyBasePage.CompositionPropertyTypes.Count(), Is.EqualTo(12)); - var uBlogsyLanding = contentTypes.First(x => x.Alias == "uBlogsyLanding"); + IContentType uBlogsyLanding = contentTypes.First(x => x.Alias == "uBlogsyLanding"); Assert.That(uBlogsyLanding.ContentTypeCompositionExists("uBlogsyBasePage"), Is.True); Assert.That(uBlogsyLanding.ContentTypeCompositionExists("uBlogsyBaseDocType"), Is.True); Assert.That(uBlogsyLanding.PropertyTypes.Count(), Is.EqualTo(5)); @@ -133,23 +137,23 @@ namespace Umbraco.Tests.Packaging public void Can_Import_Inherited_ContentTypes_And_Verify_PropertyTypes_UniqueIds() { // Arrange - var strXml = ImportResources.InheritedDocTypes_Package; + string strXml = ImportResources.InheritedDocTypes_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); // Assert - var mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); - using (var scope = ScopeProvider.CreateScope()) - foreach (var propertyType in mRBasePage.PropertyTypes) + IContentType mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); + using IScope scope = ScopeProvider.CreateScope(); + foreach (IPropertyType propertyType in mRBasePage.PropertyTypes) { - var propertyTypeDto = scope.Database.First("WHERE id = @id", new { id = propertyType.Id }); + PropertyTypeDto propertyTypeDto = scope.Database.First("WHERE id = @id", new { id = propertyType.Id }); Assert.AreEqual(propertyTypeDto.UniqueId, propertyType.Key); } } @@ -160,16 +164,16 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.InheritedDocTypes_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(dataTypes.Any(), Is.False); @@ -177,18 +181,18 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Any(), Is.True); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); - var mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); + IContentType mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); Assert.That(mRBasePage.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(mRBasePage.PropertyGroups.Count(), Is.EqualTo(1)); Assert.That(mRBasePage.PropertyGroups["Metadaten"].PropertyTypes.Count(), Is.EqualTo(2)); - var mRStartPage = contentTypes.First(x => x.Alias == "MRStartPage"); + IContentType mRStartPage = contentTypes.First(x => x.Alias == "MRStartPage"); Assert.That(mRStartPage.ContentTypeCompositionExists("MRBasePage"), Is.True); Assert.That(mRStartPage.PropertyTypes.Count(), Is.EqualTo(28)); Assert.That(mRStartPage.PropertyGroups.Count(), Is.EqualTo(7)); - var propertyGroups = mRStartPage.CompositionPropertyGroups.Where(x => x.Name == "Metadaten"); - var propertyTypes = propertyGroups.SelectMany(x => x.PropertyTypes); + IEnumerable propertyGroups = mRStartPage.CompositionPropertyGroups.Where(x => x.Name == "Metadaten"); + IEnumerable propertyTypes = propertyGroups.SelectMany(x => x.PropertyTypes); Assert.That(propertyGroups.Count(), Is.EqualTo(2)); Assert.That(propertyTypes.Count(), Is.EqualTo(6)); } @@ -199,14 +203,14 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var element = xml.Descendants("Templates").First(); + XElement element = xml.Descendants("Templates").First(); - var init = FileService.GetTemplates().Count(); + int init = FileService.GetTemplates().Count(); // Act - var templates = PackageDataInstallation.ImportTemplates(element.Elements("Template").ToList(), 0); - var numberOfTemplates = (from doc in element.Elements("Template") select doc).Count(); - var allTemplates = FileService.GetTemplates(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(element.Elements("Template").ToList(), 0); + int numberOfTemplates = (from doc in element.Elements("Template") select doc).Count(); + IEnumerable allTemplates = FileService.GetTemplates(); // Assert Assert.That(templates, Is.Not.Null); @@ -223,11 +227,10 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var element = xml.Descendants("Templates").First(); - + XElement element = xml.Descendants("Templates").First(); // Act - var templates = PackageDataInstallation.ImportTemplate(element.Elements("Template").First(), 0); + IEnumerable templates = PackageDataInstallation.ImportTemplate(element.Elements("Template").First(), 0); // Assert Assert.That(templates, Is.Not.Null); @@ -241,16 +244,15 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); - + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -261,13 +263,13 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(contentTypes.Count(x => x.ParentId == -1), Is.EqualTo(1)); - var contentMaster = contentTypes.First(x => x.Alias == "ContentMaster"); + IContentType contentMaster = contentTypes.First(x => x.Alias == "ContentMaster"); Assert.That(contentMaster.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentMaster.PropertyGroups.Count(), Is.EqualTo(1)); Assert.That(contentMaster.PropertyGroups["SEO"].PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentMaster.ContentTypeCompositionExists("Base"), Is.True); - var propertyGroupId = contentMaster.PropertyGroups["SEO"].Id; + int propertyGroupId = contentMaster.PropertyGroups["SEO"].Id; Assert.That(contentMaster.PropertyGroups["SEO"].PropertyTypes.Any(x => x.PropertyGroupId.Value != propertyGroupId), Is.False); } @@ -277,17 +279,17 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); - //Assert - Re-Import contenttypes doesn't throw + // Assert - Re-Import contenttypes doesn't throw Assert.DoesNotThrow(() => PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0)); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -301,17 +303,17 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.Fanoe_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); - //Assert - Re-Import contenttypes doesn't throw + // Assert - Re-Import contenttypes doesn't throw Assert.DoesNotThrow(() => PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0)); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -325,18 +327,18 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var docTypesElement = xml.Descendants("DocumentTypes").First(); - var element = xml.Descendants("DocumentSet").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement docTypesElement = xml.Descendants("DocumentTypes").First(); + XElement element = xml.Descendants("DocumentSet").First(); var packageDocument = CompiledPackageContentBase.Create(element); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); var importedContentTypes = contentTypes.ToDictionary(x => x.Alias, x => x); - var contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); - var numberOfDocs = (from doc in element.Descendants() - where (string) doc.Attribute("isDoc") == "" + IReadOnlyList contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); + int numberOfDocs = (from doc in element.Descendants() + where (string)doc.Attribute("isDoc") == string.Empty select doc).Count(); // Assert @@ -354,16 +356,16 @@ namespace Umbraco.Tests.Packaging Core.Services.Implement.MediaTypeService.ClearScopeEvents(); string strXml = ImportResources.MediaTypesAndMedia_Package_xml; var xml = XElement.Parse(strXml); - var mediaTypesElement = xml.Descendants("MediaTypes").First(); - var element = xml.Descendants("MediaSet").First(); + XElement mediaTypesElement = xml.Descendants("MediaTypes").First(); + XElement element = xml.Descendants("MediaSet").First(); var packageMedia = CompiledPackageContentBase.Create(element); // Act - var mediaTypes = PackageDataInstallation.ImportMediaTypes(mediaTypesElement.Elements("MediaType"), 0); + IReadOnlyList mediaTypes = PackageDataInstallation.ImportMediaTypes(mediaTypesElement.Elements("MediaType"), 0); var importedMediaTypes = mediaTypes.ToDictionary(x => x.Alias, x => x); - var medias = PackageDataInstallation.ImportContentBase(packageMedia.Yield(), importedMediaTypes, 0, MediaTypeService, MediaService); - var numberOfDocs = (from doc in element.Descendants() - where (string) doc.Attribute("isDoc") == "" + IReadOnlyList medias = PackageDataInstallation.ImportContentBase(packageMedia.Yield(), importedMediaTypes, 0, MediaTypeService, MediaService); + int numberOfDocs = (from doc in element.Descendants() + where (string)doc.Attribute("isDoc") == string.Empty select doc).Count(); // Assert @@ -374,35 +376,31 @@ namespace Umbraco.Tests.Packaging } [Test] - public void Can_Import_CheckboxList_Content_Package_Xml_With_Property_Editor_Aliases() - { + public void Can_Import_CheckboxList_Content_Package_Xml_With_Property_Editor_Aliases() => AssertCheckBoxListTests(ImportResources.CheckboxList_Content_Package); - } - - private void AssertCheckBoxListTests(string strXml) { // Arrange var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var docTypesElement = xml.Descendants("DocumentTypes").First(); - var element = xml.Descendants("DocumentSet").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement docTypesElement = xml.Descendants("DocumentTypes").First(); + XElement element = xml.Descendants("DocumentSet").First(); var packageDocument = CompiledPackageContentBase.Create(element); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); var importedContentTypes = contentTypes.ToDictionary(x => x.Alias, x => x); - var contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); - var numberOfDocs = (from doc in element.Descendants() - where (string)doc.Attribute("isDoc") == "" + IReadOnlyList contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); + int numberOfDocs = (from doc in element.Descendants() + where (string)doc.Attribute("isDoc") == string.Empty select doc).Count(); string configuration; - using (var scope = ScopeProvider.CreateScope()) + using (Core.Scoping.IScope scope = ScopeProvider.CreateScope()) { - var dtos = scope.Database.Fetch("WHERE nodeId = @Id", new { dataTypeDefinitions.First().Id }); + List dtos = scope.Database.Fetch("WHERE nodeId = @Id", new { dataTypeDefinitions.First().Id }); configuration = dtos.Single().Configuration; } @@ -423,12 +421,11 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.XsltSearch_Package; var xml = XElement.Parse(strXml); - var templateElement = xml.Descendants("Templates").First(); - + XElement templateElement = xml.Descendants("Templates").First(); // Act - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + int numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); // Assert Assert.That(templates.Any(), Is.True); @@ -442,9 +439,8 @@ namespace Umbraco.Tests.Packaging string strXml = ImportResources.SingleDocType; var docTypeElement = XElement.Parse(strXml); - // Act - var contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); // Assert Assert.That(contentTypes.Any(), Is.True); @@ -459,12 +455,12 @@ namespace Umbraco.Tests.Packaging string strXml = ImportResources.SingleDocType; var docTypeElement = XElement.Parse(strXml); - var serializer = GetRequiredService(); + IEntityXmlSerializer serializer = GetRequiredService(); // Act - var contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); - var contentType = contentTypes.FirstOrDefault(); - var element = serializer.Serialize(contentType); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IContentType contentType = contentTypes.FirstOrDefault(); + XElement element = serializer.Serialize(contentType); // Assert Assert.That(element, Is.Not.Null); @@ -472,8 +468,9 @@ namespace Umbraco.Tests.Packaging Assert.That(element.Element("Structure"), Is.Not.Null); Assert.That(element.Element("GenericProperties"), Is.Not.Null); Assert.That(element.Element("Tabs"), Is.Not.Null); - //Can't compare this XElement because the templates are not imported (they don't exist) - //Assert.That(XNode.DeepEquals(docTypeElement, element), Is.True); + + // Can't compare this XElement because the templates are not imported (they don't exist) + //// Assert.That(XNode.DeepEquals(docTypeElement, element), Is.True); } [Test] @@ -484,8 +481,8 @@ namespace Umbraco.Tests.Packaging var docTypeElement = XElement.Parse(strXml); // Act - var contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); - var contentTypesUpdated = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IReadOnlyList contentTypesUpdated = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); // Assert Assert.That(contentTypes.Any(), Is.True); @@ -505,19 +502,19 @@ namespace Umbraco.Tests.Packaging var newPackageXml = XElement.Parse(ImportResources.TemplateOnly_Package); var updatedPackageXml = XElement.Parse(ImportResources.TemplateOnly_Updated_Package); - var templateElement = newPackageXml.Descendants("Templates").First(); - var templateElementUpdated = updatedPackageXml.Descendants("Templates").First(); + XElement templateElement = newPackageXml.Descendants("Templates").First(); + XElement templateElementUpdated = updatedPackageXml.Descendants("Templates").First(); - var fileService = FileService; + IFileService fileService = FileService; // kill default test data fileService.DeleteTemplate("Textpage"); // Act - var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var templatesAfterUpdate = PackageDataInstallation.ImportTemplates(templateElementUpdated.Elements("Template").ToList(), 0); - var allTemplates = fileService.GetTemplates(); + int numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList templatesAfterUpdate = PackageDataInstallation.ImportTemplates(templateElementUpdated.Elements("Template").ToList(), 0); + IEnumerable allTemplates = fileService.GetTemplates(); // Assert Assert.That(templates.Any(), Is.True); @@ -537,7 +534,7 @@ namespace Umbraco.Tests.Packaging const string expectedNorwegianChildValue = "BarnVerdi"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); @@ -559,19 +556,19 @@ namespace Umbraco.Tests.Packaging const string childKey = "Child"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); // Act - var dictionaryItems = PackageDataInstallation.ImportDictionaryItems(dictionaryItemsElement.Elements("DictionaryItem"), 0); + IReadOnlyList dictionaryItems = PackageDataInstallation.ImportDictionaryItems(dictionaryItemsElement.Elements("DictionaryItem"), 0); // Assert Assert.That(LocalizationService.DictionaryItemExists(parentKey), "DictionaryItem parentKey does not exist"); Assert.That(LocalizationService.DictionaryItemExists(childKey), "DictionaryItem childKey does not exist"); - var parentDictionaryItem = LocalizationService.GetDictionaryItemByKey(parentKey); - var childDictionaryItem = LocalizationService.GetDictionaryItemByKey(childKey); + IDictionaryItem parentDictionaryItem = LocalizationService.GetDictionaryItemByKey(parentKey); + IDictionaryItem childDictionaryItem = LocalizationService.GetDictionaryItemByKey(childKey); Assert.That(parentDictionaryItem.ParentId, Is.Not.EqualTo(childDictionaryItem.ParentId)); Assert.That(childDictionaryItem.ParentId, Is.EqualTo(parentDictionaryItem.Key)); @@ -587,7 +584,7 @@ namespace Umbraco.Tests.Packaging const string expectedNorwegianChildValue = "BarnVerdi"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); AddExistingEnglishAndNorwegianParentDictionaryItem(expectedEnglishParentValue, expectedNorwegianParentValue); @@ -612,7 +609,7 @@ namespace Umbraco.Tests.Packaging const string expectedNorwegianChildValue = "BarnVerdi"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); AddExistingEnglishParentDictionaryItem(expectedEnglishParentValue); @@ -632,15 +629,15 @@ namespace Umbraco.Tests.Packaging { // Arrange var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var LanguageItemsElement = newPackageXml.Elements("Languages").First(); + XElement languageItemsElement = newPackageXml.Elements("Languages").First(); // Act - var languages = PackageDataInstallation.ImportLanguages(LanguageItemsElement.Elements("Language"), 0); - var allLanguages = LocalizationService.GetAllLanguages(); + IReadOnlyList languages = PackageDataInstallation.ImportLanguages(languageItemsElement.Elements("Language"), 0); + IEnumerable allLanguages = LocalizationService.GetAllLanguages(); // Assert Assert.That(languages.Any(x => x.HasIdentity == false), Is.False); - foreach (var language in languages) + foreach (ILanguage language in languages) { Assert.That(allLanguages.Any(x => x.IsoCode == language.IsoCode), Is.True); } @@ -652,8 +649,7 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.uBlogsy_Package; var xml = XElement.Parse(strXml); - var macrosElement = xml.Descendants("Macros").First(); - + XElement macrosElement = xml.Descendants("Macros").First(); // Act var macros = PackageDataInstallation.ImportMacros(macrosElement.Elements("macro"), 0).ToList(); @@ -662,7 +658,7 @@ namespace Umbraco.Tests.Packaging Assert.That(macros.Any(), Is.True); var allMacros = MacroService.GetAll().ToList(); - foreach (var macro in macros) + foreach (IMacro macro in macros) { Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True); } @@ -674,8 +670,7 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.XsltSearch_Package; var xml = XElement.Parse(strXml); - var macrosElement = xml.Descendants("Macros").First(); - + XElement macrosElement = xml.Descendants("Macros").First(); // Act var macros = PackageDataInstallation.ImportMacros(macrosElement.Elements("macro"), 0).ToList(); @@ -685,7 +680,7 @@ namespace Umbraco.Tests.Packaging Assert.That(macros.First().Properties.Values.Any(), Is.True); var allMacros = MacroService.GetAll().ToList(); - foreach (var macro in macros) + foreach (IMacro macro in macros) { Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True); } @@ -697,14 +692,13 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.CompositionsTestPackage; var xml = XElement.Parse(strXml); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); - + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(contentTypes, Is.Not.Null); @@ -712,7 +706,7 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(contentTypes.Count(x => x.ParentId == -1), Is.EqualTo(3)); - var textpage = contentTypes.First(x => x.Alias.Equals("umbTextyPage")); + IContentType textpage = contentTypes.First(x => x.Alias.Equals("umbTextyPage")); Assert.That(textpage.ParentId, Is.Not.EqualTo(-1)); Assert.That(textpage.ContentTypeComposition.Count(), Is.EqualTo(3)); Assert.That(textpage.ContentTypeCompositionExists("umbMaster"), Is.True); @@ -726,19 +720,18 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.CompositionsTestPackage_Random; var xml = XElement.Parse(strXml); - var docTypeElement = xml.Descendants("DocumentTypes").First(); - + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(contentTypes, Is.Not.Null); Assert.That(contentTypes.Any(), Is.True); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); - var testContentType = contentTypes.First(x => x.Alias.Equals("CompositeTest")); + IContentType testContentType = contentTypes.First(x => x.Alias.Equals("CompositeTest")); Assert.That(testContentType.ContentTypeComposition.Count(), Is.EqualTo(3)); Assert.That(testContentType.ContentTypeCompositionExists("Content"), Is.True); Assert.That(testContentType.ContentTypeCompositionExists("Meta"), Is.True); @@ -757,17 +750,17 @@ namespace Umbraco.Tests.Packaging private void AssertDictionaryItem(string key, string expectedValue, string cultureCode) { Assert.That(LocalizationService.DictionaryItemExists(key), "DictionaryItem key does not exist"); - var dictionaryItem = LocalizationService.GetDictionaryItemByKey(key); - var translation = dictionaryItem.Translations.SingleOrDefault(i => i.Language.IsoCode == cultureCode); + IDictionaryItem dictionaryItem = LocalizationService.GetDictionaryItemByKey(key); + IDictionaryTranslation translation = dictionaryItem.Translations.SingleOrDefault(i => i.Language.IsoCode == cultureCode); Assert.IsNotNull(translation, "Translation to {0} was not added", cultureCode); - var value = translation.Value; + string value = translation.Value; Assert.That(value, Is.EqualTo(expectedValue), "Translation value was not set"); } private void AddExistingEnglishParentDictionaryItem(string expectedEnglishParentValue) { var languages = LocalizationService.GetAllLanguages().ToList(); - var englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); + ILanguage englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); LocalizationService.Save( new DictionaryItem("Parent") { @@ -775,15 +768,14 @@ namespace Umbraco.Tests.Packaging { new DictionaryTranslation(englishLanguage, expectedEnglishParentValue), } - } - ); + }); } private void AddExistingEnglishAndNorwegianParentDictionaryItem(string expectedEnglishParentValue, string expectedNorwegianParentValue) { var languages = LocalizationService.GetAllLanguages().ToList(); - var englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); - var norwegianLanguage = languages.Single(l => l.IsoCode == "nb-NO"); + ILanguage englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); + ILanguage norwegianLanguage = languages.Single(l => l.IsoCode == "nb-NO"); LocalizationService.Save( new DictionaryItem("Parent") { @@ -792,8 +784,7 @@ namespace Umbraco.Tests.Packaging new DictionaryTranslation(englishLanguage, expectedEnglishParentValue), new DictionaryTranslation(norwegianLanguage, expectedNorwegianParentValue), } - } - ); + }); } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs index 93a6ef010b..867a770097 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -16,6 +19,7 @@ namespace Umbraco.Tests.Packaging public class PackageInstallationTest : UmbracoIntegrationTest { private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IPackageInstallation PackageInstallation => GetRequiredService(); private const string DocumentTypePickerPackage = "Document_Type_Picker_1.1.umb"; @@ -24,9 +28,8 @@ namespace Umbraco.Tests.Packaging [Test] public void Can_Read_Compiled_Package_1() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); Assert.IsNotNull(package); Assert.AreEqual(1, package.Files.Count); Assert.AreEqual("095e064b-ba4d-442d-9006-3050983c13d8.dll", package.Files[0].UniqueFileName); @@ -47,9 +50,8 @@ namespace Umbraco.Tests.Packaging [Test] public void Can_Read_Compiled_Package_2() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), HelloPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), HelloPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); Assert.IsNotNull(package); Assert.AreEqual(0, package.Files.Count); Assert.AreEqual("Hello", package.Name); @@ -73,18 +75,17 @@ namespace Umbraco.Tests.Packaging [Test] public void Can_Read_Compiled_Package_Warnings() { - //copy a file to the same path that the package will install so we can detect file conflicts - - var filePath = Path.Combine(HostingEnvironment.MapPathContentRoot("~/"), "bin", "Auros.DocumentTypePicker.dll"); + // Copy a file to the same path that the package will install so we can detect file conflicts. + string filePath = Path.Combine(HostingEnvironment.MapPathContentRoot("~/"), "bin", "Auros.DocumentTypePicker.dll"); Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, "test"); - //this is where our test zip file is - var packageFile = Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage); + // this is where our test zip file is + string packageFile = Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage); Console.WriteLine(packageFile); - var package = PackageInstallation.ReadPackage(new FileInfo(packageFile)); - var preInstallWarnings = package.Warnings; + CompiledPackage package = PackageInstallation.ReadPackage(new FileInfo(packageFile)); + PreInstallWarnings preInstallWarnings = package.Warnings; Assert.IsNotNull(preInstallWarnings); Assert.AreEqual(1, preInstallWarnings.FilesReplaced.Count()); @@ -96,14 +97,13 @@ namespace Umbraco.Tests.Packaging [Test] public void Install_Files() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); var def = PackageDefinition.FromCompiledPackage(package); def.Id = 1; def.PackageId = Guid.NewGuid(); - def.Files = new List(); //clear out the files of the def for testing, this should be populated by the install + def.Files = new List(); // clear out the files of the def for testing, this should be populated by the install var result = PackageInstallation.InstallPackageFiles(def, package, -1).ToList(); @@ -111,26 +111,24 @@ namespace Umbraco.Tests.Packaging Assert.AreEqual(Path.Combine("bin", "Auros.DocumentTypePicker.dll"), result[0]); Assert.IsTrue(File.Exists(Path.Combine(HostingEnvironment.MapPathContentRoot("~/"), result[0]))); - //make sure the def is updated too + // make sure the def is updated too Assert.AreEqual(result.Count, def.Files.Count); } [Test] public void Install_Data() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); var def = PackageDefinition.FromCompiledPackage(package); def.Id = 1; def.PackageId = Guid.NewGuid(); - var summary = PackageInstallation.InstallPackageData(def, package, -1); + InstallationSummary summary = PackageInstallation.InstallPackageData(def, package, -1); Assert.AreEqual(1, summary.DataTypesInstalled.Count()); - - //make sure the def is updated too + // make sure the def is updated too Assert.AreEqual(summary.DataTypesInstalled.Count(), def.DataTypes.Count); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs index 24a4e8d772..dd91f3ad55 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using System.Threading; using NUnit.Framework; using Umbraco.Core.Configuration.Models; @@ -19,13 +22,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Services public class SectionServiceTests : UmbracoIntegrationTest { private ISectionService SectionService => GetRequiredService(); + private IUserService UserService => GetRequiredService(); [Test] public void SectionService_Can_Get_Allowed_Sections_For_User() { // Arrange - var user = CreateTestUser(); + IUser user = CreateTestUser(); // Act var result = SectionService.GetAllowedSections(user.Id).ToList(); @@ -52,6 +56,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Services }; userGroupA.AddAllowedSection("media"); userGroupA.AddAllowedSection("settings"); + // TODO: This is failing the test UserService.Save(userGroupA, new[] { user.Id }, false); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs index ac502ddf80..92280fde43 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs @@ -1,20 +1,21 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using NUnit.Framework; -using Microsoft.Extensions.Logging; using Umbraco.Core.Configuration; using Umbraco.Core.Migrations; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Migrations.Upgrade; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; -using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; namespace Umbraco.Tests.Migrations @@ -23,24 +24,27 @@ namespace Umbraco.Tests.Migrations [UmbracoTest(Database = UmbracoTestOptions.Database.NewEmptyPerTest)] public class AdvancedMigrationTests : UmbracoIntegrationTest { - private ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; + private readonly ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; private IUmbracoVersion UmbracoVersion => GetRequiredService(); [Test] public void CreateTableOfTDto() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => { if (t != typeof(CreateTableOfTDtoMigration)) + { throw new NotSupportedException(); + } + return new CreateTableOfTDtoMigration(c); }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -50,7 +54,7 @@ namespace Umbraco.Tests.Migrations upgrader.Execute(ScopeProvider, builder, Mock.Of(), _loggerFactory.CreateLogger(), _loggerFactory); var helper = new DatabaseSchemaCreator(scope.Database, LoggerFactory.CreateLogger(), LoggerFactory, UmbracoVersion); - var exists = helper.TableExists("umbracoUser"); + bool exists = helper.TableExists("umbracoUser"); Assert.IsTrue(exists); scope.Complete(); @@ -60,7 +64,7 @@ namespace Umbraco.Tests.Migrations [Test] public void DeleteKeysAndIndexesOfTDto() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -76,7 +80,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -92,7 +96,7 @@ namespace Umbraco.Tests.Migrations [Test] public void CreateKeysAndIndexesOfTDto() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -110,7 +114,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -127,7 +131,7 @@ namespace Umbraco.Tests.Migrations [Test] public void CreateKeysAndIndexes() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -145,7 +149,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -162,7 +166,7 @@ namespace Umbraco.Tests.Migrations [Test] public void CreateColumn() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -178,7 +182,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -195,32 +199,38 @@ namespace Umbraco.Tests.Migrations { public CreateTableOfTDtoMigration(IMigrationContext context) : base(context) - { } - - public override void Migrate() { - // creates User table with keys, indexes, etc - Create.Table().Do(); } + + public override void Migrate() => + + // Create User table with keys, indexes, etc. + Create.Table().Do(); } public class DeleteKeysAndIndexesMigration : MigrationBase { public DeleteKeysAndIndexesMigration(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { // drops User table keys and indexes - //Execute.DropKeysAndIndexes("umbracoUser"); + // Execute.DropKeysAndIndexes("umbracoUser"); // drops *all* tables keys and indexes var tables = SqlSyntax.GetTablesInSchema(Context.Database).ToList(); - foreach (var table in tables) + foreach (string table in tables) + { Delete.KeysAndIndexes(table, false, true).Do(); - foreach (var table in tables) + } + + foreach (string table in tables) + { Delete.KeysAndIndexes(table, true, false).Do(); + } } } @@ -228,28 +238,32 @@ namespace Umbraco.Tests.Migrations { public CreateKeysAndIndexesOfTDtoMigration(IMigrationContext context) : base(context) - { } - - public override void Migrate() { - // creates Node table keys and indexes - Create.KeysAndIndexes().Do(); } + + public override void Migrate() => + + // Create User table keys and indexes. + Create.KeysAndIndexes().Do(); } public class CreateKeysAndIndexesMigration : MigrationBase { public CreateKeysAndIndexesMigration(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { - // creates *all* tables keys and indexes - foreach (var x in DatabaseSchemaCreator.OrderedTables) + // Creates *all* tables keys and indexes + foreach (Type x in DatabaseSchemaCreator.OrderedTables) { // ok - for tests, restrict to Node - if (x != typeof(UserDto)) continue; + if (x != typeof(UserDto)) + { + continue; + } Create.KeysAndIndexes(x).Do(); } @@ -260,7 +274,8 @@ namespace Umbraco.Tests.Migrations { public CreateColumnMigration(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { @@ -269,9 +284,9 @@ namespace Umbraco.Tests.Migrations Delete.Column("id").FromTable("umbracoUser").Do(); - var table = DefinitionFactory.GetTableDefinition(typeof(UserDto), SqlSyntax); - var column = table.Columns.First(x => x.Name == "id"); - var create = SqlSyntax.Format(column); // returns [id] INTEGER NOT NULL IDENTITY(1060,1) + TableDefinition table = DefinitionFactory.GetTableDefinition(typeof(UserDto), SqlSyntax); + ColumnDefinition column = table.Columns.First(x => x.Name == "id"); + string create = SqlSyntax.Format(column); // returns [id] INTEGER NOT NULL IDENTITY(1060,1) Database.Execute($"ALTER TABLE {SqlSyntax.GetQuotedTableName("umbracoUser")} ADD " + create); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs index dd66efb47a..cf60557ba5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs @@ -1,28 +1,30 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text.RegularExpressions; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; +using NPoco; using NUnit.Framework; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Implementations; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTests { // FIXME: npoco - is this still appropriate? - // [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class NPocoBulkInsertTests : UmbracoIntegrationTest { - private TestHelper _testHelper = new TestHelper(); + private readonly TestHelper _testHelper = new TestHelper(); + private IProfilingLogger ProfilingLogger => _testHelper.ProfilingLogger; [NUnit.Framework.Ignore("Ignored because you need to configure your own SQL Server to test this with")] @@ -33,15 +35,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // prob not what we want, this is not a real database, but hey, the test is ignored anyways // we'll fix this when we have proper testing infrastructure // var dbSqlServer = TestObjects.GetUmbracoSqlServerDatabase(new NullLogger()); - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { // Still no what we want, but look above. - var dbSqlServer = scope.Database; - //drop the table + IUmbracoDatabase dbSqlServer = scope.Database; + + // drop the table dbSqlServer.Execute("DROP TABLE [umbracoServer]"); - //re-create it + // re-create it dbSqlServer.Execute(@"CREATE TABLE [umbracoServer]( [id] [int] IDENTITY(1,1) NOT NULL, [address] [nvarchar](500) NOT NULL, @@ -56,7 +58,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] )"); var data = new List(); - for (var i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { data.Add(new ServerRegistrationDto { @@ -68,7 +70,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest }); } - using (var tr = dbSqlServer.GetTransaction()) + using (ITransaction tr = dbSqlServer.GetTransaction()) { dbSqlServer.BulkInsertRecords(data); tr.Complete(); @@ -83,7 +85,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest public void Can_Bulk_Insert_Native_Sql_Bulk_Inserts() { var servers = new List(); - for (var i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { servers.Add(new ServerRegistrationDto { @@ -98,7 +100,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // Act using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.BulkInsertRecords(servers); scope.Complete(); @@ -106,7 +108,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest } // Assert - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { Assert.That(scope.Database.ExecuteScalar("SELECT COUNT(*) FROM umbracoServer"), Is.EqualTo(1000)); } @@ -116,7 +118,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest public void Can_Bulk_Insert_Native_Sql_Bulk_Inserts_Transaction_Rollback() { var servers = new List(); - for (var i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { servers.Add(new ServerRegistrationDto { @@ -131,15 +133,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // Act using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.BulkInsertRecords(servers); - //don't call complete here - the trans will be rolled back + + // Don't call complete here - the transaction will be rolled back. } } // Assert - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { Assert.That(scope.Database.ExecuteScalar("SELECT COUNT(*) FROM umbracoServer"), Is.EqualTo(0)); } @@ -149,7 +152,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest public void Generate_Bulk_Import_Sql() { var servers = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { servers.Add(new ServerRegistrationDto { @@ -162,23 +165,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest } IDbCommand[] commands; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { commands = scope.Database.GenerateBulkInsertCommands(servers.ToArray()); scope.Complete(); } // Assert - Assert.That(commands[0].CommandText, - Is.EqualTo("INSERT INTO [umbracoServer] ([umbracoServer].[address], [umbracoServer].[computerName], [umbracoServer].[registeredDate], [umbracoServer].[lastNotifiedDate], [umbracoServer].[isActive], [umbracoServer].[isMaster]) VALUES (@0,@1,@2,@3,@4,@5), (@6,@7,@8,@9,@10,@11)")); + Assert.That( + commands[0].CommandText, + Is.EqualTo("INSERT INTO [umbracoServer] ([umbracoServer].[address], [umbracoServer].[computerName], [umbracoServer].[registeredDate], [umbracoServer].[lastNotifiedDate], [umbracoServer].[isActive], [umbracoServer].[isMaster]) VALUES (@0,@1,@2,@3,@4,@5), (@6,@7,@8,@9,@10,@11)")); } - [Test] public void Generate_Bulk_Import_Sql_Exceeding_Max_Params() { var servers = new List(); - for (var i = 0; i < 1500; i++) + for (int i = 0; i < 1500; i++) { servers.Add(new ServerRegistrationDto { @@ -192,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest } IDbCommand[] commands; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { commands = scope.Database.GenerateBulkInsertCommands(servers.ToArray()); scope.Complete(); @@ -200,7 +203,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // Assert Assert.That(commands.Length, Is.EqualTo(5)); - foreach (var s in commands.Select(x => x.CommandText)) + foreach (string s in commands.Select(x => x.CommandText)) { Assert.LessOrEqual(Regex.Matches(s, "@\\d+").Count, 2000); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs index 58429ed80e..ca248a1c80 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs @@ -1,9 +1,13 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using NPoco; using NUnit.Framework; using Umbraco.Core.Persistence; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -16,7 +20,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [SetUp] protected void SeedDatabase() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { InsertData(scope.Database); scope.Complete(); @@ -154,20 +158,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestSimple() { - // fetching a simple POCO - - using (var scope = ScopeProvider.CreateScope()) + // Fetching a simple POCO + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id, zbThing1.name // FROM zbThing1"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select() .From(); - var dtos = scope.Database.Fetch(sql); + List dtos = scope.Database.Fetch(sql); Assert.AreEqual(2, dtos.Count); Assert.AreEqual("one", dtos.First(x => x.Id == 1).Name); } @@ -176,24 +178,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToOne() { - // fetching a POCO that contains the ID of another POCO, - // and fetching that other POCO at the same time - - using (var scope = ScopeProvider.CreateScope()) + // Fetching a POCO that contains the ID of another POCO, + // and fetching that other POCO at the same time. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing2.id, zbThing2.name, zbThing2.thingId, // zbThing1.id Thing__id, zbThing1.name Thing__name // FROM zbThing2 // JOIN zbThing1 ON zbThing2.thingId=zbThing1.id"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Thing)) .From() .InnerJoin().On((t2, t1) => t2.ThingId == t1.Id); - var dtos = scope.Database.Fetch(sql); + List dtos = scope.Database.Fetch(sql); Assert.AreEqual(3, dtos.Count); Assert.AreEqual("uno", dtos.First(x => x.Id == 1).Name); Assert.IsNotNull(dtos.First(x => x.Id == 1).Thing); @@ -204,37 +204,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToManyOnOne() { - // fetching a POCO that has a list of other POCOs, + // Fetching a POCO that has a list of other POCOs, // and fetching these POCOs at the same time, // with a pk/fk relationship - // for one single POCO - - using (var scope = ScopeProvider.CreateScope()) + // for one single POCO. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, @" // SELECT zbThing1.id AS Id, zbThing1.name AS Name, // zbThing2.id AS Things__Id, zbThing2.name AS Things__Name, zbThing2.thingId AS Things__ThingId // FROM zbThing1 // JOIN zbThing2 ON zbThing1.id=zbThing2.thingId // WHERE zbThing1.id=1"); - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Things)) .From() .InnerJoin().On(left => left.Id, right => right.ThingId) .Where(x => x.Id == 1); - //var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, sql); - var dtos = scope.Database.FetchOneToMany(x => x.Things, sql); + // var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, sql); + List dtos = scope.Database.FetchOneToMany(x => x.Things, sql); Assert.AreEqual(1, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing3Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Things); Assert.AreEqual(2, dto1.Things.Count); - var dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); + Thing2Dto dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("uno", dto2.Name); } @@ -243,39 +241,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToManyOnMany() { - // fetching a POCO that has a list of other POCOs, + // Fetching a POCO that has a list of other POCOs, // and fetching these POCOs at the same time, // with a pk/fk relationship - // for several POCOs + // for several POCOs. // - // the ORDER BY clause (matching x => x.Id) is required - // for proper aggregation to take place - - using (var scope = ScopeProvider.CreateScope()) + // The ORDER BY clause (matching x => x.Id) is required + // for proper aggregation to take place. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id AS Id, zbThing1.name AS Name, // zbThing2.id AS Things__Id, zbThing2.name AS Things__Name, zbThing2.thingId AS Things__ThingId // FROM zbThing1 // JOIN zbThing2 ON zbThing1.id=zbThing2.thingId // ORDER BY zbThing1.id"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Things)) // select Thing3Dto, and Thing2Dto for Things .From() .InnerJoin().On(left => left.Id, right => right.ThingId) .OrderBy(x => x.Id); - var dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); + List dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing3Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Things); Assert.AreEqual(2, dto1.Things.Count); - var dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); + Thing2Dto dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("uno", dto2.Name); } @@ -284,11 +280,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToManyOnManyTemplate() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.SqlContext.Templates.Clear(); - var sql = scope.SqlContext.Templates.Get("xxx", s => s + Sql sql = scope.SqlContext.Templates.Get("xxx", s => s .Select(r => r.Select(x => x.Things)) // select Thing3Dto, and Thing2Dto for Things .From() .InnerJoin().On(left => left.Id, right => right.ThingId) @@ -297,15 +293,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // cached sql = scope.SqlContext.Templates.Get("xxx", s => throw new InvalidOperationException()).Sql(); - var dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); + List dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing3Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Things); Assert.AreEqual(2, dto1.Things.Count); - var dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); + Thing2Dto dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("uno", dto2.Name); } @@ -314,39 +310,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestManyToMany() { - // fetching a POCO that has a list of other POCOs, + // Fetching a POCO that has a list of other POCOs, // and fetching these POCOs at the same time, - // with an n-to-n intermediate table + // with an n-to-n intermediate table. // - // the ORDER BY clause (matching x => x.Id) is required - // for proper aggregation to take place - - using (var scope = ScopeProvider.CreateScope()) + // The ORDER BY clause (matching x => x.Id) is required + // for proper aggregation to take place. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id, zbThing1.name, zbThingGroup.id, zbThingGroup.name // FROM zbThing1 // JOIN zbThing2Group ON zbThing1.id=zbThing2Group.thingId // JOIN zbThingGroup ON zbThing2Group.groupId=zbThingGroup.id // ORDER BY zbThing1.id"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Groups)) .From() .InnerJoin().On((t, t2g) => t.Id == t2g.ThingId) .InnerJoin().On((t2g, tg) => t2g.GroupId == tg.Id) .OrderBy(x => x.Id); - var dtos = scope.Database.FetchOneToMany(x => x.Groups, /*x => x.Id,*/ sql); + List dtos = scope.Database.FetchOneToMany(x => x.Groups, /*x => x.Id,*/ sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing4Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Groups); Assert.AreEqual(2, dto1.Groups.Count); - var dto2 = dto1.Groups.FirstOrDefault(x => x.Id == 1); + ThingGroupDto dto2 = dto1.Groups.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("g-one", dto2.Name); } @@ -355,33 +349,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestCalculated() { - // fetching a POCO that has a countof other POCOs, - // with an n-to-n intermediate table - - using (var scope = ScopeProvider.CreateScope()) + // Fetching a POCO that has a countof other POCOs, + // with an n-to-n intermediate table. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id, zbThing1.name, COUNT(zbThing2Group.groupId) as groupCount // FROM zbThing1 // JOIN zbThing2Group ON zbThing1.id=zbThing2Group.thingId // GROUP BY zbThing1.id, zbThing1.name"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select() .Append(", COUNT(zbThing2Group.groupId) AS groupCount") // FIXME: .From() .InnerJoin().On((t, t2g) => t.Id == t2g.ThingId) .GroupBy(x => x.Id, x => x.Name); - var dtos = scope.Database.Fetch(sql); + List dtos = scope.Database.Fetch(sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing5Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.AreEqual(2, dto1.GroupCount); - var dto2 = dtos.FirstOrDefault(x => x.Id == 2); + Thing5Dto dto2 = dtos.FirstOrDefault(x => x.Id == 2); Assert.IsNotNull(dto2); Assert.AreEqual("two", dto2.Name); Assert.AreEqual(1, dto2.GroupCount); @@ -395,22 +387,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestSql() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .SelectAll() .From() .Where(x => x.Id == 1); - var dto = scope.Database.Fetch(sql).FirstOrDefault(); + Thing1Dto dto = scope.Database.Fetch(sql).FirstOrDefault(); Assert.IsNotNull(dto); Assert.AreEqual("one", dto.Name); - //var sql2 = new Sql(sql.SQL, new { id = 1 }); - //WriteSql(sql2); - //dto = Database.Fetch(sql2).FirstOrDefault(); - //Assert.IsNotNull(dto); - //Assert.AreEqual("one", dto.Name); + //// var sql2 = new Sql(sql.SQL, new { id = 1 }); + //// WriteSql(sql2); + //// dto = Database.Fetch(sql2).FirstOrDefault(); + //// Assert.IsNotNull(dto); + //// Assert.AreEqual("one", dto.Name); var sql3 = new Sql(sql.SQL, 1); dto = scope.Database.Fetch(sql3).FirstOrDefault(); @@ -422,7 +414,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestMultipleOneToOne() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var tA1A = new ThingA1Dto { Id = 1, Name = "a1_a" }; scope.Database.Insert(tA1A); @@ -448,7 +440,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest var k2 = new ThingA12Dto { Name = "B", Thing1Id = tA1A.Id, Thing2Id = tA2B.Id }; scope.Database.Insert(k2); - var sql = @"SELECT a1.id, a1.name, + string sql = @"SELECT a1.id, a1.name, a2.id AS T2A__Id, a2.name AS T2A__Name, a3.id AS T2A__T3__Id, a3.name AS T2A__T3__Name, a2x.id AS T2B__Id, a2x.name AS T2B__Name, a3x.id AS T2B__T3__Id, a3x.name AS T2B__T3__Name FROM zbThingA1 a1 @@ -460,10 +452,10 @@ JOIN zbThingA2 a2x ON a12x.thing2id=a2x.id JOIN zbThingA3 a3x ON a2x.id=a3x.id "; - var ts = scope.Database.Fetch(sql); + List ts = scope.Database.Fetch(sql); Assert.AreEqual(1, ts.Count); - var t = ts.First(); + ThingA1Dto t = ts.First(); Assert.AreEqual("a1_a", t.Name); Assert.AreEqual("a2_a", t.T2A.Name); Assert.AreEqual("a2_b", t.T2B.Name); @@ -578,7 +570,6 @@ JOIN zbThingA3 a3x ON a2x.id=a3x.id [Column("groupCount")] [ResultColumn] // not included in insert/update, not sql-generated - //[ComputedColumn] // not included in insert/update, sql-generated public int GroupCount { get; set; } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs index d62e0623b1..10e89bc83a 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs @@ -1,14 +1,19 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; -using Microsoft.Extensions.Logging; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories { @@ -19,21 +24,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private ILogger _logger; [SetUp] - public void Prepare() - { - _logger = LoggerFactory.CreateLogger(); - } + public void Prepare() => _logger = LoggerFactory.CreateLogger(); [Test] public void Can_Add_Audit_Entry() { - var sp = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); repo.Save(new AuditItem(-1, AuditType.System, -1, UmbracoObjectTypes.Document.GetName(), "This is a System audit trail")); - var dtos = scope.Database.Fetch("WHERE id > -1"); + List dtos = scope.Database.Fetch("WHERE id > -1"); Assert.That(dtos.Any(), Is.True); Assert.That(dtos.First().Comment, Is.EqualTo("This is a System audit trail")); @@ -43,12 +45,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} published")); @@ -57,11 +59,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 10, out var total, Direction.Descending, null, null); + IEnumerable page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 10, out long total, Direction.Descending, null, null); Assert.AreEqual(10, page.Count()); Assert.AreEqual(200, total); @@ -71,12 +73,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items_By_User_Id_With_Query_And_Filter() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} published")); @@ -85,20 +87,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var query = sp.SqlContext.Query().Where(x => x.UserId == -1); + IQuery query = sp.SqlContext.Query().Where(x => x.UserId == -1); try { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var page = repo.GetPagedResultsByQuery(query, 0, 10, out var total, Direction.Descending, + IEnumerable page = repo.GetPagedResultsByQuery( + query, + 0, + 10, + out long total, + Direction.Descending, new[] { AuditType.Publish }, - sp.SqlContext.Query().Where(x => x.UserId > -2)); + sp.SqlContext.Query() + .Where(x => x.UserId > -2)); Assert.AreEqual(10, page.Count()); Assert.AreEqual(100, total); @@ -114,12 +122,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items_With_AuditType_Filter() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} published")); @@ -128,12 +136,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 9, out var total, Direction.Descending, - new[] { AuditType.Publish }, null) + IAuditItem[] page = repo.GetPagedResultsByQuery( + sp.SqlContext.Query(), + 0, + 9, + out long total, + Direction.Descending, + new[] { AuditType.Publish }, + null) .ToArray(); Assert.AreEqual(9, page.Length); @@ -145,12 +159,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items_With_Custom_Filter() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), "Content created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), "Content published")); @@ -159,12 +173,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 8, out var total, Direction.Descending, - null, sp.SqlContext.Query().Where(item => item.Comment == "Content created")) + IAuditItem[] page = repo.GetPagedResultsByQuery( + sp.SqlContext.Query(), + 0, + 8, + out long total, + Direction.Descending, + null, + sp.SqlContext.Query() + .Where(item => item.Comment == "Content created")) .ToArray(); Assert.AreEqual(8, page.Length); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs index 5013823540..69441fd649 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs @@ -1,28 +1,26 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; -using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Umbraco.Web.Models.ContentEditing; +using Content = Umbraco.Core.Models.Content; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories { @@ -32,31 +30,36 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { private ContentType _simpleContentType; private ContentType _textpageContentType; - private IFileSystems FileSystems => GetRequiredService(); - private UmbracoMapper Mapper => GetRequiredService(); - private IContentTypeService ContentTypeService => GetRequiredService(); - private IDocumentTypeContainerRepository DocumentTypeContainerRepository => GetRequiredService(); - private IMediaTypeContainerRepository MediaTypeContainerRepository => GetRequiredService(); - private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); - private IDocumentRepository DocumentRepository => GetRequiredService(); - private ContentTypeRepository ContentTypeRepository => (ContentTypeRepository) GetRequiredService(); + private IFileSystems FileSystems => GetRequiredService(); + + private UmbracoMapper Mapper => GetRequiredService(); + + private IContentTypeService ContentTypeService => GetRequiredService(); + + private IDocumentTypeContainerRepository DocumentTypeContainerRepository => GetRequiredService(); + + private IMediaTypeContainerRepository MediaTypeContainerRepository => GetRequiredService(); + + private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); + + private IDocumentRepository DocumentRepository => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); + + private ContentTypeRepository ContentTypeRepository => (ContentTypeRepository)GetRequiredService(); [SetUp] - public void SetUpData() - { - CreateTestData(); - } + public void SetUpData() => CreateTestData(); public void CreateTestData() { - //Create and Save ContentType "umbTextpage" -> (_simpleContentType.Id) + // Create and Save ContentType "umbTextpage" -> (_simpleContentType.Id) _simpleContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: 0); ContentTypeService.Save(_simpleContentType); - //Create and Save ContentType "textPage" -> (_textpageContentType.Id) - _textpageContentType = ContentTypeBuilder.CreateTextPageContentType( defaultTemplateId: 0); + // Create and Save ContentType "textPage" -> (_textpageContentType.Id) + _textpageContentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: 0); ContentTypeService.Save(_textpageContentType); } @@ -66,60 +69,53 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Maps_Templates_Correctly() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var templateRepo = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); - var repository = ContentTypeRepository; - var templates = new[] + var templateRepo = new TemplateRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); + ContentTypeRepository repository = ContentTypeRepository; + Template[] templates = new[] { new Template(ShortStringHelper, "test1", "test1"), new Template(ShortStringHelper, "test2", "test2"), new Template(ShortStringHelper, "test3", "test3") }; - foreach (var template in templates) + foreach (Template template in templates) { templateRepo.Save(template); } - - var contentType = ContentTypeBuilder.CreateSimpleContentType(); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(); contentType.AllowedTemplates = new[] { templates[0], templates[1] }; contentType.SetDefaultTemplate(templates[0]); repository.Save(contentType); - - //re-get - var result = repository.Get(contentType.Id); + // re-get + IContentType result = repository.Get(contentType.Id); Assert.AreEqual(2, result.AllowedTemplates.Count()); Assert.AreEqual(templates[0].Id, result.DefaultTemplate.Id); } - } [Test] public void Can_Move() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; var container1 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah1" }; DocumentTypeContainerRepository.Save(container1); - var container2 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah2", ParentId = container1.Id }; DocumentTypeContainerRepository.Save(container2); - var contentType = (IContentType)ContentTypeBuilder.CreateBasicContentType("asdfasdf"); contentType.ParentId = container2.Id; repository.Save(contentType); - - //create a + // create a var contentType2 = (IContentType)new ContentType(ShortStringHelper, contentType, "hello") { Name = "Blahasdfsadf" @@ -127,13 +123,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor contentType.ParentId = contentType.Id; repository.Save(contentType2); - - var result = repository.Move(contentType, container1).ToArray(); - + global::Umbraco.Core.Events.MoveEventInfo[] result = repository.Move(contentType, container1).ToArray(); Assert.AreEqual(2, result.Count()); - //re-get + // re-get contentType = repository.Get(contentType.Id); contentType2 = repository.Get(contentType2.Id); @@ -141,22 +135,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType.Id).OriginalPath, contentType.Path); Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType2.Id).OriginalPath, contentType2.Path); } - } [Test] public void Can_Create_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var container = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah" }; DocumentTypeContainerRepository.Save(container); Assert.That(container.Id, Is.GreaterThan(0)); - var found = DocumentTypeContainerRepository.Get(container.Id); + EntityContainer found = DocumentTypeContainerRepository.Get(container.Id); Assert.IsNotNull(found); } } @@ -166,10 +158,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { EntityContainer container1, container2, container3; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - container1 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "container1" }; DocumentTypeContainerRepository.Save(container1); container2 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "container2" }; @@ -181,13 +172,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(container2.Id, Is.GreaterThan(0)); Assert.That(container3.Id, Is.GreaterThan(0)); - var found1 = DocumentTypeContainerRepository.Get(container1.Id); + EntityContainer found1 = DocumentTypeContainerRepository.Get(container1.Id); Assert.IsNotNull(found1); - var found2 = DocumentTypeContainerRepository.Get(container2.Id); + EntityContainer found2 = DocumentTypeContainerRepository.Get(container2.Id); Assert.IsNotNull(found2); - var found3 = DocumentTypeContainerRepository.Get(container3.Id); + EntityContainer found3 = DocumentTypeContainerRepository.Get(container3.Id); Assert.IsNotNull(found3); - var allContainers = DocumentTypeContainerRepository.GetMany(); + IEnumerable allContainers = DocumentTypeContainerRepository.GetMany(); Assert.AreEqual(3, allContainers.Count()); } } @@ -195,18 +186,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var container = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah" }; DocumentTypeContainerRepository.Save(container); - // Act DocumentTypeContainerRepository.Delete(container); - - var found = DocumentTypeContainerRepository.Get(container.Id); + EntityContainer found = DocumentTypeContainerRepository.Get(container.Id); Assert.IsNull(found); } } @@ -214,19 +203,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; MediaTypeContainerRepository.Save(container); - - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup", defaultTemplateId:0); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup", defaultTemplateId: 0); contentType.ParentId = container.Id; repository.Save(contentType); - Assert.AreEqual(container.Id, contentType.ParentId); } } @@ -234,24 +221,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; MediaTypeContainerRepository.Save(container); - IMediaType contentType = MediaTypeBuilder.CreateSimpleMediaType("test", "Test", propertyGroupName: "testGroup"); contentType.ParentId = container.Id; MediaTypeRepository.Save(contentType); - // Act MediaTypeContainerRepository.Delete(container); - - var found = MediaTypeContainerRepository.Get(container.Id); + EntityContainer found = MediaTypeContainerRepository.Get(container.Id); Assert.IsNull(found); contentType = MediaTypeRepository.Get(contentType.Id); @@ -264,16 +247,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - // Act - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup"); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup"); ContentTypeRepository.Save(contentType); - - var fetched = ContentTypeRepository.Get(contentType.Id); + IContentType fetched = ContentTypeRepository.Get(contentType.Id); // Assert Assert.That(contentType.HasIdentity, Is.True); @@ -283,15 +264,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.SortOrder, Is.GreaterThan(0)); Assert.That(contentType.PropertyGroups.ElementAt(0).Name == "testGroup", Is.True); - var groupId = contentType.PropertyGroups.ElementAt(0).Id; + int groupId = contentType.PropertyGroups.ElementAt(0).Id; Assert.That(contentType.PropertyTypes.All(x => x.PropertyGroupId.Value == groupId), Is.True); - foreach (var propertyType in contentType.PropertyTypes) + foreach (IPropertyType propertyType in contentType.PropertyTypes) { Assert.AreNotEqual(propertyType.Key, Guid.Empty); } - TestHelper.AssertPropertyValuesAreEqual(fetched, contentType, "yyyy-MM-dd HH:mm:ss", ignoreProperties: new [] { "DefaultTemplate", "AllowedTemplates", "UpdateDate" }); + TestHelper.AssertPropertyValuesAreEqual(fetched, contentType, ignoreProperties: new[] { "DefaultTemplate", "AllowedTemplates", "UpdateDate" }); } } @@ -299,10 +280,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_ContentTypeRepository_After_Model_Mapping() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act var contentType = (IContentType)ContentTypeBuilder.CreateSimpleContentType2("test", "Test", propertyGroupName: "testGroup"); @@ -313,18 +295,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // there is NO mapping from display to contentType, but only from save // to contentType, so if we want to test, let's to it properly! - var display = Mapper.Map(contentType); - var save = MapToContentTypeSave(display); - var mapped = Mapper.Map(save); + DocumentTypeDisplay display = Mapper.Map(contentType); + DocumentTypeSave save = MapToContentTypeSave(display); + IContentType mapped = Mapper.Map(save); Assert.AreEqual(4, mapped.PropertyTypes.Count()); repository.Save(mapped); - Assert.AreEqual(4, mapped.PropertyTypes.Count()); - //re-get + // re-get contentType = repository.Get(mapped.Id); Assert.AreEqual(4, contentType.PropertyTypes.Count()); @@ -336,29 +317,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.Path.Contains(","), Is.True); Assert.That(contentType.SortOrder, Is.GreaterThan(0)); - Assert.That(contentType.PropertyGroups.ElementAt(0).Name == "testGroup", Is.True); - var groupId = contentType.PropertyGroups.ElementAt(0).Id; + int groupId = contentType.PropertyGroups.ElementAt(0).Id; - var propertyTypes = contentType.PropertyTypes.ToArray(); + IPropertyType[] propertyTypes = contentType.PropertyTypes.ToArray(); Assert.AreEqual("gen", propertyTypes[0].Alias); // just to be sure Assert.IsNull(propertyTypes[0].PropertyGroupId); - Assert.IsTrue(propertyTypes.Skip(1).All((x => x.PropertyGroupId.Value == groupId))); - Assert.That(propertyTypes.Single(x=> x.Alias == "title").LabelOnTop, Is.True); + Assert.IsTrue(propertyTypes.Skip(1).All(x => x.PropertyGroupId.Value == groupId)); + Assert.That(propertyTypes.Single(x => x.Alias == "title").LabelOnTop, Is.True); } - } [Test] public void Can_Perform_Update_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); contentType.Thumbnail = "Doc2.png"; contentType.PropertyGroups["Content"].PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "subtitle") @@ -372,8 +352,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }); repository.Save(contentType); - - var dirty = contentType.IsDirty(); + bool dirty = contentType.IsDirty(); // Assert Assert.That(contentType.HasIdentity, Is.True); @@ -381,17 +360,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.Thumbnail, Is.EqualTo("Doc2.png")); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "subtitle"), Is.True); Assert.That(contentType.PropertyTypes.Single(x => x.Alias == "subtitle").LabelOnTop, Is.True); - } - - } // this is for tests only because it makes no sense at all to have such a // mapping defined, we only need it for the weird tests that use it - private DocumentTypeSave MapToContentTypeSave(DocumentTypeDisplay display) - { - return new DocumentTypeSave + private DocumentTypeSave MapToContentTypeSave(DocumentTypeDisplay display) => + new DocumentTypeSave { // EntityBasic Name = display.Name, @@ -399,9 +374,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Trashed = display.Trashed, Key = display.Key, ParentId = display.ParentId, - //Alias = display.Alias, + //// Alias = display.Alias, Path = display.Path, - //AdditionalData = display.AdditionalData, + //// AdditionalData = display.AdditionalData, // ContentTypeBasic Alias = display.Alias, @@ -416,7 +391,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor AllowAsRoot = display.AllowAsRoot, AllowedTemplates = display.AllowedTemplates.Select(x => x.Alias), AllowedContentTypes = display.AllowedContentTypes, - DefaultTemplate = display.DefaultTemplate == null ? null : display.DefaultTemplate.Alias, + DefaultTemplate = display.DefaultTemplate?.Alias, Groups = display.Groups.Select(x => new PropertyGroupBasic { Inherited = x.Inherited, @@ -426,27 +401,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Name = x.Name }).ToArray() }; - } [Test] public void Can_Perform_Update_On_ContentTypeRepository_After_Model_Mapping() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); // there is NO mapping from display to contentType, but only from save // to contentType, so if we want to test, let's to it properly! - var display = Mapper.Map(contentType); - var save = MapToContentTypeSave(display); + DocumentTypeDisplay display = Mapper.Map(contentType); + DocumentTypeSave save = MapToContentTypeSave(display); // modify... save.Thumbnail = "Doc2.png"; - var contentGroup = save.Groups.Single(x => x.Name == "Content"); + PropertyGroupBasic contentGroup = save.Groups.Single(x => x.Name == "Content"); contentGroup.Properties = contentGroup.Properties.Concat(new[] { new PropertyTypeBasic @@ -457,7 +432,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Validation = new PropertyTypeValidation { Mandatory = false, - Pattern = "" + Pattern = string.Empty }, SortOrder = 1, DataTypeId = -88, @@ -465,7 +440,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } }); - var mapped = Mapper.Map(save, contentType); + IContentType mapped = Mapper.Map(save, contentType); // just making sure Assert.AreEqual(mapped.Thumbnail, "Doc2.png"); @@ -474,10 +449,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(mapped); + bool dirty = mapped.IsDirty(); - var dirty = mapped.IsDirty(); - - //re-get + // re-get contentType = repository.Get(_textpageContentType.Id); // Assert @@ -488,7 +462,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.PropertyTypes.Single(x => x.Alias == "subtitle").LabelOnTop, Is.True); - foreach (var propertyType in contentType.PropertyTypes) + foreach (IPropertyType propertyType in contentType.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); Assert.Greater(propertyType.Id, 0); @@ -500,20 +474,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId:0); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: 0); repository.Save(contentType); - - var contentType2 = repository.Get(contentType.Id); + IContentType contentType2 = repository.Get(contentType.Id); repository.Delete(contentType2); - - var exists = repository.Exists(contentType.Id); + bool exists = repository.Exists(contentType.Id); // Assert Assert.That(exists, Is.False); @@ -524,25 +497,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_With_Heirarchy_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var ctMain = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId:0); - var ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true, defaultTemplateId: 0); - var ctChild2 = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, defaultTemplateId: 0); + ContentTypeRepository repository = ContentTypeRepository; + ContentType ctMain = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: 0); + ContentType ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true, defaultTemplateId: 0); + ContentType ctChild2 = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, defaultTemplateId: 0); repository.Save(ctMain); repository.Save(ctChild1); repository.Save(ctChild2); - // Act - - var resolvedParent = repository.Get(ctMain.Id); + IContentType resolvedParent = repository.Get(ctMain.Id); repository.Delete(resolvedParent); - // Assert Assert.That(repository.Exists(ctMain.Id), Is.False); Assert.That(repository.Exists(ctChild1.Id), Is.False); @@ -556,27 +526,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor IContentType contentType; // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; contentType = repository.Get(_textpageContentType.Id); - var child1 = ContentTypeBuilder.CreateSimpleContentType("abc", "abc", contentType, randomizeAliases: true, defaultTemplateId:0); + ContentType child1 = ContentTypeBuilder.CreateSimpleContentType("abc", "abc", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(child1); - var child3 = ContentTypeBuilder.CreateSimpleContentType("zyx", "zyx", contentType, randomizeAliases: true, defaultTemplateId:0); + ContentType child3 = ContentTypeBuilder.CreateSimpleContentType("zyx", "zyx", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(child3); - var child2 = ContentTypeBuilder.CreateSimpleContentType("a123", "a123", contentType, randomizeAliases: true, defaultTemplateId:0); + ContentType child2 = ContentTypeBuilder.CreateSimpleContentType("a123", "a123", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(child2); scope.Complete(); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentTypes = repository.Get(scope.SqlContext.Query().Where(x => x.ParentId == contentType.Id)); + IEnumerable contentTypes = repository.Get(scope.SqlContext.Query().Where(x => x.ParentId == contentType.Id)); // Assert Assert.That(contentTypes.Count(), Is.EqualTo(3)); @@ -584,20 +554,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("abc", contentTypes.ElementAt(1).Name); Assert.AreEqual("zyx", contentTypes.ElementAt(2).Name); } - } [Test] public void Can_Perform_Get_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); // Assert Assert.That(contentType, Is.Not.Null); @@ -609,17 +578,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_Guid_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); - var childContentType = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", contentType, randomizeAliases:true, defaultTemplateId:0); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); + ContentType childContentType = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(childContentType); - // Act - var result = repository.Get(childContentType.Key); + IContentType result = repository.Get(childContentType.Key); // Assert Assert.That(result, Is.Not.Null); @@ -631,12 +599,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_Missing_Guid_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var result = repository.Get(Guid.NewGuid()); + IContentType result = repository.Get(Guid.NewGuid()); // Assert Assert.That(result, Is.Null); @@ -647,17 +616,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var repository = (ContentTypeRepository)ContentTypeRepository; // Act - var contentTypes = repository.GetMany(); + IEnumerable contentTypes = repository.GetMany(); int count = scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType", - new {NodeObjectType = Constants.ObjectTypes.DocumentType}); + new { NodeObjectType = Constants.ObjectTypes.DocumentType }); // Assert Assert.That(contentTypes.Any(), Is.True); @@ -669,14 +638,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Guid_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var repository = (ContentTypeRepository)ContentTypeRepository; - var allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); + Guid[] allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); // Act - var contentTypes = ((IReadRepository)repository).GetMany(allGuidIds); + IEnumerable contentTypes = ((IReadRepository)repository).GetMany(allGuidIds); int count = scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType", @@ -692,13 +661,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var exists = repository.Exists(_simpleContentType.Id); + bool exists = repository.Exists(_simpleContentType.Id); // Assert Assert.That(exists, Is.True); @@ -709,18 +678,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_ContentType_With_PropertyType_Removed() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); // Act contentType.PropertyGroups["Meta"].PropertyTypes.Remove("description"); repository.Save(contentType); - - var result = repository.Get(_textpageContentType.Id); + IContentType result = repository.Get(_textpageContentType.Id); // Assert Assert.That(result.PropertyTypes.Any(x => x.Alias == "description"), Is.False); @@ -733,13 +701,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_SimpleTextpage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentType = repository.Get(_simpleContentType.Id); + IContentType contentType = repository.Get(_simpleContentType.Id); // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(3)); @@ -751,13 +719,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_Textpage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(4)); @@ -769,11 +737,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyType_With_No_Group() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); Assert.That(contentType.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(4)); @@ -782,22 +750,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var urlAlias = new PropertyType(ShortStringHelper, "test", ValueStorageType.Nvarchar, "urlAlias") { Name = "Url Alias", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var addedPropertyType = contentType.AddPropertyType(urlAlias); + bool addedPropertyType = contentType.AddPropertyType(urlAlias); Assert.That(contentType.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(5)); repository.Save(contentType); - // Assert - var updated = repository.Get(_textpageContentType.Id); + IContentType updated = repository.Get(_textpageContentType.Id); Assert.That(addedPropertyType, Is.True); Assert.That(updated.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(updated.PropertyTypes.Count(), Is.EqualTo(5)); @@ -810,19 +777,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_AllowedChildContentTypes_On_ContentType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var subpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSubpage", "Subpage"); - var simpleSubpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSimpleSubpage", "Simple Subpage"); + ContentType subpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSubpage", "Subpage"); + ContentType simpleSubpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSimpleSubpage", "Simple Subpage"); repository.Save(subpageContentType); repository.Save(simpleSubpageContentType); - // Act - var contentType = repository.Get(_simpleContentType.Id); + IContentType contentType = repository.Get(_simpleContentType.Id); contentType.AllowedContentTypes = new List { new ContentTypeSort(new Lazy(() => subpageContentType.Id), 0, subpageContentType.Alias), @@ -830,9 +796,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(contentType); - - //Assert - var updated = repository.Get(_simpleContentType.Id); + // Assert + IContentType updated = repository.Get(_simpleContentType.Id); Assert.That(updated.AllowedContentTypes.Any(), Is.True); Assert.That(updated.AllowedContentTypes.Any(x => x.Alias == subpageContentType.Alias), Is.True); @@ -844,21 +809,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Removal_Of_Used_PropertyType_From_ContentType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - // Act contentType.RemovePropertyType("keywords"); repository.Save(contentType); - // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "keywords"), Is.False); @@ -870,57 +833,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Addition_Of_PropertyType_After_ContentType_Is_Used() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - // Act - var propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); - propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + PropertyGroup propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); + propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); repository.Save(contentType); - // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(5)); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "metaAuthor"), Is.True); } - } [Test] public void Can_Verify_Usage_Of_New_PropertyType_On_Content() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - - var propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); - propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + PropertyGroup propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); + propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); repository.Save(contentType); - // Act - var content = DocumentRepository.Get(subpage.Id); + IContent content = DocumentRepository.Get(subpage.Id); content.SetValue("metaAuthor", "John Doe"); DocumentRepository.Save(content); - - //Assert - var updated = DocumentRepository.Get(subpage.Id); + // Assert + IContent updated = DocumentRepository.Get(subpage.Id); Assert.That(updated.GetValue("metaAuthor").ToString(), Is.EqualTo("John Doe")); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(5)); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "metaAuthor"), Is.True); @@ -931,33 +888,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_That_A_Combination_Of_Adding_And_Deleting_PropertyTypes_Doesnt_Cause_Issues_For_Content_And_ContentType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - - //Remove PropertyType + // Remove PropertyType contentType.RemovePropertyType("keywords"); - //Add PropertyType - var propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); - propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + + // Add PropertyType + PropertyGroup propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); + propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); repository.Save(contentType); - // Act - var content = DocumentRepository.Get(subpage.Id); + IContent content = DocumentRepository.Get(subpage.Id); content.SetValue("metaAuthor", "John Doe"); DocumentRepository.Save(content); - - //Assert - var updated = DocumentRepository.Get(subpage.Id); + // Assert + IContent updated = DocumentRepository.Get(subpage.Id); Assert.That(updated.GetValue("metaAuthor").ToString(), Is.EqualTo("John Doe")); Assert.That(updated.Properties.First(x => x.Alias == "description").GetValue(), Is.EqualTo("This is the meta description for a textpage")); @@ -971,21 +926,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Content_Type_Has_Content_Nodes() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var contentTypeId = _textpageContentType.Id; - var contentType = repository.Get(contentTypeId); + int contentTypeId = _textpageContentType.Id; + IContentType contentType = repository.Get(contentTypeId); // Act - var result = repository.HasContentNodes(contentTypeId); + bool result = repository.HasContentNodes(contentTypeId); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Test Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Test Page 1", contentType.Id); DocumentRepository.Save(subpage); - var result2 = repository.HasContentNodes(contentTypeId); + bool result2 = repository.HasContentNodes(contentTypeId); // Assert Assert.That(result, Is.False); @@ -993,6 +948,86 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } + [Test] + public void Can_Update_Variation_Of_Element_Type_Property() + { + var provider = ScopeProvider; + using (var scope = provider.CreateScope()) + { + ContentTypeRepository repository = ContentTypeRepository; + var contentRepository = DocumentRepository; + // Create elementType + var elementType = new ContentType(ShortStringHelper, -1) + { + Alias = "elementType", + Name = "Element type", + Description = "Element type to use as compositions", + Icon = ".sprTreeDoc3", + Thumbnail = "doc.png", + SortOrder = 1, + CreatorId = 0, + Trashed = false, + IsElement = true, + Variations = ContentVariation.Nothing + }; + + var contentCollection = new PropertyTypeCollection(true); + contentCollection.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext) + { + Alias = "title", + Name = "Title", + Description = "", + Mandatory = false, + SortOrder = 1, + DataTypeId = Constants.DataTypes.Textbox, + LabelOnTop = true, + Variations = ContentVariation.Nothing + }); + elementType.PropertyGroups.Add(new PropertyGroup(contentCollection) {Name = "Content", SortOrder = 1}); + elementType.ResetDirtyProperties(false); + elementType.SetDefaultTemplate(new Template(ShortStringHelper, "ElementType", "elementType")); + repository.Save(elementType); + + // Create the basic "home" doc type that uses element type as comp + var docType = new ContentType(ShortStringHelper, -1) + { + Alias = "home", + Name = "Home", + Description = "Home containing elementType", + Icon = ".sprTreeDoc3", + Thumbnail = "doc.png", + SortOrder = 1, + CreatorId = 0, + Trashed = false, + Variations = ContentVariation.Nothing + }; + var comp = new List(); + comp.Add(elementType); + docType.ContentTypeComposition = comp; + repository.Save(docType); + + // Create "home" content + var content = new Content("Home", -1, docType){Level = 1, SortOrder = 1, CreatorId = 0, WriterId = 0}; + object obj = new {title = "test title"}; + content.PropertyValues(obj); + content.ResetDirtyProperties(false); + contentRepository.Save(content); + + // Update variation on element type + elementType.Variations = ContentVariation.Culture; + elementType.PropertyTypes.First().Variations = ContentVariation.Culture; + repository.Save(elementType); + + // Update variation on doc type + docType.Variations = ContentVariation.Culture; + repository.Save(docType); + + // Re fetch renewedContent and make sure that the culture has been set. + var renewedContent = ContentService.GetById(content.Id); + var hasCulture = renewedContent.Properties["title"].Values.First().Culture != null; + Assert.That(hasCulture, Is.True); + } + } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs index c94b708ff9..699e22746f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs @@ -1,9 +1,16 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Events; using Umbraco.Core.Models; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; @@ -17,12 +24,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class DataTypeDefinitionRepositoryTest : UmbracoIntegrationTest { private IDataTypeService DataTypeService => GetRequiredService(); + private ILocalizedTextService LocalizedTextService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); + private IDataTypeContainerRepository DataTypeContainerRepository => GetRequiredService(); + private IDataTypeRepository DataTypeRepository => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); [Test] @@ -66,9 +80,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; ContentTypeRepository.Save(ct); - var usages = DataTypeRepository.FindUsages(dataType1.Id); + IReadOnlyDictionary> usages = DataTypeRepository.FindUsages(dataType1.Id); - var key = usages.First().Key; + Udi key = usages.First().Key; Assert.AreEqual(ct.Key, ((GuidUdi)key).Guid); Assert.AreEqual(2, usages[key].Count()); Assert.AreEqual("pt1", usages[key].ElementAt(0)); @@ -88,31 +102,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { using (ScopeProvider.CreateScope()) { - var container1 = new EntityContainer(Constants.ObjectTypes.DataType) { Name = "blah1" }; DataTypeContainerRepository.Save(container1); var container2 = new EntityContainer(Constants.ObjectTypes.DataType) { Name = "blah2", ParentId = container1.Id }; DataTypeContainerRepository.Save(container2); - var dataType = (IDataType) new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer, container2.Id) + var dataType = (IDataType)new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer, container2.Id) { Name = "dt1" }; DataTypeRepository.Save(dataType); - //create a + // create a var dataType2 = (IDataType)new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer, dataType.Id) { Name = "dt2" }; DataTypeRepository.Save(dataType2); - var result = DataTypeRepository.Move(dataType, container1).ToArray(); + MoveEventInfo[] result = DataTypeRepository.Move(dataType, container1).ToArray(); Assert.AreEqual(2, result.Length); - //re-get + // re-get dataType = DataTypeRepository.Get(dataType.Id); dataType2 = DataTypeRepository.Get(dataType2.Id); @@ -132,7 +145,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(container.Id, Is.GreaterThan(0)); - var found = DataTypeContainerRepository.Get(container.Id); + EntityContainer found = DataTypeContainerRepository.Get(container.Id); Assert.IsNotNull(found); } } @@ -148,7 +161,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeContainerRepository.Delete(container); - var found = DataTypeContainerRepository.Get(container.Id); + EntityContainer found = DataTypeContainerRepository.Get(container.Id); Assert.IsNull(found); } } @@ -182,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeContainerRepository.Delete(container); - var found = DataTypeContainerRepository.Get(container.Id); + EntityContainer found = DataTypeContainerRepository.Get(container.Id); Assert.IsNull(found); dataType = DataTypeRepository.Get(dataType.Id); @@ -196,11 +209,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { using (ScopeProvider.CreateScope()) { - IDataType dataType = new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) {Name = "test"}; + IDataType dataType = new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = "test" }; DataTypeRepository.Save(dataType); - var id = dataType.Id; + int id = dataType.Id; Assert.That(id, Is.GreaterThan(0)); // Act @@ -212,14 +225,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void Can_Perform_Get_On_DataTypeDefinitionRepository() { using (ScopeProvider.CreateScope()) { // Act - var dataTypeDefinition = DataTypeRepository.Get(Constants.DataTypes.DropDownSingle); + IDataType dataTypeDefinition = DataTypeRepository.Get(Constants.DataTypes.DropDownSingle); // Assert Assert.That(dataTypeDefinition, Is.Not.Null); @@ -234,7 +246,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var dataTypeDefinitions = DataTypeRepository.GetMany().ToArray(); + IDataType[] dataTypeDefinitions = DataTypeRepository.GetMany().ToArray(); // Assert Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -250,7 +262,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var dataTypeDefinitions = DataTypeRepository.GetMany(-40, -41, -42).ToArray(); + IDataType[] dataTypeDefinitions = DataTypeRepository.GetMany(-40, -41, -42).ToArray(); // Assert Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -263,12 +275,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_GetByQuery_On_DataTypeDefinitionRepository() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - // Act - var query = scope.SqlContext.Query().Where(x => x.EditorAlias == Constants.PropertyEditors.Aliases.RadioButtonList); - var result = DataTypeRepository.Get(query).ToArray(); + IQuery query = scope.SqlContext.Query().Where(x => x.EditorAlias == Constants.PropertyEditors.Aliases.RadioButtonList); + IDataType[] result = DataTypeRepository.Get(query).ToArray(); // Assert Assert.That(result, Is.Not.Null); @@ -280,10 +291,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Count_On_DataTypeDefinitionRepository() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { // Act - var query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("D")); + IQuery query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("D")); int count = DataTypeRepository.Count(query); // Assert @@ -307,15 +318,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeRepository.Save(dataTypeDefinition); - var exists = DataTypeRepository.Exists(dataTypeDefinition.Id); - var fetched = DataTypeRepository.Get(dataTypeDefinition.Id); + bool exists = DataTypeRepository.Exists(dataTypeDefinition.Id); + IDataType fetched = DataTypeRepository.Get(dataTypeDefinition.Id); // Assert Assert.That(dataTypeDefinition.HasIdentity, Is.True); Assert.That(exists, Is.True); // cannot compare 'configuration' as it's two different objects - TestHelper.AssertPropertyValuesAreEqual(dataTypeDefinition, fetched, "yyyy-MM-dd HH:mm:ss", ignoreProperties: new [] { "Configuration" }); + TestHelper.AssertPropertyValuesAreEqual(dataTypeDefinition, fetched, ignoreProperties: new[] { "Configuration" }); // still, can compare explicitely Assert.IsNotNull(dataTypeDefinition.Configuration); @@ -340,12 +351,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor DataTypeRepository.Save(dataTypeDefinition); // Act - var definition = DataTypeRepository.Get(dataTypeDefinition.Id); + IDataType definition = DataTypeRepository.Get(dataTypeDefinition.Id); definition.Name = "AgeDataType Updated"; - definition.Editor = new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer); //change + definition.Editor = new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer); // change DataTypeRepository.Save(definition); - var definitionUpdated = DataTypeRepository.Get(dataTypeDefinition.Id); + IDataType definitionUpdated = DataTypeRepository.Get(dataTypeDefinition.Id); // Assert Assert.That(definitionUpdated, Is.Not.Null); @@ -359,7 +370,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { using (ScopeProvider.CreateScope()) { - var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService,LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) + var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { DatabaseType = ValueStorageType.Integer, Name = "AgeDataType", @@ -369,11 +380,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeRepository.Save(dataTypeDefinition); - var existsBefore = DataTypeRepository.Exists(dataTypeDefinition.Id); + bool existsBefore = DataTypeRepository.Exists(dataTypeDefinition.Id); DataTypeRepository.Delete(dataTypeDefinition); - var existsAfter = DataTypeRepository.Exists(dataTypeDefinition.Id); + bool existsAfter = DataTypeRepository.Exists(dataTypeDefinition.Id); // Assert Assert.That(existsBefore, Is.True); @@ -387,8 +398,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var exists = DataTypeRepository.Exists(1046); //Content picker - var doesntExist = DataTypeRepository.Exists(-80); + bool exists = DataTypeRepository.Exists(1046); // Content picker + bool doesntExist = DataTypeRepository.Exists(-80); // Assert Assert.That(exists, Is.True); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs index 105d7520fd..edbeac263e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs @@ -1,10 +1,15 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -16,25 +21,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class DictionaryRepositoryTest : UmbracoIntegrationTest { [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); - private IDictionaryRepository CreateRepository() - { - return GetRequiredService(); - } + private IDictionaryRepository CreateRepository() => GetRequiredService(); [Test] public void Can_Perform_Get_By_Key_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235") { Translations = new List @@ -45,7 +44,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get("Testing1235"); // Assert @@ -61,11 +60,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_UniqueId_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235") { Translations = new List @@ -76,7 +75,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get(dictionaryItem.Key); // Assert @@ -92,11 +91,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235") { Translations = new List @@ -107,10 +106,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get(dictionaryItem.Id); - // Assert Assert.That(dictionaryItem, Is.Not.Null); Assert.That(dictionaryItem.ItemKey, Is.EqualTo("Testing1235")); @@ -124,18 +122,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_DictionaryRepository_When_No_Language_Assigned() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); - var dictionaryItem = (IDictionaryItem) new DictionaryItem("Testing1235"); + IDictionaryRepository repository = CreateRepository(); + var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235"); repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get(dictionaryItem.Id); - // Assert Assert.That(dictionaryItem, Is.Not.Null); Assert.That(dictionaryItem.ItemKey, Is.EqualTo("Testing1235")); @@ -147,14 +144,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var dictionaryItem = repository.Get(1); - var dictionaryItems = repository.GetMany(); + IDictionaryItem dictionaryItem = repository.Get(1); + IEnumerable dictionaryItems = repository.GetMany(); // Assert Assert.That(dictionaryItems, Is.Not.Null); @@ -168,13 +165,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var dictionaryItems = repository.GetMany(1, 2); + IEnumerable dictionaryItems = repository.GetMany(1, 2); // Assert Assert.That(dictionaryItems, Is.Not.Null); @@ -188,14 +185,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var query = provider.SqlContext.Query().Where(x => x.ItemKey == "Article"); - var result = repository.Get(query); + IQuery query = provider.SqlContext.Query().Where(x => x.ItemKey == "Article"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result, Is.Not.Null); @@ -208,14 +205,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var query = provider.SqlContext.Query().Where(x => x.ItemKey.StartsWith("Read")); - var result = repository.Count(query); + IQuery query = provider.SqlContext.Query().Where(x => x.ItemKey.StartsWith("Read")); + int result = repository.Count(query); // Assert Assert.That(result, Is.EqualTo(1)); @@ -226,13 +223,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var languageRepository = GetRequiredService(); - var repository = CreateRepository(); + ILanguageRepository languageRepository = GetRequiredService(); + IDictionaryRepository repository = CreateRepository(); - var language = languageRepository.Get(1); + ILanguage language = languageRepository.Get(1); var read = new DictionaryItem("Read"); var translations = new List @@ -244,7 +241,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act repository.Save(read); - var exists = repository.Exists(read.Id); + bool exists = repository.Exists(read.Id); // Assert Assert.That(read.HasIdentity, Is.True); @@ -256,20 +253,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var item = repository.Get(1); + IDictionaryItem item = repository.Get(1); var translations = item.Translations.ToList(); translations[0].Value = "Read even more"; item.Translations = translations; repository.Save(item); - var dictionaryItem = repository.Get(1); + IDictionaryItem dictionaryItem = repository.Get(1); // Assert Assert.That(dictionaryItem, Is.Not.Null); @@ -282,25 +279,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_WithNewTranslation_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var globalSettings = new GlobalSettings(); var languageNo = new Language(globalSettings, "nb-NO") { CultureName = "nb-NO" }; localizationService.Save(languageNo); // Act - var item = repository.Get(1); + IDictionaryItem item = repository.Get(1); var translations = item.Translations.ToList(); translations.Add(new DictionaryTranslation(languageNo, "Les mer")); item.Translations = translations; repository.Save(item); - var dictionaryItem = (DictionaryItem) repository.Get(1); + var dictionaryItem = (DictionaryItem)repository.Get(1); // Assert Assert.That(dictionaryItem, Is.Not.Null); @@ -313,16 +310,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var item = repository.Get(1); + IDictionaryItem item = repository.Get(1); repository.Delete(item); - var exists = repository.Exists(1); + bool exists = repository.Exists(1); // Assert Assert.That(exists, Is.False); @@ -333,13 +330,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var exists = repository.Exists(1); + bool exists = repository.Exists(1); // Assert Assert.That(exists, Is.True); @@ -351,27 +348,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { Dictionary keyMap; - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); keyMap = repository.GetDictionaryItemKeyMap(); } Assert.IsNotNull(keyMap); Assert.IsNotEmpty(keyMap); - foreach (var kvp in keyMap) + foreach (KeyValuePair kvp in keyMap) + { Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value); + } } public void CreateTestData() { - var localizationService = GetRequiredService(); - var language = localizationService.GetLanguageByIsoCode("en-US"); + ILocalizationService localizationService = GetRequiredService(); + ILanguage language = localizationService.GetLanguageByIsoCode("en-US"); var globalSettings = new GlobalSettings(); var languageDK = new Language(globalSettings, "da-DK") { CultureName = "da-DK" }; - localizationService.Save(languageDK);//Id 2 + localizationService.Save(languageDK); // Id 2 var readMore = new DictionaryItem("Read More"); var translations = new List @@ -380,7 +379,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new DictionaryTranslation(languageDK, "Læs mere") }; readMore.Translations = translations; - localizationService.Save(readMore);//Id 1 + localizationService.Save(readMore); // Id 1 var article = new DictionaryItem("Article"); var translations2 = new List @@ -389,7 +388,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new DictionaryTranslation(languageDK, "Artikel") }; article.Translations = translations2; - localizationService.Save(article);//Id 2 + localizationService.Save(article); // Id 2 } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs index e0ef0434c9..7bfc9ea573 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs @@ -1,7 +1,11 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; @@ -9,6 +13,7 @@ using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.PropertyEditors; @@ -32,10 +37,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Content _trashed; private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IFileSystems FileSystems => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); [SetUp] @@ -50,36 +60,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } [TearDown] - public void Teardown() - { - ContentRepositoryBase.ThrowOnWarning = false; - } + public void Teardown() => ContentRepositoryBase.ThrowOnWarning = false; public void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Create and Save ContentType "umbTextpage" -> (_contentType.Id) - _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId:template.Id); + // Create and Save ContentType "umbTextpage" -> (_contentType.Id) + _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); _contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"); ContentTypeService.Save(_contentType); - //Create and Save Content "Homepage" based on "umbTextpage" -> (_textpage.Id) + // Create and Save Content "Homepage" based on "umbTextpage" -> (_textpage.Id) _textpage = ContentBuilder.CreateSimpleContent(_contentType); _textpage.Key = new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0"); ContentService.Save(_textpage, 0); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage.Id) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage.Id) _subpage = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 1", _textpage.Id); _subpage.Key = new Guid("FF11402B-7E53-4654-81A7-462AC2108059"); ContentService.Save(_subpage, 0); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage2.Id) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage2.Id) _subpage2 = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 2", _textpage.Id); ContentService.Save(_subpage2, 0); - //Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (_trashed.Id) + // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (_trashed.Id) _trashed = ContentBuilder.CreateSimpleContent(_contentType, "Text Page Deleted", -20); _trashed.Trashed = true; ContentService.Save(_trashed, 0); @@ -87,26 +94,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out DataTypeRepository dtdRepository, AppCaches appCaches = null) { - appCaches = appCaches ?? AppCaches; + appCaches ??= AppCaches; - TemplateRepository tr; - var ctRepository = CreateRepository(scopeAccessor, out contentTypeRepository, out tr); + DocumentRepository ctRepository = CreateRepository(scopeAccessor, out contentTypeRepository, out TemplateRepository tr); var editors = new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty())); dtdRepository = new DataTypeRepository(scopeAccessor, appCaches, new Lazy(() => editors), LoggerFactory.CreateLogger(), LoggerFactory, ConfigurationEditorJsonSerializer); return ctRepository; } - private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, AppCaches appCaches = null) - { - TemplateRepository tr; - return CreateRepository(scopeAccessor, out contentTypeRepository, out tr, appCaches); - } + private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, AppCaches appCaches = null) => + CreateRepository(scopeAccessor, out contentTypeRepository, out TemplateRepository tr, appCaches); private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out TemplateRepository templateRepository, AppCaches appCaches = null) { - var globalSettings = Microsoft.Extensions.Options.Options.Create(new GlobalSettings()); + IOptions globalSettings = Options.Create(new GlobalSettings()); - appCaches = appCaches ?? AppCaches; + appCaches ??= AppCaches; templateRepository = new TemplateRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); var tagRepository = new TagRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger()); @@ -118,8 +121,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var relationRepository = new RelationRepository(scopeAccessor, LoggerFactory.CreateLogger(), relationTypeRepository, entityRepository); var propertyEditors = new Lazy(() => new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty()))); var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty()); - var repository = new DocumentRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger(), LoggerFactory, contentTypeRepository, templateRepository, tagRepository, languageRepository, relationRepository, - relationTypeRepository, propertyEditors, dataValueReferences, DataTypeService, ConfigurationEditorJsonSerializer); + var repository = new DocumentRepository( + scopeAccessor, + appCaches, + LoggerFactory.CreateLogger(), + LoggerFactory, + contentTypeRepository, + templateRepository, + tagRepository, + languageRepository, + relationRepository, + relationTypeRepository, + propertyEditors, + dataValueReferences, + DataTypeService, + ConfigurationEditorJsonSerializer); return repository; } @@ -131,41 +147,43 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new DictionaryAppCache(), new IsolatedCaches(t => new ObjectCacheAppCache())); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, appCaches: realCache); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, appCaches: realCache); - var udb = scope.Database; + IUmbracoDatabase udb = scope.Database; udb.EnableSqlCount = false; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); repository.Save(content); udb.EnableSqlCount = true; - //go get it, this should already be cached since the default repository key is the INT - repository.Get(content.Id); - Assert.AreEqual(0, udb.SqlCount); - //retrieve again, this should use cache + // go get it, this should already be cached since the default repository key is the INT repository.Get(content.Id); Assert.AreEqual(0, udb.SqlCount); - //reset counter + // retrieve again, this should use cache + repository.Get(content.Id); + Assert.AreEqual(0, udb.SqlCount); + + // reset counter udb.EnableSqlCount = false; udb.EnableSqlCount = true; - //now get by GUID, this won't be cached yet because the default repo key is not a GUID + // now get by GUID, this won't be cached yet because the default repo key is not a GUID repository.Get(content.Key); - var sqlCount = udb.SqlCount; + int sqlCount = udb.SqlCount; Assert.Greater(sqlCount, 0); - //retrieve again, this should use cache now + + // retrieve again, this should use cache now repository.Get(content.Key); Assert.AreEqual(sqlCount, udb.SqlCount); } @@ -174,16 +192,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CreateVersions() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, out DataTypeRepository _); var versions = new List(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); - + ContentType hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(hasPropertiesContentType); @@ -203,10 +220,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // NEW VERSION // new edit version has been created - Assert.AreNotEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreNotEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); Assert.AreEqual(PublishedState.Published, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -220,9 +237,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -234,10 +251,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreEqual(versions[^2], versions[^1]); Assert.IsFalse(content1.Published); Assert.AreEqual(PublishedState.Unpublished, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(false, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -251,8 +268,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^2], versions[^1]); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(false, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -265,10 +282,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // NEW VERSION // new version has been created - Assert.AreNotEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreNotEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); Assert.AreEqual(PublishedState.Published, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -278,15 +295,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor content1.Name = "name-3"; content1.SetValue("title", "title-3"); - //Thread.Sleep(2000); // force date change + //// Thread.Sleep(2000); // force date change repository.Save(content1); versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^2], versions[^1]); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -301,30 +318,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // NEW VERSION // a new version has been created - Assert.AreNotEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreNotEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); Assert.AreEqual(PublishedState.Published, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); // all versions - var allVersions = repository.GetAllVersions(content1.Id).ToArray(); + IContent[] allVersions = repository.GetAllVersions(content1.Id).ToArray(); Console.WriteLine(); - foreach (var v in versions) + foreach (int v in versions) + { Console.WriteLine(v); + } + Console.WriteLine(); - foreach (var v in allVersions) + foreach (IContent v in allVersions) { var c = (Content)v; Console.WriteLine($"{c.Id} {c.VersionId} {(c.Published ? "+" : "-")}pub pk={c.VersionId} ppk={c.PublishedVersionId} name=\"{c.Name}\" pname=\"{c.PublishName}\""); } // get older version - var content = repository.GetVersion(versions[versions.Count - 4]); + IContent content = repository.GetVersion(versions[^4]); Assert.AreNotEqual(0, content.VersionId); - Assert.AreEqual(versions[versions.Count - 4], content.VersionId); + Assert.AreEqual(versions[^4], content.VersionId); Assert.AreEqual("name-4", content1.Name); Assert.AreEqual("title-4", content1.GetValue("title")); Assert.AreEqual("name-2", content.Name); @@ -332,10 +352,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // get all versions - most recent first allVersions = repository.GetAllVersions(content1.Id).ToArray(); - var expVersions = versions.Distinct().Reverse().ToArray(); + int[] expVersions = versions.Distinct().Reverse().ToArray(); Assert.AreEqual(expVersions.Length, allVersions.Length); - for (var i = 0; i < expVersions.Length; i++) + for (int i = 0; i < expVersions.Length; i++) + { Assert.AreEqual(expVersions[i], allVersions[i].VersionId); + } } } @@ -350,36 +372,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void PropertyDataAssignedCorrectly() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, out DataTypeRepository _); - var emptyContentType = ContentTypeBuilder.CreateBasicContentType(); - var hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType emptyContentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(emptyContentType); contentTypeRepository.Save(hasPropertiesContentType); - - var content1 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); - var content2 = ContentBuilder.CreateBasicContent(emptyContentType); - var content3 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); - + Content content1 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); + Content content2 = ContentBuilder.CreateBasicContent(emptyContentType); + Content content3 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); repository.Save(content1); repository.Save(content2); repository.Save(content3); - // this will cause the GetPropertyCollection to execute and we need to ensure that // all of the properties and property types are all correct - var result = repository.GetMany(content1.Id, content2.Id, content3.Id).ToArray(); - var n1 = result[0]; - var n2 = result[1]; - var n3 = result[2]; + IContent[] result = repository.GetMany(content1.Id, content2.Id, content3.Id).ToArray(); + IContent n1 = result[0]; + IContent n2 = result[1]; + IContent n3 = result[2]; Assert.AreEqual(content1.Id, n1.Id); Assert.AreEqual(content2.Id, n2.Id); @@ -393,72 +412,72 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - // /// - // /// This test ensures that when property values using special database fields are saved, the actual data in the - // /// object being stored is also transformed in the same way as the data being stored in the database is. - // /// Before you would see that ex: a decimal value being saved as 100 or "100", would be that exact value in the - // /// object, but the value saved to the database was actually 100.000000. - // /// When querying the database for the value again - the value would then differ from what is in the object. - // /// This caused inconsistencies between saving+publishing and simply saving and then publishing, due to the former - // /// sending the non-transformed data directly on to publishing. - // /// - // [Test] - // public void PropertyValuesWithSpecialTypes() - // { - // var provider = ScopeProvider; - // using (var scope = provider.CreateScope()) - // { - // var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository dataTypeDefinitionRepository); - // - // var editor = new DecimalPropertyEditor(LoggerFactory, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper); - // var dtd = new DataType(editor) { Name = "test", DatabaseType = ValueStorageType.Decimal }; - // dataTypeDefinitionRepository.Save(dtd); - // - // const string decimalPropertyAlias = "decimalProperty"; - // const string intPropertyAlias = "intProperty"; - // const string dateTimePropertyAlias = "datetimeProperty"; - // var dateValue = new DateTime(2016, 1, 6); - // - // var propertyTypeCollection = new PropertyTypeCollection(true, - // new List - // { - // MockedPropertyTypes.CreateDecimalProperty(decimalPropertyAlias, "Decimal property", dtd.Id), - // MockedPropertyTypes.CreateIntegerProperty(intPropertyAlias, "Integer property"), - // MockedPropertyTypes.CreateDateTimeProperty(dateTimePropertyAlias, "DateTime property") - // }); - // var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", propertyTypeCollection); - // contentTypeRepository.Save(contentType); - // - // // int and decimal values are passed in as strings as they would be from the backoffice UI - // var textpage = ContentBuilder.CreateSimpleContentWithSpecialDatabaseTypes(contentType, "test@umbraco.org", -1, "100", "150", dateValue); - // - // repository.Save(textpage); - // scope.Complete(); - // - // Assert.That(contentType.HasIdentity, Is.True); - // Assert.That(textpage.HasIdentity, Is.True); - // - // var persistedTextpage = repository.Get(textpage.Id); - // Assert.That(persistedTextpage.Name, Is.EqualTo(textpage.Name)); - // Assert.AreEqual(100m, persistedTextpage.GetValue(decimalPropertyAlias)); - // Assert.AreEqual(persistedTextpage.GetValue(decimalPropertyAlias), textpage.GetValue(decimalPropertyAlias)); - // Assert.AreEqual(150, persistedTextpage.GetValue(intPropertyAlias)); - // Assert.AreEqual(persistedTextpage.GetValue(intPropertyAlias), textpage.GetValue(intPropertyAlias)); - // Assert.AreEqual(dateValue, persistedTextpage.GetValue(dateTimePropertyAlias)); - // Assert.AreEqual(persistedTextpage.GetValue(dateTimePropertyAlias), textpage.GetValue(dateTimePropertyAlias)); - // } - // } + //// /// + //// /// This test ensures that when property values using special database fields are saved, the actual data in the + //// /// object being stored is also transformed in the same way as the data being stored in the database is. + //// /// Before you would see that ex: a decimal value being saved as 100 or "100", would be that exact value in the + //// /// object, but the value saved to the database was actually 100.000000. + //// /// When querying the database for the value again - the value would then differ from what is in the object. + //// /// This caused inconsistencies between saving+publishing and simply saving and then publishing, due to the former + //// /// sending the non-transformed data directly on to publishing. + //// /// + //// [Test] + //// public void PropertyValuesWithSpecialTypes() + //// { + //// var provider = ScopeProvider; + //// using (var scope = provider.CreateScope()) + //// { + //// var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository dataTypeDefinitionRepository); + //// + //// var editor = new DecimalPropertyEditor(LoggerFactory, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper); + //// var dtd = new DataType(editor) { Name = "test", DatabaseType = ValueStorageType.Decimal }; + //// dataTypeDefinitionRepository.Save(dtd); + //// + //// const string decimalPropertyAlias = "decimalProperty"; + //// const string intPropertyAlias = "intProperty"; + //// const string dateTimePropertyAlias = "datetimeProperty"; + //// var dateValue = new DateTime(2016, 1, 6); + //// + //// var propertyTypeCollection = new PropertyTypeCollection(true, + //// new List + //// { + //// MockedPropertyTypes.CreateDecimalProperty(decimalPropertyAlias, "Decimal property", dtd.Id), + //// MockedPropertyTypes.CreateIntegerProperty(intPropertyAlias, "Integer property"), + //// MockedPropertyTypes.CreateDateTimeProperty(dateTimePropertyAlias, "DateTime property") + //// }); + //// var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", propertyTypeCollection); + //// contentTypeRepository.Save(contentType); + //// + //// // int and decimal values are passed in as strings as they would be from the backoffice UI + //// var textpage = ContentBuilder.CreateSimpleContentWithSpecialDatabaseTypes(contentType, "test@umbraco.org", -1, "100", "150", dateValue); + //// + //// repository.Save(textpage); + //// scope.Complete(); + //// + //// Assert.That(contentType.HasIdentity, Is.True); + //// Assert.That(textpage.HasIdentity, Is.True); + //// + //// var persistedTextpage = repository.Get(textpage.Id); + //// Assert.That(persistedTextpage.Name, Is.EqualTo(textpage.Name)); + //// Assert.AreEqual(100m, persistedTextpage.GetValue(decimalPropertyAlias)); + //// Assert.AreEqual(persistedTextpage.GetValue(decimalPropertyAlias), textpage.GetValue(decimalPropertyAlias)); + //// Assert.AreEqual(150, persistedTextpage.GetValue(intPropertyAlias)); + //// Assert.AreEqual(persistedTextpage.GetValue(intPropertyAlias), textpage.GetValue(intPropertyAlias)); + //// Assert.AreEqual(dateValue, persistedTextpage.GetValue(dateTimePropertyAlias)); + //// Assert.AreEqual(persistedTextpage.GetValue(dateTimePropertyAlias), textpage.GetValue(dateTimePropertyAlias)); + //// } + //// } [Test] public void SaveContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); IContent textpage = ContentBuilder.CreateSimpleContent(contentType); @@ -474,25 +493,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void SaveContentWithDefaultTemplate() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out TemplateRepository templateRepository); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, out TemplateRepository templateRepository); var template = new Template(ShortStringHelper, "hello", "hello"); templateRepository.Save(template); - - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage"); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage"); contentType.AllowedTemplates = Enumerable.Empty(); // because CreateSimpleContentType assigns one already contentType.SetDefaultTemplate(template); contentTypeRepository.Save(contentType); - var textpage = ContentBuilder.CreateSimpleContent(contentType); + Content textpage = ContentBuilder.CreateSimpleContent(contentType); repository.Save(textpage); - - var fetched = repository.Get(textpage.Id); + IContent fetched = repository.Get(textpage.Id); Assert.True(textpage.TemplateId.HasValue); Assert.NotZero(textpage.TemplateId.Value); @@ -500,40 +517,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); - TestHelper.AssertPropertyValuesAreEqual(textpage, fetched, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(textpage, fetched); } } - //Covers issue U4-2791 and U4-2607 + // Covers issue U4-2791 and U4-2607 [Test] public void SaveContentWithAtSignInName() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - - var textpage = ContentBuilder.CreateSimpleContent(contentType, "test@umbraco.org"); - var anotherTextpage = ContentBuilder.CreateSimpleContent(contentType, "@lightgiants"); + Content textpage = ContentBuilder.CreateSimpleContent(contentType, "test@umbraco.org"); + Content anotherTextpage = ContentBuilder.CreateSimpleContent(contentType, "@lightgiants"); repository.Save(textpage); repository.Save(anotherTextpage); - - Assert.That(contentType.HasIdentity, Is.True); Assert.That(textpage.HasIdentity, Is.True); - var content = repository.Get(textpage.Id); + IContent content = repository.Get(textpage.Id); Assert.That(content.Name, Is.EqualTo(textpage.Name)); - var content2 = repository.Get(anotherTextpage.Id); + IContent content2 = repository.Get(anotherTextpage.Id); Assert.That(content2.Name, Is.EqualTo(anotherTextpage.Name)); scope.Complete(); @@ -543,43 +557,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void SaveContentMultiple() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - var textpage = ContentBuilder.CreateSimpleContent(contentType); + Content textpage = ContentBuilder.CreateSimpleContent(contentType); repository.Save(textpage); - - var subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", textpage.Id); + Content subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", textpage.Id); repository.Save(subpage); - Assert.That(contentType.HasIdentity, Is.True); Assert.That(textpage.HasIdentity, Is.True); Assert.That(subpage.HasIdentity, Is.True); Assert.That(textpage.Id, Is.EqualTo(subpage.ParentId)); } - } - [Test] public void GetContentIsNotDirty() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage2.Id); - var dirty = ((Content)content).IsDirty(); + IContent content = repository.Get(_subpage2.Id); + bool dirty = ((Content)content).IsDirty(); Assert.That(dirty, Is.False); } @@ -588,16 +598,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void UpdateContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage.Id); + IContent content = repository.Get(_subpage.Id); content.Name = "About 2"; repository.Save(content); - var updatedContent = repository.Get(_subpage.Id); + IContent updatedContent = repository.Get(_subpage.Id); Assert.AreEqual(content.Id, updatedContent.Id); Assert.AreEqual(content.Name, updatedContent.Name); @@ -617,42 +627,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void UpdateContentWithNullTemplate() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage.Id); + IContent content = repository.Get(_subpage.Id); content.TemplateId = null; repository.Save(content); - var updatedContent = repository.Get(_subpage.Id); + IContent updatedContent = repository.Get(_subpage.Id); Assert.False(updatedContent.TemplateId.HasValue); } - } [Test] public void DeleteContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = contentTypeRepository.Get(_contentType.Id); - var content = new Content("Textpage 2 Child Node", _trashed.Id, contentType); - content.CreatorId = 0; - content.WriterId = 0; + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + IContentType contentType = contentTypeRepository.Get(_contentType.Id); + var content = new Content("Textpage 2 Child Node", _trashed.Id, contentType) + { + CreatorId = 0, + WriterId = 0 + }; repository.Save(content); - var id = content.Id; + int id = content.Id; repository.Delete(content); - - var content1 = repository.Get(id); + IContent content1 = repository.Get(id); Assert.IsNull(content1); } } @@ -660,11 +670,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage2.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); + IContent content = repository.Get(_subpage2.Id); Assert.AreEqual(_subpage2.Id, content.Id); Assert.That(content.CreateDate, Is.GreaterThan(DateTime.MinValue)); @@ -681,13 +691,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void QueryContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.Get(query); Assert.GreaterOrEqual(2, result.Count()); } @@ -698,36 +708,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { IContent[] result; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); result = repository.GetMany().ToArray(); // save them all - foreach (var content in result) + foreach (IContent content in result) { content.SetValue("title", content.GetValue("title") + "x"); repository.Save(content); } - // publish them all - foreach (var content in result) + foreach (IContent content in result) { content.PublishCulture(CultureImpact.Invariant); repository.Save(content); } - scope.Complete(); } // get them all again - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); - var result2 = repository.GetMany().ToArray(); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); + IContent[] result2 = repository.GetMany().ToArray(); Assert.AreEqual(result.Length, result2.Length); } @@ -736,10 +744,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void AliasRegexTest() { - var regex = new SqlServerSyntaxProvider().AliasRegex; + System.Text.RegularExpressions.Regex regex = new SqlServerSyntaxProvider().AliasRegex; Assert.AreEqual(@"(\[\w+]\.\[\w+])\s+AS\s+(\[\w+])", regex.ToString()); const string sql = "SELECT [table].[column1] AS [alias1], [table].[column2] AS [alias2] FROM [table];"; - var matches = regex.Matches(sql); + System.Text.RegularExpressions.MatchCollection matches = regex.Matches(sql); Assert.AreEqual(2, matches.Count); Assert.AreEqual("[table].[column1]", matches[0].Groups[1].Value); Assert.AreEqual("[alias1]", matches[0].Groups[2].Value); @@ -750,25 +758,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_With_Variant_Names() { - // one invariant content type named "umbInvariantTextPage" - // - var template = TemplateBuilder.CreateTextPageTemplate(); + // One invariant content type named "umbInvariantTextPage" + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var invariantCt = ContentTypeBuilder.CreateSimpleContentType("umbInvariantTextpage", "Invariant Textpage", defaultTemplateId: template.Id); + ContentType invariantCt = ContentTypeBuilder.CreateSimpleContentType("umbInvariantTextpage", "Invariant Textpage", defaultTemplateId: template.Id); invariantCt.Variations = ContentVariation.Nothing; - foreach (var p in invariantCt.PropertyTypes) p.Variations = ContentVariation.Nothing; + foreach (IPropertyType p in invariantCt.PropertyTypes) + { + p.Variations = ContentVariation.Nothing; + } + ContentTypeService.Save(invariantCt); - // one variant (by culture) content type named "umbVariantTextPage" + // One variant (by culture) content type named "umbVariantTextPage" // with properties, every 2nd one being variant (by culture), the other being invariant - // - - var variantCt = ContentTypeBuilder.CreateSimpleContentType("umbVariantTextpage", "Variant Textpage", defaultTemplateId: template.Id); + ContentType variantCt = ContentTypeBuilder.CreateSimpleContentType("umbVariantTextpage", "Variant Textpage", defaultTemplateId: template.Id); variantCt.Variations = ContentVariation.Culture; var propTypes = variantCt.PropertyTypes.ToList(); - for (var i = 0; i < propTypes.Count; i++) + for (int i = 0; i < propTypes.Count; i++) { - var p = propTypes[i]; + IPropertyType p = propTypes[i]; p.Variations = i % 2 == 0 ? ContentVariation.Culture : ContentVariation.Nothing; } @@ -777,30 +786,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor invariantCt.AllowedContentTypes = new[] { new ContentTypeSort(invariantCt.Id, 0), new ContentTypeSort(variantCt.Id, 1) }; ContentTypeService.Save(invariantCt); - //create content - - var root = ContentBuilder.CreateSimpleContent(invariantCt); + // Create content + Content root = ContentBuilder.CreateSimpleContent(invariantCt); ContentService.Save(root); var children = new List(); - for (var i = 0; i < 25; i++) + for (int i = 0; i < 25; i++) { - var isInvariant = i % 2 == 0; - var name = (isInvariant ? "INV" : "VAR") + "_" + Guid.NewGuid(); - var culture = isInvariant ? null : "en-US"; + bool isInvariant = i % 2 == 0; + string name = (isInvariant ? "INV" : "VAR") + "_" + Guid.NewGuid(); + string culture = isInvariant ? null : "en-US"; - var child = ContentBuilder.CreateSimpleContent( + Content child = ContentBuilder.CreateSimpleContent( isInvariant ? invariantCt : variantCt, - name, root, + name, + root, culture, setPropertyValues: isInvariant); if (!isInvariant) { - //manually set the property values since we have mixed variant/invariant property types + // manually set the property values since we have mixed variant/invariant property types child.SetValue("title", name + " Subpage", culture: culture); - child.SetValue("bodyText", "This is a subpage", culture: null); //this one is invariant + child.SetValue("bodyText", "This is a subpage", culture: null); // this one is invariant child.SetValue("author", "John Doe", culture: culture); } @@ -808,17 +817,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor children.Add(child); } - var child1 = children[1]; + IContent child1 = children[1]; Assert.IsTrue(child1.ContentType.VariesByCulture()); Assert.IsTrue(child1.Name.StartsWith("VAR")); Assert.IsTrue(child1.GetCultureName("en-US").StartsWith("VAR")); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var child = repository.Get(children[1].Id); // 1 is variant + IContent child = repository.Get(children[1].Id); // 1 is variant Assert.IsTrue(child.ContentType.VariesByCulture()); Assert.IsTrue(child.Name.StartsWith("VAR")); Assert.IsTrue(child.GetCultureName("en-US").StartsWith("VAR")); @@ -828,23 +837,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var query = scope.SqlContext.Query().Where(x => x.ParentId == root.Id); - var result = repository.GetPage(query, 0, 20, out var totalRecords, null, Ordering.By("UpdateDate")); + IQuery query = scope.SqlContext.Query().Where(x => x.ParentId == root.Id); + IEnumerable result = repository.GetPage(query, 0, 20, out long totalRecords, null, Ordering.By("UpdateDate")); Assert.AreEqual(25, totalRecords); - foreach (var r in result) + foreach (IContent r in result) { - var isInvariant = r.ContentType.Alias == "umbInvariantTextpage"; - var name = isInvariant ? r.Name : r.CultureInfos["en-US"].Name; - var namePrefix = isInvariant ? "INV" : "VAR"; + bool isInvariant = r.ContentType.Alias == "umbInvariantTextpage"; + string name = isInvariant ? r.Name : r.CultureInfos["en-US"].Name; + string namePrefix = isInvariant ? "INV" : "VAR"; - //ensure the correct name (invariant vs variant) is in the result + // ensure the correct name (invariant vs variant) is in the result Assert.IsTrue(name.StartsWith(namePrefix)); - foreach (var p in r.Properties) + foreach (IProperty p in r.Properties) { - //ensure there is a value for the correct variant/invariant property - var value = p.GetValue(p.PropertyType.Variations.VariesByNothing() ? null : "en-US"); + // ensure there is a value for the correct variant/invariant property + object value = p.GetValue(p.PropertyType.Variations.VariesByNothing() ? null : "en-US"); Assert.IsNotNull(value); } } @@ -860,19 +869,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_CustomPropertySort() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Name.Contains("Text")); + IQuery query = scope.SqlContext.Query().Where(x => x.Name.Contains("Text")); try { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var result = repository.GetPage(query, 0, 2, out var totalRecords, null, Ordering.By("title", isCustomField: true)); + IEnumerable result = repository.GetPage(query, 0, 2, out long totalRecords, null, Ordering.By("title", isCustomField: true)); Assert.AreEqual(3, totalRecords); Assert.AreEqual(2, result.Count()); @@ -892,19 +901,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_FirstPage() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); try { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var result = repository.GetPage(query, 0, 1, out var totalRecords, null, Ordering.By("Name")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("Name")); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -921,13 +930,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_SecondPage() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 1, 1, out var totalRecords, null, Ordering.By("Name")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 1, 1, out long totalRecords, null, Ordering.By("Name")); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -938,13 +947,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_SinglePage() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 0, 2, out var totalRecords, null, Ordering.By("Name")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 2, out long totalRecords, null, Ordering.By("Name")); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(2)); @@ -955,13 +964,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_DescendingOrder() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 0, 1, out var totalRecords, null, Ordering.By("Name", Direction.Descending)); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("Name", Direction.Descending)); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -972,15 +981,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_FilterMatchingSome() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("Page 2")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filterQuery, Ordering.By("Name")); + IQuery filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("Page 2")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filterQuery, Ordering.By("Name")); Assert.That(totalRecords, Is.EqualTo(1)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -991,15 +1000,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_FilterMatchingAll() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("text")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filterQuery, Ordering.By("Name")); + IQuery filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("text")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filterQuery, Ordering.By("Name")); Assert.That(totalRecords, Is.EqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -1010,13 +1019,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetAllContentByIds() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); - - var contents = repository.GetMany(_subpage.Id, _subpage2.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); + IEnumerable contents = repository.GetMany(_subpage.Id, _subpage2.Id); Assert.That(contents, Is.Not.Null); Assert.That(contents.Any(), Is.True); @@ -1027,12 +1035,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetAllContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var contents = repository.GetMany(); + IEnumerable contents = repository.GetMany(); Assert.That(contents, Is.Not.Null); Assert.That(contents.Any(), Is.True); @@ -1053,12 +1061,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void ExistContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var exists = repository.Exists(_subpage.Id); + bool exists = repository.Exists(_subpage.Id); Assert.That(exists, Is.True); } @@ -1067,13 +1075,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CountContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + int result = repository.Count(query); Assert.That(result, Is.GreaterThanOrEqualTo(2)); } @@ -1082,19 +1090,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void QueryContentByUniqueId() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Key == new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); - var content = repository.Get(query).SingleOrDefault(); + IQuery query = scope.SqlContext.Query().Where(x => x.Key == new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent content = repository.Get(query).SingleOrDefault(); Assert.IsNotNull(content); Assert.AreEqual(_textpage.Id, content.Id); } } - - } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs index b6faa4e31d..3a9794a93b 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Data; using System.Linq; using Microsoft.Extensions.Logging; @@ -20,20 +23,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class DomainRepositoryTest : UmbracoIntegrationTest { private ILanguageRepository LanguageRepository => GetRequiredService(); + private IDocumentRepository DocumentRepository => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); private DomainRepository CreateRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; + var accessor = (IScopeAccessor)provider; var domainRepository = new DomainRepository(accessor, AppCaches.NoCache, LoggerFactory.CreateLogger()); return domainRepository; } private int CreateTestData(string isoName, out ContentType ct) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var globalSettings = new GlobalSettings(); var lang = new Language(globalSettings, isoName); @@ -51,21 +56,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_And_Get_By_Id() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); Assert.NotNull(domain); @@ -81,20 +85,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_And_Get_By_Id_Empty_lang() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var content = DocumentRepository.Get(contentId); + IContent content = DocumentRepository.Get(contentId); var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id }; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); Assert.NotNull(domain); @@ -109,16 +112,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Cant_Create_Duplicate_Domain_Name() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var domain1 = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain1); @@ -132,26 +134,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); repo.Delete(domain); - //re-get + // re-get domain = repo.Get(domain.Id); - Assert.IsNull(domain); } } @@ -159,29 +159,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Update() { - ContentType ct; - var contentId1 = CreateTestData("en-AU", out ct); + int contentId1 = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var content1 = DocumentRepository.Get(contentId1); + IContent content1 = DocumentRepository.Get(contentId1); - //more test data - var lang1 = LanguageRepository.GetByIsoCode("en-AU"); + // more test data + ILanguage lang1 = LanguageRepository.GetByIsoCode("en-AU"); var globalSettings = new GlobalSettings(); var lang2 = new Language(globalSettings, "es"); LanguageRepository.Save(lang2); var content2 = new Content("test", -1, ct) { CreatorId = 0, WriterId = 0 }; DocumentRepository.Save(content2); - var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content1.Id, LanguageId = lang1.Id }; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); domain.DomainName = "blah.com"; @@ -189,7 +187,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor domain.LanguageId = lang2.Id; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); Assert.AreEqual("blah.com", domain.DomainName); @@ -199,20 +197,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void Exists() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -220,7 +216,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var found = repo.Exists("test1.com"); + bool found = repo.Exists("test1.com"); Assert.IsTrue(found); } @@ -229,16 +225,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_By_Name() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -246,7 +241,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var found = repo.GetByName("test1.com"); + IDomain found = repo.GetByName("test1.com"); Assert.IsNotNull(found); } @@ -255,16 +250,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -272,7 +266,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all = repo.GetMany(); + IEnumerable all = repo.GetMany(); Assert.AreEqual(10, all.Count()); } @@ -281,16 +275,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_Ids() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var ids = new List(); for (int i = 0; i < 10; i++) @@ -300,7 +293,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor ids.Add(domain.Id); } - var all = repo.GetMany(ids.Take(8).ToArray()); + IEnumerable all = repo.GetMany(ids.Take(8).ToArray()); Assert.AreEqual(8, all.Count()); } @@ -309,16 +302,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_Without_Wildcards() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -330,7 +322,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all = repo.GetAll(false); + IEnumerable all = repo.GetAll(false); Assert.AreEqual(5, all.Count()); } @@ -339,20 +331,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_For_Content() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); var contentItems = new List(); - var lang = LanguageRepository.GetByIsoCode("en-AU"); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); contentItems.Add(DocumentRepository.Get(contentId)); - //more test data (3 content items total) + // more test data (3 content items total) for (int i = 0; i < 2; i++) { var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 }; @@ -370,13 +361,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all1 = repo.GetAssignedDomains(contentItems[0].Id, true); + IEnumerable all1 = repo.GetAssignedDomains(contentItems[0].Id, true); Assert.AreEqual(5, all1.Count()); - var all2 = repo.GetAssignedDomains(contentItems[1].Id, true); + IEnumerable all2 = repo.GetAssignedDomains(contentItems[1].Id, true); Assert.AreEqual(5, all2.Count()); - var all3 = repo.GetAssignedDomains(contentItems[2].Id, true); + IEnumerable all3 = repo.GetAssignedDomains(contentItems[2].Id, true); Assert.AreEqual(0, all3.Count()); } } @@ -384,20 +375,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_For_Content_Without_Wildcards() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); var contentItems = new List(); - var lang = LanguageRepository.GetByIsoCode("en-AU"); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); contentItems.Add(DocumentRepository.Get(contentId)); - //more test data (3 content items total) + // more test data (3 content items total) for (int i = 0; i < 2; i++) { var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 }; @@ -415,10 +405,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all1 = repo.GetAssignedDomains(contentItems[0].Id, false); + IEnumerable all1 = repo.GetAssignedDomains(contentItems[0].Id, false); Assert.AreEqual(5, all1.Count()); - var all2 = repo.GetAssignedDomains(contentItems[1].Id, false); + IEnumerable all2 = repo.GetAssignedDomains(contentItems[1].Id, false); Assert.AreEqual(0, all2.Count()); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs index 8fbfc765d7..cd2e5e5d01 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Collections.Generic; using System.Linq; using NUnit.Framework; @@ -5,6 +8,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Core.Services; @@ -18,71 +22,61 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [UmbracoTest(Mapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class EntityRepositoryTest : UmbracoIntegrationTest { - private EntityRepository CreateRepository(IScopeAccessor scopeAccessor) - { - var entityRepository = new EntityRepository(scopeAccessor, AppCaches.Disabled); - return entityRepository; - } - [Test] public void Get_Paged_Mixed_Entities_By_Ids() { - //Create content - - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + // Create content + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); var createdContent = new List(); - var contentType = ContentTypeBuilder.CreateBasicContentType("blah"); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType("blah"); contentTypeService.Save(contentType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateBasicContent(contentType); + Content c1 = ContentBuilder.CreateBasicContent(contentType); contentService.Save(c1); createdContent.Add(c1); } - //Create media - - var mediaService = GetRequiredService(); - var mediaTypeService = GetRequiredService(); + // Create media + IMediaService mediaService = GetRequiredService(); + IMediaTypeService mediaTypeService = GetRequiredService(); var createdMedia = new List(); - var imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); + MediaType imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); mediaTypeService.Save(imageType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageType, -1); + Media c1 = MediaBuilder.CreateMediaImage(imageType, -1); mediaService.Save(c1); createdMedia.Add(c1); } // Create members - - var memberService = GetRequiredService(); - var memberTypeService = GetRequiredService(); - var memberType = MemberTypeBuilder.CreateSimpleMemberType("simple"); + IMemberService memberService = GetRequiredService(); + IMemberTypeService memberTypeService = GetRequiredService(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType("simple"); memberTypeService.Save(memberType); var createdMembers = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10).ToList(); memberService.Save(createdMembers); - - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repo = CreateRepository((IScopeAccessor)provider); + EntityRepository repo = CreateRepository((IScopeAccessor)provider); - var ids = createdContent.Select(x => x.Id).Concat(createdMedia.Select(x => x.Id)).Concat(createdMembers.Select(x => x.Id)); + IEnumerable ids = createdContent.Select(x => x.Id).Concat(createdMedia.Select(x => x.Id)).Concat(createdMembers.Select(x => x.Id)); - var objectTypes = new[] { Constants.ObjectTypes.Document, Constants.ObjectTypes.Media, Constants.ObjectTypes.Member }; + System.Guid[] objectTypes = new[] { Constants.ObjectTypes.Document, Constants.ObjectTypes.Media, Constants.ObjectTypes.Member }; - var query = provider.SqlContext.Query() + IQuery query = provider.SqlContext.Query() .WhereIn(e => e.Id, ids); - var entities = repo.GetPagedResultsByQuery(query, objectTypes, 0, 20, out var totalRecords, null, null).ToList(); + var entities = repo.GetPagedResultsByQuery(query, objectTypes, 0, 20, out long totalRecords, null, null).ToList(); Assert.AreEqual(20, entities.Count); Assert.AreEqual(30, totalRecords); - //add the next page + // add the next page entities.AddRange(repo.GetPagedResultsByQuery(query, objectTypes, 1, 20, out totalRecords, null, null)); Assert.AreEqual(30, entities.Count); @@ -97,5 +91,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual(10, memberEntities.Count); } } + + private EntityRepository CreateRepository(IScopeAccessor scopeAccessor) => new EntityRepository(scopeAccessor, AppCaches.Disabled); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs index 93b6ee43f5..29885d732d 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs @@ -1,6 +1,9 @@ -using System; -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Microsoft.Extensions.Logging; +using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; @@ -17,10 +20,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSetAndGet() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; // Insert new key/value - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { var keyValue = new KeyValue { @@ -28,26 +31,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Value = "bar", UpdateDate = DateTime.Now, }; - var repo = CreateRepository(provider); + IKeyValueRepository repo = CreateRepository(provider); repo.Save(keyValue); scope.Complete(); } // Retrieve key/value - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var keyValue = repo.Get("foo"); + IKeyValueRepository repo = CreateRepository(provider); + IKeyValue keyValue = repo.Get("foo"); scope.Complete(); Assert.AreEqual("bar", keyValue.Value); } // Update value - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var keyValue = repo.Get("foo"); + IKeyValueRepository repo = CreateRepository(provider); + IKeyValue keyValue = repo.Get("foo"); keyValue.Value = "buzz"; keyValue.UpdateDate = DateTime.Now; repo.Save(keyValue); @@ -55,19 +58,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } // Retrieve key/value again - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var keyValue = repo.Get("foo"); + IKeyValueRepository repo = CreateRepository(provider); + IKeyValue keyValue = repo.Get("foo"); scope.Complete(); Assert.AreEqual("buzz", keyValue.Value); } } - private IKeyValueRepository CreateRepository(IScopeProvider provider) - { - return new KeyValueRepository((IScopeAccessor) provider, LoggerFactory.CreateLogger()); - } + private IKeyValueRepository CreateRepository(IScopeProvider provider) => new KeyValueRepository((IScopeAccessor)provider, LoggerFactory.CreateLogger()); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.cs index aa9c0ddc86..45e63cf091 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Extensions.Logging; @@ -7,6 +11,7 @@ using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Persistence; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Core.Services; @@ -28,23 +33,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor _globalSettings = new GlobalSettings(); } - private LanguageRepository CreateRepository(IScopeProvider provider) - { - return new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(_globalSettings)); - } - [Test] public void Can_Perform_Get_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(1); + ILanguage language = repository.Get(1); // Assert Assert.That(language, Is.Not.Null); @@ -58,10 +58,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Get_By_Iso_Code_On_LanguageRepository() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); var au = CultureInfo.GetCultureInfo("en-AU"); var language = (ILanguage)new Language(_globalSettings, au.Name) @@ -71,7 +71,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(language); - //re-get + // re-get language = repository.GetByIsoCode(au.Name); // Assert @@ -87,13 +87,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Get_When_Id_Doesnt_Exist_Returns_Null() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(0); + ILanguage language = repository.Get(0); // Assert Assert.That(language, Is.Null); @@ -104,13 +104,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var languages = repository.GetMany(); + IEnumerable languages = repository.GetMany(); // Assert Assert.That(languages, Is.Not.Null); @@ -124,13 +124,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var languages = repository.GetMany(1, 2); + IEnumerable languages = repository.GetMany(1, 2); // Assert Assert.That(languages, Is.Not.Null); @@ -144,14 +144,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var query = scope.SqlContext.Query().Where(x => x.IsoCode == "da-DK"); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.IsoCode == "da-DK"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result, Is.Not.Null); @@ -164,13 +164,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var query = scope.SqlContext.Query().Where(x => x.IsoCode.StartsWith("D")); + IQuery query = scope.SqlContext.Query().Where(x => x.IsoCode.StartsWith("D")); int count = repository.Count(query); // Assert @@ -182,10 +182,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act var languageBR = new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR" }; @@ -193,7 +193,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(languageBR.HasIdentity, Is.True); - Assert.That(languageBR.Id, Is.EqualTo(6)); //With 5 existing entries the Id should be 6 + Assert.That(languageBR.Id, Is.EqualTo(6)); // With 5 existing entries the Id should be 6 Assert.IsFalse(languageBR.IsDefault); Assert.IsFalse(languageBR.IsMandatory); Assert.IsNull(languageBR.FallbackLanguageId); @@ -204,10 +204,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository_With_Boolean_Properties() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act var languageBR = new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; @@ -215,7 +215,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(languageBR.HasIdentity, Is.True); - Assert.That(languageBR.Id, Is.EqualTo(6)); //With 5 existing entries the Id should be 6 + Assert.That(languageBR.Id, Is.EqualTo(6)); // With 5 existing entries the Id should be 6 Assert.IsTrue(languageBR.IsDefault); Assert.IsTrue(languageBR.IsMandatory); Assert.IsNull(languageBR.FallbackLanguageId); @@ -226,10 +226,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository_With_Fallback_Language() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act var languageBR = new Language(_globalSettings, "pt-BR") @@ -241,7 +241,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(languageBR.HasIdentity, Is.True); - Assert.That(languageBR.Id, Is.EqualTo(6)); //With 5 existing entries the Id should be 6 + Assert.That(languageBR.Id, Is.EqualTo(6)); // With 5 existing entries the Id should be 6 Assert.That(languageBR.FallbackLanguageId, Is.EqualTo(1)); } } @@ -250,10 +250,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository_With_New_Default() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); var languageBR = (ILanguage)new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; repository.Save(languageBR); @@ -278,20 +278,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(5); + ILanguage language = repository.Get(5); language.IsoCode = "pt-BR"; language.CultureName = "pt-BR"; language.FallbackLanguageId = 1; repository.Save(language); - var languageUpdated = repository.Get(5); + ILanguage languageUpdated = repository.Get(5); // Assert Assert.That(languageUpdated, Is.Not.Null); @@ -305,13 +305,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Perform_Update_With_Existing_Culture() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(5); + ILanguage language = repository.Get(5); language.IsoCode = "da-DK"; language.CultureName = "da-DK"; @@ -323,16 +323,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(3); + ILanguage language = repository.Get(3); repository.Delete(language); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -343,20 +343,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_LanguageRepository_With_Language_Used_As_Fallback() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { // Add language to delete as a fall-back language to another one - var repository = CreateRepository(provider); - var languageToFallbackFrom = repository.Get(5); + LanguageRepository repository = CreateRepository(provider); + ILanguage languageToFallbackFrom = repository.Get(5); languageToFallbackFrom.FallbackLanguageId = 2; // fall back to #2 (something we can delete) repository.Save(languageToFallbackFrom); // delete #2 - var languageToDelete = repository.Get(2); + ILanguage languageToDelete = repository.Get(2); repository.Delete(languageToDelete); - var exists = repository.Exists(2); + bool exists = repository.Exists(2); // has been deleted Assert.That(exists, Is.False); @@ -367,14 +367,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(10); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(10); // Assert Assert.That(exists, Is.True); @@ -382,22 +382,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } + private LanguageRepository CreateRepository(IScopeProvider provider) => new LanguageRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(_globalSettings)); + private void CreateTestData() { - //Id 1 is en-US - when Umbraco is installed - - var localizationService = GetRequiredService(); + // Id 1 is en-US - when Umbraco is installed + ILocalizationService localizationService = GetRequiredService(); var languageDK = new Language(_globalSettings, "da-DK") { CultureName = "da-DK" }; - localizationService.Save(languageDK);//Id 2 + localizationService.Save(languageDK); // Id 2 var languageSE = new Language(_globalSettings, "sv-SE") { CultureName = "sv-SE" }; - localizationService.Save(languageSE);//Id 3 + localizationService.Save(languageSE); // Id 3 var languageDE = new Language(_globalSettings, "de-DE") { CultureName = "de-DE" }; - localizationService.Save(languageDE);//Id 4 + localizationService.Save(languageDE); // Id 4 var languagePT = new Language(_globalSettings, "pt-PT") { CultureName = "pt-PT" }; - localizationService.Save(languagePT);//Id 5 + localizationService.Save(languagePT); // Id 5 } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs index e68f9584fb..160642bcb7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs @@ -1,4 +1,8 @@ -using System.Data.SqlClient; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; @@ -29,10 +33,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Cannot_Add_Duplicate_Macros() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "test1", "Test", "~/views/macropartials/test.cshtml"); @@ -44,12 +48,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Cannot_Update_To_Duplicate_Macro_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Alias = "test2"; Assert.Throws(() => repository.Save(macro)); @@ -60,10 +64,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Assert Assert.That(repository, Is.Not.Null); @@ -74,13 +78,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macro = repository.Get(1); + IMacro macro = repository.Get(1); // Assert Assert.That(macro, Is.Not.Null); @@ -100,13 +104,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macros = repository.GetMany(); + IEnumerable macros = repository.GetMany(); // Assert Assert.That(macros.Count(), Is.EqualTo(3)); @@ -117,14 +121,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_Repository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias.ToUpper() == "TEST1"); - var result = repository.Get((IQuery) query); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias.ToUpper() == "TEST1"); + IEnumerable result = repository.Get((IQuery)query); // Assert Assert.AreEqual(1, result.Count()); @@ -135,13 +139,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_Repository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("Test")); + IQuery query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("Test")); int count = repository.Count(query); // Assert @@ -153,10 +157,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act var macro = new Macro(ShortStringHelper, "test", "Test", "~/views/macropartials/test.cshtml"); @@ -165,7 +169,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(macro.HasIdentity, Is.True); - Assert.That(macro.Id, Is.EqualTo(4));//With 3 existing entries the Id should be 4 + Assert.That(macro.Id, Is.EqualTo(4)); // With 3 existing entries the Id should be 4 Assert.Greater(macro.Properties.Values.Single().Id, 0); } } @@ -174,13 +178,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macro = repository.Get(2); + IMacro macro = repository.Get(2); macro.Name = "Hello"; macro.CacheDuration = 1234; macro.CacheByPage = true; @@ -191,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(macro); - var macroUpdated = repository.Get(2); + IMacro macroUpdated = repository.Get(2); // Assert Assert.That(macroUpdated, Is.Not.Null); @@ -209,17 +213,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macro = repository.Get(3); + IMacro macro = repository.Get(3); Assert.IsNotNull(macro); repository.Delete(macro); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -230,14 +234,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(10); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(10); // Assert Assert.That(exists, Is.True); @@ -249,25 +253,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_Property_For_Macro() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); repository.Save(macro); // Assert - Assert.Greater(macro.Properties.Values.First().Id, 0); //ensure id is returned - var result = repository.Get(1); + Assert.Greater(macro.Properties.Values.First().Id, 0); // ensure id is returned + IMacro result = repository.Get(1); Assert.Greater(result.Properties.Values.First().Id, 0); Assert.AreEqual(1, result.Properties.Values.Count()); Assert.AreEqual("new1", result.Properties.Values.First().Alias); Assert.AreEqual("New1", result.Properties.Values.First().Name); Assert.AreEqual(3, result.Properties.Values.First().SortOrder); - } } @@ -275,24 +278,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_New_Macro_With_Property() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); - // Assert - var result = repository.Get(macro.Id); + IMacro result = repository.Get(macro.Id); Assert.AreEqual(1, result.Properties.Values.Count()); Assert.AreEqual("blah1", result.Properties.Values.First().Alias); Assert.AreEqual("New1", result.Properties.Values.First().Name); Assert.AreEqual(4, result.Properties.Values.First().SortOrder); - } } @@ -300,23 +301,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Remove_Macro_Property() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); - var result = repository.Get(macro.Id); + IMacro result = repository.Get(macro.Id); result.Properties.Remove("blah1"); repository.Save(result); // Assert result = repository.Get(macro.Id); Assert.AreEqual(0, result.Properties.Values.Count()); - } } @@ -324,16 +324,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_Remove_Macro_Properties() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); var prop1 = new MacroProperty("blah1", "New1", 4, "test.editor"); var prop2 = new MacroProperty("blah2", "New2", 3, "test.editor"); - //add/remove a few to test the collection observable + // add/remove a few to test the collection observable macro.Properties.Add(prop1); macro.Properties.Add(prop2); macro.Properties.Remove(prop1); @@ -343,11 +343,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(macro); // Assert - var result = repository.Get(macro.Id); + IMacro result = repository.Get(macro.Id); Assert.AreEqual(1, result.Properties.Values.Count()); Assert.AreEqual("blah2", result.Properties.Values.Single().Alias); - } } @@ -355,26 +354,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_Property_For_Macro() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); repository.Save(macro); - //Act + // Act macro = repository.Get(1); macro.Properties["new1"].Name = "this is a new name"; repository.Save(macro); - // Assert - var result = repository.Get(1); + IMacro result = repository.Get(1); Assert.AreEqual("new1", result.Properties.Values.First().Alias); Assert.AreEqual("this is a new name", result.Properties.Values.First().Name); - } } @@ -382,32 +379,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_Macro_Property_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); repository.Save(macro); - //Act + // Act macro = repository.Get(1); macro.Properties.UpdateProperty("new1", newAlias: "newAlias"); repository.Save(macro); // Assert - var result = repository.Get(1); + IMacro result = repository.Get(1); Assert.AreEqual("newAlias", result.Properties.Values.First().Alias); } } public void CreateTestData() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); repository.Save(new Macro(ShortStringHelper, "test1", "Test1", "~/views/macropartials/test1.cshtml")); repository.Save(new Macro(ShortStringHelper, "test2", "Test2", "~/views/macropartials/test2.cshtml")); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs index f504218cec..0c70405378 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs @@ -1,4 +1,8 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; +using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Moq; @@ -10,6 +14,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; @@ -27,9 +32,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class MediaRepositoryTest : UmbracoIntegrationTest { private IMediaService MediaService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); + private ITemplateRepository TemplateRepository => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); // Makes handing IDs easier, these are set by CreateTestData @@ -38,15 +47,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Media _testFile; [SetUp] - public void SetUpTestData() - { - CreateTestData(); - } + public void SetUpTestData() => CreateTestData(); private MediaRepository CreateRepository(IScopeProvider provider, out MediaTypeRepository mediaTypeRepository, AppCaches appCaches = null) { - appCaches = appCaches ?? AppCaches.NoCache; - var scopeAccessor = (IScopeAccessor) provider; + appCaches ??= AppCaches.NoCache; + var scopeAccessor = (IScopeAccessor)provider; var globalSettings = new GlobalSettings(); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, TemplateRepository, appCaches, ShortStringHelper); var languageRepository = new LanguageRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); @@ -65,46 +71,46 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CacheActiveForIntsAndGuids() { - MediaTypeRepository mediaTypeRepository; - var realCache = new AppCaches( new ObjectCacheAppCache(), new DictionaryAppCache(), new IsolatedCaches(t => new ObjectCacheAppCache())); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out mediaTypeRepository, appCaches: realCache); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository, appCaches: realCache); - var udb = scope.Database; + IUmbracoDatabase udb = scope.Database; udb.EnableSqlCount = false; - var mediaType = MediaTypeBuilder.CreateSimpleMediaType("umbTextpage1", "Textpage"); + MediaType mediaType = MediaTypeBuilder.CreateSimpleMediaType("umbTextpage1", "Textpage"); mediaTypeRepository.Save(mediaType); - var media = MediaBuilder.CreateSimpleMedia(mediaType, "hello", -1); + Media media = MediaBuilder.CreateSimpleMedia(mediaType, "hello", -1); repository.Save(media); udb.EnableSqlCount = true; - //go get it, this should already be cached since the default repository key is the INT - var found = repository.Get(media.Id); + // go get it, this should already be cached since the default repository key is the INT + IMedia found = repository.Get(media.Id); Assert.AreEqual(0, udb.SqlCount); - //retrieve again, this should use cache + + // retrieve again, this should use cache found = repository.Get(media.Id); Assert.AreEqual(0, udb.SqlCount); - //reset counter + // reset counter udb.EnableSqlCount = false; udb.EnableSqlCount = true; - //now get by GUID, this won't be cached yet because the default repo key is not a GUID + // now get by GUID, this won't be cached yet because the default repo key is not a GUID found = repository.Get(media.Key); - var sqlCount = udb.SqlCount; + int sqlCount = udb.SqlCount; Assert.Greater(sqlCount, 0); - //retrieve again, this should use cache now + + // retrieve again, this should use cache now found = repository.Get(media.Key); Assert.AreEqual(sqlCount, udb.SqlCount); } @@ -114,26 +120,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SaveMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); - var mediaType = mediaTypeRepository.Get(1032); - var image = MediaBuilder.CreateMediaImage(mediaType, -1); + IMediaType mediaType = mediaTypeRepository.Get(1032); + Media image = MediaBuilder.CreateMediaImage(mediaType, -1); // Act mediaTypeRepository.Save(mediaType); repository.Save(image); - var fetched = repository.Get(image.Id); + IMedia fetched = repository.Get(image.Id); // Assert Assert.That(mediaType.HasIdentity, Is.True); Assert.That(image.HasIdentity, Is.True); - TestHelper.AssertPropertyValuesAreEqual(image, fetched, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(image, fetched); } } @@ -141,19 +146,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SaveMediaMultiple() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); - var mediaType = mediaTypeRepository.Get(1032); - var file = MediaBuilder.CreateMediaFile(mediaType, -1); + IMediaType mediaType = mediaTypeRepository.Get(1032); + Media file = MediaBuilder.CreateMediaFile(mediaType, -1); // Act repository.Save(file); - var image = MediaBuilder.CreateMediaImage(mediaType, -1); + Media image = MediaBuilder.CreateMediaImage(mediaType, -1); repository.Save(image); // Assert @@ -170,14 +174,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetMediaIsNotDirty() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var media = repository.Get(_testImage.Id); + IMedia media = repository.Get(_testImage.Id); bool dirty = ((ICanBeDirty)media).IsDirty(); // Assert @@ -189,18 +192,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void UpdateMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var content = repository.Get(_testFile.Id); + IMedia content = repository.Get(_testFile.Id); content.Name = "Test File Updated"; repository.Save(content); - var updatedContent = repository.Get(_testFile.Id); + IMedia updatedContent = repository.Get(_testFile.Id); // Assert Assert.That(updatedContent.Id, Is.EqualTo(content.Id)); @@ -212,18 +214,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void DeleteMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var media = repository.Get(_testFile.Id); + IMedia media = repository.Get(_testFile.Id); repository.Delete(media); - var deleted = repository.Get(_testFile.Id); - var exists = repository.Exists(_testFile.Id); + IMedia deleted = repository.Get(_testFile.Id); + bool exists = repository.Exists(_testFile.Id); // Assert Assert.That(deleted, Is.Null); @@ -235,14 +236,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var media = repository.Get(_testImage.Id); + IMedia media = repository.Get(_testImage.Id); // Assert Assert.That(media.Id, Is.EqualTo(_testImage.Id)); @@ -262,18 +262,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void QueryMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.Get(query); // Assert - Assert.That(result.Count(), Is.GreaterThanOrEqualTo(2)); //There should be two entities on level 2: File and Media + Assert.That(result.Count(), Is.GreaterThanOrEqualTo(2)); // There should be two entities on level 2: File and Media } } @@ -281,23 +280,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void QueryMedia_ContentTypeIdFilter() { // Arrange - var folderMediaType = MediaTypeService.Get(1031); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IMediaType folderMediaType = MediaTypeService.Get(1031); + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act for (int i = 0; i < 10; i++) { - var folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + Media folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); repository.Save(folder); } - - var types = new[] { 1031 }; - var query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentTypeId)); - var result = repository.Get(query); + int[] types = new[] { 1031 }; + IQuery query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentTypeId)); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(11)); @@ -312,23 +310,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // and we don't absolutely need it now, so leaving it out for now // Arrange - var folderMediaType = MediaTypeService.Get(1031); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IMediaType folderMediaType = MediaTypeService.Get(1031); + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act for (int i = 0; i < 10; i++) { - var folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + Media folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); repository.Save(folder); } - - var types = new[] { "Folder" }; - var query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentType.Alias)); - var result = repository.Get(query); + string[] types = new[] { "Folder" }; + IQuery query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentType.Alias)); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(11)); @@ -339,15 +336,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_FirstPage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 0, 1, out totalRecords, null, Ordering.By("SortOrder")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -360,16 +356,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_SecondPage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 1, 1, out totalRecords, null, Ordering.By("SortOrder")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 1, 1, out long totalRecords, null, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -382,16 +376,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_SinglePage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 0, 2, out totalRecords, null, Ordering.By("SortOrder")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 2, out long totalRecords, null, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -404,16 +396,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_DescendingOrder() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 0, 1, out totalRecords, null, Ordering.By("SortOrder", Direction.Descending)); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("SortOrder", Direction.Descending)); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -426,15 +416,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_AlternateOrder() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 0, 1, out var totalRecords, null, Ordering.By("Name")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("Name")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -447,17 +436,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_FilterMatchingSome() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filter = scope.SqlContext.Query().Where(x => x.Name.Contains("File")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filter, Ordering.By("SortOrder")); + IQuery filter = scope.SqlContext.Query().Where(x => x.Name.Contains("File")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filter, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.EqualTo(1)); @@ -470,16 +458,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_FilterMatchingAll() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out _); + MediaRepository repository = CreateRepository(provider, out _); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filter = scope.SqlContext.Query().Where(x => x.Name.Contains("Test")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filter, Ordering.By("SortOrder")); + IQuery filter = scope.SqlContext.Query().Where(x => x.Name.Contains("Test")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filter, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.EqualTo(2)); @@ -492,14 +480,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetAllMediaByIds() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var medias = repository.GetMany(_testImage.Id, _testFile.Id); + IEnumerable medias = repository.GetMany(_testImage.Id, _testFile.Id); // Assert Assert.That(medias, Is.Not.Null); @@ -512,14 +499,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetAllMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var medias = repository.GetMany(); + IEnumerable medias = repository.GetMany(); // Assert Assert.That(medias, Is.Not.Null); @@ -542,16 +528,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void ExistMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var exists = repository.Exists(_testImage.Id); - var existsToo = repository.Exists(_testImage.Id); - var doesntExists = repository.Exists(NodeDto.NodeIdSeed + 5); + bool exists = repository.Exists(_testImage.Id); + bool existsToo = repository.Exists(_testImage.Id); + bool doesntExists = repository.Exists(NodeDto.NodeIdSeed + 5); // Assert Assert.That(exists, Is.True); @@ -564,16 +549,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void CountMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act int level = 2; - var query = scope.SqlContext.Query().Where(x => x.Level == level); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == level); + int result = repository.Count(query); // Assert Assert.That(result, Is.GreaterThanOrEqualTo(2)); @@ -582,18 +566,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void CreateTestData() { - //Create and Save folder-Media -> (1051) - var folderMediaType = MediaTypeService.Get(1031); + // Create and Save folder-Media -> (1051) + IMediaType folderMediaType = MediaTypeService.Get(1031); _testFolder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); MediaService.Save(_testFolder, 0); - //Create and Save image-Media -> (1052) - var imageMediaType = MediaTypeService.Get(1032); + // Create and Save image-Media -> (1052) + IMediaType imageMediaType = MediaTypeService.Get(1032); _testImage = MediaBuilder.CreateMediaImage(imageMediaType, _testFolder.Id); MediaService.Save(_testImage, 0); - //Create and Save file-Media -> (1053) - var fileMediaType = MediaTypeService.Get(1033); + // Create and Save file-Media -> (1053) + IMediaType fileMediaType = MediaTypeService.Get(1033); _testFile = MediaBuilder.CreateMediaFile(fileMediaType, _testFolder.Id); MediaService.Save(_testFile, 0); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.cs index 77f18944c0..0626205d25 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; @@ -20,42 +24,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class MediaTypeRepositoryTest : UmbracoIntegrationTest { private IContentTypeCommonRepository CommonRepository => GetRequiredService(); + private ILanguageRepository LanguageRepository => GetRequiredService(); - private MediaTypeRepository CreateRepository(IScopeProvider provider) - { - return new MediaTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), CommonRepository, LanguageRepository, ShortStringHelper); - } - - private EntityContainerRepository CreateContainerRepository(IScopeProvider provider) - { - return new EntityContainerRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Constants.ObjectTypes.MediaTypeContainer); - - } - [Test] public void Can_Move() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); - var repository = CreateRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); var container1 = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah1" }; containerRepository.Save(container1); - var container2 = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah2", ParentId = container1.Id }; containerRepository.Save(container2); - var contentType = (IMediaType)MediaTypeBuilder.CreateVideoMediaType(); contentType.ParentId = container2.Id; repository.Save(contentType); - - //create a + // create a var contentType2 = (IMediaType)new MediaType(ShortStringHelper, contentType, "hello") { Name = "Blahasdfsadf" @@ -63,13 +54,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor contentType.ParentId = contentType.Id; repository.Save(contentType2); - - var result = repository.Move(contentType, container1).ToArray(); - + global::Umbraco.Core.Events.MoveEventInfo[] result = repository.Move(contentType, container1).ToArray(); Assert.AreEqual(2, result.Length); - //re-get + // re-get contentType = repository.Get(contentType.Id); contentType2 = repository.Get(contentType2.Id); @@ -77,23 +66,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType.Id).OriginalPath, contentType.Path); Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType2.Id).OriginalPath, contentType2.Path); } - } [Test] public void Can_Create_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); Assert.That(container.Id, Is.GreaterThan(0)); - var found = containerRepository.Get(container.Id); + EntityContainer found = containerRepository.Get(container.Id); Assert.IsNotNull(found); } } @@ -101,10 +89,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); @@ -114,8 +102,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act containerRepository.Delete(container); - - var found = containerRepository.Get(container.Id); + EntityContainer found = containerRepository.Get(container.Id); Assert.IsNull(found); } } @@ -123,21 +110,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); - var repository = CreateRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); - - var contentType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType contentType = MediaTypeBuilder.CreateVideoMediaType(); contentType.ParentId = container.Id; repository.Save(contentType); - Assert.AreEqual(container.Id, contentType.ParentId); } } @@ -145,26 +130,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); - var repository = CreateRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); - IMediaType contentType = MediaTypeBuilder.CreateVideoMediaType(); contentType.ParentId = container.Id; repository.Save(contentType); - // Act containerRepository.Delete(container); - - var found = containerRepository.Get(container.Id); + EntityContainer found = containerRepository.Get(container.Id); Assert.IsNull(found); contentType = repository.Get(contentType.Id); @@ -177,17 +159,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var contentType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType contentType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(contentType); - - var fetched = repository.Get(contentType.Id); + IMediaType fetched = repository.Get(contentType.Id); // Assert Assert.That(contentType.HasIdentity, Is.True); @@ -195,27 +176,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.Path.Contains(","), Is.True); Assert.That(contentType.SortOrder, Is.GreaterThan(0)); - TestHelper.AssertPropertyValuesAreEqual(contentType, fetched, "yyyy-MM-dd HH:mm:ss", ignoreProperties: new[] { "UpdateDate" }); + TestHelper.AssertPropertyValuesAreEqual(contentType, fetched, ignoreProperties: new[] { "UpdateDate" }); } - - } [Test] public void Can_Perform_Update_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var videoMediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType videoMediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(videoMediaType); - // Act - var mediaType = repository.Get(videoMediaType.Id); + IMediaType mediaType = repository.Get(videoMediaType.Id); mediaType.Thumbnail = "Doc2.png"; mediaType.PropertyGroups["Media"].PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "subtitle") @@ -228,8 +206,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }); repository.Save(mediaType); - - var dirty = ((MediaType) mediaType).IsDirty(); + bool dirty = ((MediaType)mediaType).IsDirty(); // Assert Assert.That(mediaType.HasIdentity, Is.True); @@ -243,21 +220,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(mediaType); - - var contentType2 = repository.Get(mediaType.Id); + IMediaType contentType2 = repository.Get(mediaType.Id); repository.Delete(contentType2); - - var exists = repository.Exists(mediaType.Id); + bool exists = repository.Exists(mediaType.Id); // Assert Assert.That(exists, Is.False); @@ -268,13 +243,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var mediaType = repository.Get(1033); //File + IMediaType mediaType = repository.Get(1033); // File // Assert Assert.That(mediaType, Is.Not.Null); @@ -287,12 +262,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_Guid_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var mediaType = repository.Get(1033); //File + IMediaType mediaType = repository.Get(1033); // File // Act mediaType = repository.Get(mediaType.Key); @@ -308,13 +283,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var mediaTypes = repository.GetMany(); + IEnumerable mediaTypes = repository.GetMany(); int count = scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType", @@ -330,16 +305,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Guid_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); + Guid[] allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); // Act - - var mediaTypes = ((IReadRepository)repository).GetMany(allGuidIds); + IEnumerable mediaTypes = ((IReadRepository)repository).GetMany(allGuidIds); int count = scope.Database.ExecuteScalar( @@ -356,13 +330,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(1032); //Image + bool exists = repository.Exists(1032); // Image // Assert Assert.That(exists, Is.True); @@ -373,22 +347,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_MediaType_With_PropertyType_Removed() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(mediaType); - // Act - var mediaTypeV2 = repository.Get(mediaType.Id); + IMediaType mediaTypeV2 = repository.Get(mediaType.Id); mediaTypeV2.PropertyGroups["Media"].PropertyTypes.Remove("title"); repository.Save(mediaTypeV2); - - var mediaTypeV3 = repository.Get(mediaType.Id); + IMediaType mediaTypeV3 = repository.Get(mediaType.Id); // Assert Assert.That(mediaTypeV3.PropertyTypes.Any(x => x.Alias == "title"), Is.False); @@ -401,17 +373,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_Video_MediaType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(mediaType); - // Act - var contentType = repository.Get(mediaType.Id); + IMediaType contentType = repository.Get(mediaType.Id); // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(2)); @@ -423,18 +394,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_File_MediaType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var contentType = repository.Get(1033); //File + IMediaType contentType = repository.Get(1033); // File // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentType.PropertyGroups.Count(), Is.EqualTo(1)); } } + + private MediaTypeRepository CreateRepository(IScopeProvider provider) => + new MediaTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), CommonRepository, LanguageRepository, ShortStringHelper); + + private EntityContainerRepository CreateContainerRepository(IScopeProvider provider) => + new EntityContainerRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Constants.ObjectTypes.MediaTypeContainer); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.cs index 7b26ccd500..57518eb371 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; @@ -29,32 +33,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class MemberRepositoryTest : UmbracoIntegrationTest { private IPasswordHasher PasswordHasher => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IMemberTypeRepository MemberTypeRepository => GetRequiredService(); + private IMemberGroupRepository MemberGroupRepository => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); private MemberRepository CreateRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; - var tagRepo = GetRequiredService(); - var relationTypeRepository = GetRequiredService(); - var relationRepository = GetRequiredService(); + var accessor = (IScopeAccessor)provider; + ITagRepository tagRepo = GetRequiredService(); + IRelationTypeRepository relationTypeRepository = GetRequiredService(); + IRelationRepository relationRepository = GetRequiredService(); var propertyEditors = new Lazy(() => new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty()))); var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty()); - var repository = new MemberRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), MemberTypeRepository, MemberGroupRepository, tagRepo, Mock.Of(), relationRepository, relationTypeRepository, PasswordHasher, propertyEditors, dataValueReferences, DataTypeService, JsonSerializer); - return repository; + return new MemberRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), MemberTypeRepository, MemberGroupRepository, tagRepo, Mock.Of(), relationRepository, relationTypeRepository, PasswordHasher, propertyEditors, dataValueReferences, DataTypeService, JsonSerializer); } [Test] public void GetMember() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var member = CreateTestMember(); + IMember member = CreateTestMember(); member = repository.Get(member.Id); @@ -66,16 +73,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetMembers() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var type = CreateTestMemberType(); - var m1 = CreateTestMember(type, "Test 1", "test1@test.com", "pass1", "test1"); - var m2 = CreateTestMember(type, "Test 2", "test2@test.com", "pass2", "test2"); + IMemberType type = CreateTestMemberType(); + IMember m1 = CreateTestMember(type, "Test 1", "test1@test.com", "pass1", "test1"); + IMember m2 = CreateTestMember(type, "Test 2", "test2@test.com", "pass2", "test2"); - var members = repository.GetMany(m1.Id, m2.Id); + IEnumerable members = repository.GetMany(m1.Id, m2.Id); Assert.That(members, Is.Not.Null); Assert.That(members.Count(), Is.EqualTo(2)); @@ -87,18 +94,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetAllMembers() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var type = CreateTestMemberType(); - for (var i = 0; i < 5; i++) + IMemberType type = CreateTestMemberType(); + for (int i = 0; i < 5; i++) { CreateTestMember(type, "Test " + i, "test" + i + "@test.com", "pass" + i, "test" + i); } - var members = repository.GetMany(); + IEnumerable members = repository.GetMany(); Assert.That(members, Is.Not.Null); Assert.That(members.Any(x => x == null), Is.False); @@ -111,17 +118,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void QueryMember() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); var key = Guid.NewGuid(); - var member = CreateTestMember(key: key); + IMember member = CreateTestMember(key: key); // Act - var query = scope.SqlContext.Query().Where(x => x.Key == key); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Key == key); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.EqualTo(1)); @@ -132,14 +139,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void SaveMember() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var member = CreateTestMember(); + IMember member = CreateTestMember(); - var sut = repository.Get(member.Id); + IMember sut = repository.Get(member.Id); Assert.That(sut, Is.Not.Null); Assert.That(sut.HasIdentity, Is.True); @@ -148,33 +155,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(sut.RawPasswordValue, Is.EqualTo("123")); Assert.That(sut.Username, Is.EqualTo("hefty")); - TestHelper.AssertPropertyValuesAreEqual(sut, member, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(sut, member); } } [Test] public void MemberHasBuiltinProperties() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - var member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); + Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); - var sut = repository.Get(member.Id); + IMember sut = repository.Get(member.Id); Assert.That(memberType.CompositionPropertyGroups.Count(), Is.EqualTo(2)); Assert.That(memberType.CompositionPropertyTypes.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); Assert.That(sut.Properties.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); - var grp = memberType.CompositionPropertyGroups.FirstOrDefault(x => x.Name == Constants.Conventions.Member.StandardPropertiesGroupName); + PropertyGroup grp = memberType.CompositionPropertyGroups.FirstOrDefault(x => x.Name == Constants.Conventions.Member.StandardPropertiesGroupName); Assert.IsNotNull(grp); - var aliases = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Select(x => x.Key).ToArray(); - foreach (var p in memberType.CompositionPropertyTypes.Where(x => aliases.Contains(x.Alias))) + string[] aliases = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Select(x => x.Key).ToArray(); + foreach (IPropertyType p in memberType.CompositionPropertyTypes.Where(x => aliases.Contains(x.Alias))) { Assert.AreEqual(grp.Id, p.PropertyGroupId.Value); } @@ -185,21 +192,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SavingPreservesPassword() { IMember sut; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - - var member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); + Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); - sut = repository.Get(member.Id); - //when the password is null it will not overwrite what is already there. + + // When the password is null it will not overwrite what is already there. sut.RawPasswordValue = null; repository.Save(sut); @@ -213,19 +219,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SavingUpdatesNameAndEmail() { IMember sut; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - - var member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); + Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); - sut = repository.Get(member.Id); sut.Username = "This is new"; sut.Email = "thisisnew@hello.com"; @@ -241,16 +245,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void QueryMember_WithSubQuery() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - var query = provider.SqlContext.Query().Where(x => - ((Member) x).LongStringPropertyValue.Contains("1095") && - ((Member) x).PropertyTypeAlias == "headshot"); + IQuery query = provider.SqlContext.Query().Where(x => + ((Member)x).LongStringPropertyValue.Contains("1095") && + ((Member)x).PropertyTypeAlias == "headshot"); - var sqlSubquery = GetSubquery(); + Sql sqlSubquery = GetSubquery(); var translator = new SqlTranslator(sqlSubquery, query); - var subquery = translator.Translate(); - var sql = GetBaseQuery(false) + Sql subquery = translator.Translate(); + Sql sql = GetBaseQuery(false) .Append("WHERE umbracoNode.id IN (" + subquery.SQL + ")", subquery.Arguments) .OrderByDescending(x => x.VersionDate) .OrderBy(x => x.SortOrder); @@ -261,19 +265,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IMember CreateTestMember(IMemberType memberType = null, string name = null, string email = null, string password = null, string username = null, Guid? key = null) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); if (memberType == null) { memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - } - var member = MemberBuilder.CreateSimpleMember(memberType, name ?? "Johnny Hefty", email ?? "johnny@example.com", password ?? "123", username ?? "hefty", key); + Member member = MemberBuilder.CreateSimpleMember(memberType, name ?? "Johnny Hefty", email ?? "johnny@example.com", password ?? "123", username ?? "hefty", key); repository.Save(member); scope.Complete(); @@ -283,12 +286,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IMemberType CreateTestMemberType(string alias = null) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(alias); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(alias); MemberTypeRepository.Save(memberType); scope.Complete(); return memberType; @@ -297,10 +300,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Sql GetBaseQuery(bool isCount) { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; if (isCount) { - var sqlCount = provider.SqlContext.Sql() + Sql sqlCount = provider.SqlContext.Sql() .SelectCount() .From() .InnerJoin().On(left => left.NodeId, right => right.NodeId) @@ -311,17 +314,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor return sqlCount; } - var sql = provider.SqlContext.Sql(); - sql.Select("umbracoNode.*", $"{Constants.DatabaseSchema.Tables.Content}.contentTypeId", "cmsContentType.alias AS ContentTypeAlias", $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionId", - $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionDate", "cmsMember.Email", - "cmsMember.LoginName", "cmsMember.Password", - Constants.DatabaseSchema.Tables.PropertyData + ".id AS PropertyDataId", Constants.DatabaseSchema.Tables.PropertyData + ".propertytypeid", - Constants.DatabaseSchema.Tables.PropertyData + ".dateValue", Constants.DatabaseSchema.Tables.PropertyData + ".intValue", - Constants.DatabaseSchema.Tables.PropertyData + ".textValue", Constants.DatabaseSchema.Tables.PropertyData + ".varcharValue", - "cmsPropertyType.id", "cmsPropertyType.Alias", "cmsPropertyType.Description", - "cmsPropertyType.Name", "cmsPropertyType.mandatory", "cmsPropertyType.validationRegExp", - "cmsPropertyType.sortOrder AS PropertyTypeSortOrder", "cmsPropertyType.propertyTypeGroupId", - "cmsPropertyType.dataTypeId", "cmsDataType.propertyEditorAlias", "cmsDataType.dbType") + Sql sql = provider.SqlContext.Sql(); + sql.Select( + "umbracoNode.*", + $"{Constants.DatabaseSchema.Tables.Content}.contentTypeId", + "cmsContentType.alias AS ContentTypeAlias", + $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionId", + $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionDate", + "cmsMember.Email", + "cmsMember.LoginName", + "cmsMember.Password", + Constants.DatabaseSchema.Tables.PropertyData + ".id AS PropertyDataId", + Constants.DatabaseSchema.Tables.PropertyData + ".propertytypeid", + Constants.DatabaseSchema.Tables.PropertyData + ".dateValue", + Constants.DatabaseSchema.Tables.PropertyData + ".intValue", + Constants.DatabaseSchema.Tables.PropertyData + ".textValue", + Constants.DatabaseSchema.Tables.PropertyData + ".varcharValue", + "cmsPropertyType.id", + "cmsPropertyType.Alias", + "cmsPropertyType.Description", + "cmsPropertyType.Name", + "cmsPropertyType.mandatory", + "cmsPropertyType.validationRegExp", + "cmsPropertyType.sortOrder AS PropertyTypeSortOrder", + "cmsPropertyType.propertyTypeGroupId", + "cmsPropertyType.dataTypeId", + "cmsDataType.propertyEditorAlias", + "cmsDataType.dbType") .From() .InnerJoin().On(left => left.NodeId, right => right.NodeId) .InnerJoin().On(left => left.NodeId, right => right.ContentTypeId) @@ -337,8 +356,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Sql GetSubquery() { - var provider = ScopeProvider; - var sql = provider.SqlContext.Sql(); + IScopeProvider provider = ScopeProvider; + Sql sql = provider.SqlContext.Sql(); sql.Select("umbracoNode.id") .From() .InnerJoin().On(left => left.NodeId, right => right.NodeId) diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs index f2bf72a74d..d8f550f1bb 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; -using Moq; using Microsoft.Extensions.Logging; +using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; @@ -22,25 +26,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { private MemberTypeRepository CreateRepository(IScopeProvider provider) { - var commonRepository = GetRequiredService(); - var languageRepository = GetRequiredService(); - return new MemberTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of>(), commonRepository, languageRepository, ShortStringHelper); + IContentTypeCommonRepository commonRepository = GetRequiredService(); + ILanguageRepository languageRepository = GetRequiredService(); + return new MemberTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, Mock.Of>(), commonRepository, languageRepository, ShortStringHelper); } [Test] public void Can_Persist_Member_Type() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType = (IMemberType) MemberTypeBuilder.CreateSimpleMemberType(); + var memberType = (IMemberType)MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); - var sut = repository.Get(memberType.Id); + IMemberType sut = repository.Get(memberType.Id); - var standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); Assert.That(sut, Is.Not.Null); Assert.That(sut.PropertyGroups.Count, Is.EqualTo(2)); @@ -49,48 +53,46 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(sut.PropertyGroups.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); Assert.That(sut.PropertyTypes.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); - TestHelper.AssertPropertyValuesAreEqual(sut, memberType, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(sut, memberType); } } [Test] public void Can_Persist_Member_Type_Same_Property_Keys() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); var memberType = (IMemberType)MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); scope.Complete(); - var propertyKeys = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); - var groupKeys = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] propertyKeys = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] groupKeys = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); memberType = repository.Get(memberType.Id); - var propertyKeys2 = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); - var groupKeys2 = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] propertyKeys2 = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] groupKeys2 = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); Assert.IsTrue(propertyKeys.SequenceEqual(propertyKeys2)); Assert.IsTrue(groupKeys.SequenceEqual(groupKeys2)); - } } [Test] public void Cannot_Persist_Member_Type_Without_Alias() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); memberType.Alias = null; - Assert.Throws(() => repository.Save(memberType)); } } @@ -98,24 +100,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All_Member_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IEnumerable result = repository.GetMany(); - var result = repository.GetMany(); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.AreEqual(3, result.Count()); } } @@ -123,24 +123,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All_Member_Types_By_Guid_Ids() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IEnumerable result = ((IReadRepository)repository).GetMany(memberType1.Key, memberType2.Key); - var result = ((IReadRepository)repository).GetMany(memberType1.Key, memberType2.Key); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.AreEqual(2, result.Count()); } } @@ -148,53 +146,49 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Member_Types_By_Guid_Id() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IMemberType result = repository.Get(memberType1.Key); - var result = repository.Get(memberType1.Key); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.IsNotNull(result); Assert.AreEqual(memberType1.Key, result.Key); } } - //NOTE: This tests for left join logic (rev 7b14e8eacc65f82d4f184ef46c23340c09569052) + // NOTE: This tests for left join logic (rev 7b14e8eacc65f82d4f184ef46c23340c09569052) [Test] public void Can_Get_All_Members_When_No_Properties_Assigned() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); memberType1.PropertyTypeCollection.Clear(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.PropertyTypeCollection.Clear(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IEnumerable result = repository.GetMany(); - var result = repository.GetMany(); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.AreEqual(3, result.Count()); } } @@ -202,10 +196,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Member_Type_By_Id() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); @@ -218,10 +212,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Member_Type_By_Guid_Id() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); @@ -235,12 +229,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Bug_Changing_Built_In_Member_Type_Property_Type_Aliases_Results_In_Exception() { - var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType("mtype"); @@ -255,10 +249,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); - foreach (var stub in stubs) + foreach (KeyValuePair stub in stubs) { - var prop = memberType.PropertyTypes.First(x => x.Alias == stub.Key); - prop.Alias = prop.Alias + "__0000"; + IPropertyType prop = memberType.PropertyTypes.First(x => x.Alias == stub.Key); + prop.Alias += "__0000"; } // saving *existing* member type does *not* ensure stub properties @@ -273,19 +267,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.IsNotNull(memberType); Assert.AreEqual(2, memberType.PropertyGroups.Count); - Assert.AreEqual(3 + stubs.Count * 2, memberType.PropertyTypes.Count()); + Assert.AreEqual(3 + (stubs.Count * 2), memberType.PropertyTypes.Count()); } } [Test] public void Built_In_Member_Type_Properties_Are_Automatically_Added_When_Creating() { - var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); @@ -311,12 +305,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Built_In_Member_Type_Properties_Missing_Are_Automatically_Added_When_Creating() { - var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); @@ -342,24 +336,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - //This is to show that new properties are created for each member type - there was a bug before + // This is to show that new properties are created for each member type - there was a bug before // that was reusing the same properties with the same Ids between member types [Test] public void Built_In_Member_Type_Properties_Are_Not_Reused_For_Different_Member_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); IMemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType("test2"); repository.Save(memberType1); repository.Save(memberType2); - - var m1Ids = memberType1.PropertyTypes.Select(x => x.Id).ToArray(); - var m2Ids = memberType2.PropertyTypes.Select(x => x.Id).ToArray(); + int[] m1Ids = memberType1.PropertyTypes.Select(x => x.Id).ToArray(); + int[] m2Ids = memberType2.PropertyTypes.Select(x => x.Id).ToArray(); Assert.IsFalse(m1Ids.Any(m2Ids.Contains)); } @@ -369,21 +362,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Delete_MemberType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); // Act IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); - - var contentType2 = repository.Get(memberType.Id); + IMemberType contentType2 = repository.Get(memberType.Id); repository.Delete(contentType2); - - var exists = repository.Exists(memberType.Id); + bool exists = repository.Exists(memberType.Id); // Assert Assert.That(exists, Is.False); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs index f784390ced..c15a858218 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs @@ -1,9 +1,14 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.Dtos; @@ -21,10 +26,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CreateNotification() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var node = new NodeDto // create bogus item so we can add a notification { @@ -39,11 +44,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor UniqueId = Guid.NewGuid(), UserId = Constants.Security.SuperUserId }; - var result = scope.Database.Insert(node); - var entity = Mock.Of(e => e.Id == node.NodeId); - var user = Mock.Of(e => e.Id == node.UserId); + object result = scope.Database.Insert(node); + IEntity entity = Mock.Of(e => e.Id == node.NodeId); + IUser user = Mock.Of(e => e.Id == node.UserId); - var notification = repo.CreateNotification(user, entity, "A"); + Notification notification = repo.CreateNotification(user, entity, "A"); Assert.AreEqual("A", notification.Action); Assert.AreEqual(node.NodeId, notification.EntityId); @@ -55,26 +60,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetUserNotifications() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var userDto = new UserDto { Email = "test", Login = "test", Password = "test", UserName = "test", UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + IUser userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var node = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1," + i, SortOrder = 1, Text = "hello" + i, Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; - var result = scope.Database.Insert(node); - var entity = Mock.Of(e => e.Id == node.NodeId); - var notification = repo.CreateNotification((i%2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); + object result = scope.Database.Insert(node); + IEntity entity = Mock.Of(e => e.Id == node.NodeId); + Notification notification = repo.CreateNotification((i % 2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); } - var notifications = repo.GetUserNotifications(userAdmin); + IEnumerable notifications = repo.GetUserNotifications(userAdmin); Assert.AreEqual(5, notifications.Count()); } @@ -83,27 +88,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetEntityNotifications() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var node1 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,1", SortOrder = 1, Text = "hello1", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node1); - var entity1 = Mock.Of(e => e.Id == node1.NodeId); + IEntity entity1 = Mock.Of(e => e.Id == node1.NodeId); var node2 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,2", SortOrder = 1, Text = "hello2", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node2); - var entity2 = Mock.Of(e => e.Id == node2.NodeId); + IEntity entity2 = Mock.Of(e => e.Id == node2.NodeId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var userDto = new UserDto { Email = "test" + i, Login = "test" + i, Password = "test", UserName = "test" + i, UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var notification = repo.CreateNotification(userNew, (i%2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + Notification notification = repo.CreateNotification(userNew, (i % 2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); } - var notifications = repo.GetEntityNotifications(entity1); + IEnumerable notifications = repo.GetEntityNotifications(entity1); Assert.AreEqual(5, notifications.Count()); } @@ -112,27 +117,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Delete_By_Entity() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var node1 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,1", SortOrder = 1, Text = "hello1", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node1); - var entity1 = Mock.Of(e => e.Id == node1.NodeId); + IEntity entity1 = Mock.Of(e => e.Id == node1.NodeId); var node2 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,2", SortOrder = 1, Text = "hello2", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node2); - var entity2 = Mock.Of(e => e.Id == node2.NodeId); + IEntity entity2 = Mock.Of(e => e.Id == node2.NodeId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var userDto = new UserDto { Email = "test" + i, Login = "test" + i, Password = "test", UserName = "test" + i, UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var notification = repo.CreateNotification(userNew, (i%2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + Notification notification = repo.CreateNotification(userNew, (i % 2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); } - var delCount = repo.DeleteNotifications(entity1); + int delCount = repo.DeleteNotifications(entity1); Assert.AreEqual(5, delCount); } @@ -141,26 +146,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Delete_By_User() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var userDto = new UserDto { Email = "test", Login = "test", Password = "test", UserName = "test", UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + IUser userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var node = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1," + i, SortOrder = 1, Text = "hello" + i, Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; - var result = scope.Database.Insert(node); - var entity = Mock.Of(e => e.Id == node.NodeId); - var notification = repo.CreateNotification((i%2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); + object result = scope.Database.Insert(node); + IEntity entity = Mock.Of(e => e.Id == node.NodeId); + Notification notification = repo.CreateNotification((i % 2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); } - var delCount = repo.DeleteNotifications(userAdmin); + int delCount = repo.DeleteNotifications(userAdmin); Assert.AreEqual(5, delCount); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs index ffda46ed0d..d4a90e6fcb 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs @@ -1,15 +1,20 @@ -using Microsoft.Extensions.Logging; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Tests.Testing; -using System; -using System.IO; -using Umbraco.Core.Hosting; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; +using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories { @@ -18,19 +23,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class PartialViewRepositoryTests : UmbracoIntegrationTest { private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IFileSystem _fileSystem; [SetUp] - public void SetUp() - { + public void SetUp() => _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory.CreateLogger(), HostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.PartialViews), HostingEnvironment.ToAbsolute(Constants.SystemDirectories.PartialViews)); - } [TearDown] public void TearDownFiles() { - //Delete all files - Purge((PhysicalFileSystem)_fileSystem, ""); + // Delete all files + Purge((PhysicalFileSystem)_fileSystem, string.Empty); _fileSystem = null; } @@ -38,12 +42,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void PathTests() { // unless noted otherwise, no changes / 7.2.8 - - var fileSystems = Mock.Of(); + IFileSystems fileSystems = Mock.Of(); Mock.Get(fileSystems).Setup(x => x.PartialViewsFileSystem).Returns(_fileSystem); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var repository = new PartialViewRepository(fileSystems, IOHelper); @@ -59,7 +62,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("path-2\\test-path-2.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); // fixed in 7.3 - 7.2.8 does not update the path Assert.AreEqual("/Views/Partials/path-2/test-path-2.cshtml", partialView.VirtualPath); - partialView = (PartialView) repository.Get("path-2/test-path-2.cshtml"); + partialView = (PartialView)repository.Get("path-2/test-path-2.cshtml"); Assert.IsNotNull(partialView); Assert.AreEqual("path-2\\test-path-2.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-2.cshtml", partialView.VirtualPath); @@ -70,47 +73,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("path-2\\test-path-3.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-3.cshtml", partialView.VirtualPath); - partialView = (PartialView) repository.Get("path-2/test-path-3.cshtml"); + partialView = (PartialView)repository.Get("path-2/test-path-3.cshtml"); Assert.IsNotNull(partialView); Assert.AreEqual("path-2\\test-path-3.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-3.cshtml", partialView.VirtualPath); - partialView = (PartialView) repository.Get("path-2\\test-path-3.cshtml"); + partialView = (PartialView)repository.Get("path-2\\test-path-3.cshtml"); Assert.IsNotNull(partialView); Assert.AreEqual("path-2\\test-path-3.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-3.cshtml", partialView.VirtualPath); partialView = new PartialView(PartialViewType.PartialView, "\\test-path-4.cshtml") { Content = "// partialView" }; Assert.Throws(() => // fixed in 7.3 - 7.2.8 used to strip the \ - { - repository.Save(partialView); - }); + repository.Save(partialView)); - partialView = (PartialView) repository.Get("missing.cshtml"); + partialView = (PartialView)repository.Get("missing.cshtml"); Assert.IsNull(partialView); // fixed in 7.3 - 7.2.8 used to... - Assert.Throws(() => - { - partialView = (PartialView) repository.Get("\\test-path-4.cshtml"); // outside the filesystem, does not exist - }); - Assert.Throws(() => - { - partialView = (PartialView) repository.Get("../../packages.config"); // outside the filesystem, exists - }); + Assert.Throws(() => partialView = (PartialView)repository.Get("\\test-path-4.cshtml")); + Assert.Throws(() => partialView = (PartialView)repository.Get("../../packages.config")); } } - private void Purge(PhysicalFileSystem fs, string path) { - var files = fs.GetFiles(path, "*.cshtml"); - foreach (var file in files) + IEnumerable files = fs.GetFiles(path, "*.cshtml"); + foreach (string file in files) { fs.DeleteFile(file); } - var dirs = fs.GetDirectories(path); - foreach (var dir in dirs) + + IEnumerable dirs = fs.GetDirectories(path); + foreach (string dir in dirs) { Purge(fs, dir); fs.DeleteDirectory(dir); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs index a02889c6ae..20c3f98f45 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs @@ -1,21 +1,18 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; -using Umbraco.Core.Configuration.Models; -using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; -using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Content = Umbraco.Core.Models.Content; @@ -26,32 +23,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class PublicAccessRepositoryTest : UmbracoIntegrationTest { private IContentTypeRepository ContentTypeRepository => GetRequiredService(); - private DocumentRepository DocumentRepository => (DocumentRepository) GetRequiredService(); + + private DocumentRepository DocumentRepository => (DocumentRepository)GetRequiredService(); [Test] public void Can_Delete() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + }, + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - repo.Delete(entry); - entry = repo.Get(entry.Key); Assert.IsNull(entry); } @@ -60,26 +57,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Add() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + }, + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - var found = repo.GetMany().ToArray(); + PublicAccessEntry[] found = repo.GetMany().ToArray(); Assert.AreEqual(1, found.Length); Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId); @@ -100,31 +97,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Add2() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - new PublicAccessRule - { - RuleValue = "test2", - RuleType = "RoleName2" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + }, + new PublicAccessRule + { + RuleValue = "test2", + RuleType = "RoleName2" + }, + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - var found = repo.GetMany().ToArray(); + PublicAccessEntry[] found = repo.GetMany().ToArray(); Assert.AreEqual(1, found.Length); Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId); @@ -143,34 +140,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Update() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + } + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - //re-get + // re-get entry = repo.Get(entry.Key); entry.Rules.First().RuleValue = "blah"; entry.Rules.First().RuleType = "asdf"; repo.Save(entry); - - - //re-get + // re-get entry = repo.Get(entry.Key); Assert.AreEqual("blah", entry.Rules.First().RuleValue); @@ -181,25 +176,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_By_Id() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + } + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - //re-get + // re-get entry = repo.Get(entry.Key); Assert.IsNotNull(entry); @@ -209,12 +204,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All() { - var content = CreateTestData(30).ToArray(); + IContent[] content = CreateTestData(30).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); var allEntries = new List(); for (int i = 0; i < 10; i++) @@ -228,91 +223,91 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor RuleType = "RoleName" + j }); } + var entry1 = new PublicAccessEntry(content[i], content[i + 1], content[i + 2], rules); repo.Save(entry1); allEntries.Add(entry1); } - //now remove a few rules from a few of the items and then add some more, this will put things 'out of order' which - //we need to verify our sort order is working for the relator + // now remove a few rules from a few of the items and then add some more, this will put things 'out of order' which + // we need to verify our sort order is working for the relator // FIXME: no "relator" in v8?! for (int i = 0; i < allEntries.Count; i++) { - //all the even ones + // all the even ones if (i % 2 == 0) { - var rules = allEntries[i].Rules.ToArray(); + PublicAccessRule[] rules = allEntries[i].Rules.ToArray(); for (int j = 0; j < rules.Length; j++) { - //all the even ones + // all the even ones if (j % 2 == 0) { allEntries[i].RemoveRule(rules[j]); } } + allEntries[i].AddRule("newrule" + i, "newrule" + i); repo.Save(allEntries[i]); - } } - var found = repo.GetMany().ToArray(); + PublicAccessEntry[] found = repo.GetMany().ToArray(); Assert.AreEqual(10, found.Length); - foreach (var publicAccessEntry in found) + foreach (PublicAccessEntry publicAccessEntry in found) { - var matched = allEntries.First(x => x.Key == publicAccessEntry.Key); + PublicAccessEntry matched = allEntries.First(x => x.Key == publicAccessEntry.Key); Assert.AreEqual(matched.Rules.Count(), publicAccessEntry.Rules.Count()); } } } - [Test] public void Get_All_With_Id() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[] + PublicAccessRule[] rules1 = new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, - }); + }; + var entry1 = new PublicAccessEntry(content[0], content[1], content[2], rules1); repo.Save(entry1); - var entry2 = new PublicAccessEntry(content[1], content[0], content[2], new[] + PublicAccessRule[] rules2 = new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, - }); + }; + var entry2 = new PublicAccessEntry(content[1], content[0], content[2], rules2); repo.Save(entry2); - - - var found = repo.GetMany(entry1.Key).ToArray(); + PublicAccessEntry[] found = repo.GetMany(entry1.Key).ToArray(); Assert.AreEqual(1, found.Count()); } } private IEnumerable CreateTestData(int count) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var ct = ContentTypeBuilder.CreateBasicContentType("testing"); + ContentType ct = ContentTypeBuilder.CreateBasicContentType("testing"); ContentTypeRepository.Save(ct); var result = new List(); @@ -322,6 +317,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor DocumentRepository.Save(c); result.Add(c); } + scope.Complete(); return result; diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.cs index 54d83172f0..cc0624a2b8 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; @@ -18,19 +22,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class RedirectUrlRepositoryTests : UmbracoIntegrationTest { [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); [Test] public void CanSaveAndGet() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -42,10 +43,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var rurl = repo.GetMostRecentUrl("blah"); + IRedirectUrlRepository repo = CreateRepository(provider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); @@ -56,10 +57,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSaveAndGetWithCulture() { - var culture = "en"; - using (var scope = ScopeProvider.CreateScope()) + string culture = "en"; + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -72,10 +73,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); - var rurl = repo.GetMostRecentUrl("blah"); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); @@ -84,17 +85,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void CanSaveAndGetMostRecent() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; Assert.AreNotEqual(_textpage.Id, _otherpage.Id); - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -109,7 +109,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // and... can that happen in real life? // we don't really *care* about the IX, only supposed to make things faster... // BUT in realife we AddOrUpdate in a trx so it should be safe, always - rurl = new RedirectUrl { ContentKey = _otherpage.Key, @@ -122,10 +121,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var rurl = repo.GetMostRecentUrl("blah"); + IRedirectUrlRepository repo = CreateRepository(provider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); @@ -136,13 +135,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSaveAndGetMostRecentForCulture() { - var cultureA = "en"; - var cultureB = "de"; + string cultureA = "en"; + string cultureB = "de"; Assert.AreNotEqual(_textpage.Id, _otherpage.Id); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -158,7 +157,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // and... can that happen in real life? // we don't really *care* about the IX, only supposed to make things faster... // BUT in realife we AddOrUpdate in a trx so it should be safe, always - rurl = new RedirectUrl { ContentKey = _otherpage.Key, @@ -172,10 +170,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); - var rurl = repo.GetMostRecentUrl("blah", cultureA); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah", cultureA); scope.Complete(); Assert.IsNotNull(rurl); @@ -184,15 +182,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void CanSaveAndGetByContent() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -204,7 +201,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); // FIXME: goes too fast and bam, errors, first is blah - rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -217,10 +213,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var rurls = repo.GetContentUrls(_textpage.Key).ToArray(); + IRedirectUrlRepository repo = CreateRepository(provider); + IRedirectUrl[] rurls = repo.GetContentUrls(_textpage.Key).ToArray(); scope.Complete(); Assert.AreEqual(2, rurls.Length); @@ -232,11 +228,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSaveAndDelete() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -258,57 +254,59 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); repo.DeleteContentUrls(_textpage.Key); scope.Complete(); - var rurls = repo.GetContentUrls(_textpage.Key); + IEnumerable rurls = repo.GetContentUrls(_textpage.Key); Assert.AreEqual(0, rurls.Count()); } } - private IRedirectUrlRepository CreateRepository(IScopeProvider provider) - { - return new RedirectUrlRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); - } + private IRedirectUrlRepository CreateRepository(IScopeProvider provider) => + new RedirectUrlRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - private IContent _textpage, _subpage, _otherpage, _trashed; + private IContent _textpage; + private IContent _subpage; + private IContent _otherpage; + private IContent _trashed; public void CreateTestData() { - var fileService = GetRequiredService(); - var template = TemplateBuilder.CreateTextPageTemplate(); + IFileService fileService = GetRequiredService(); + Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); // else, FK violation on contentType! - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); - //Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); + + // Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); contentType.Key = Guid.NewGuid(); contentTypeService.Save(contentType); - //Create and Save Content "Homepage" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 1) + // Create and Save Content "Homepage" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 1) _textpage = ContentBuilder.CreateSimpleContent(contentType); _textpage.Key = Guid.NewGuid(); contentService.Save(_textpage); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 2) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 2) _subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", _textpage.Id); _subpage.Key = Guid.NewGuid(); contentService.Save(_subpage); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 3) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 3) _otherpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 2", _textpage.Id); _otherpage.Key = Guid.NewGuid(); contentService.Save(_otherpage); - //Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 4) + // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 4) _trashed = ContentBuilder.CreateSimpleContent(contentType, "Text Page Deleted", -20); _trashed.Key = Guid.NewGuid(); - ((Content) _trashed).Trashed = true; + ((Content)_trashed).Trashed = true; contentService.Save(_trashed); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs index b73af3fdfc..cccae431a7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; @@ -8,6 +11,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; @@ -48,10 +52,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IFileService FileService => GetRequiredService(); [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); private RelationRepository CreateRepository(IScopeProvider provider, out RelationTypeRepository relationTypeRepository) { @@ -72,7 +73,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var relation = new Relation(_textpage.Id, _subpage.Id, relationType); repository.Save(relation); - // Assert Assert.That(relation, Is.Not.Null); Assert.That(relation.HasIdentity, Is.True); @@ -92,7 +92,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor relation.Comment = "This relation has been updated"; repository.Save(relation); - IRelation relationUpdated = repository.Get(1); // Assert @@ -114,8 +113,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor IRelation relation = repository.Get(2); repository.Delete(relation); - - var exists = repository.Exists(2); + bool exists = repository.Exists(2); // Assert Assert.That(exists, Is.False); @@ -187,10 +185,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (IScope scope = ScopeProvider.CreateScope()) { - RelationRepository repository = CreateRepository(ScopeProvider, out var relationTypeRepository); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository relationTypeRepository); // Get parent entities for child id - var parents = repository.GetPagedParentEntitiesByChildId(createdMedia[0].Id, 0, 11, out var totalRecords).ToList(); + var parents = repository.GetPagedParentEntitiesByChildId(createdMedia[0].Id, 0, 11, out long totalRecords).ToList(); Assert.AreEqual(6, totalRecords); Assert.AreEqual(6, parents.Count); @@ -232,10 +230,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (IScope scope = ScopeProvider.CreateScope()) { - RelationRepository repository = CreateRepository(ScopeProvider, out var relationTypeRepository); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository relationTypeRepository); // Get parent entities for child id - var parents = repository.GetPagedParentEntitiesByChildId(media.Id, 0, 10, out var totalRecords).ToList(); + var parents = repository.GetPagedParentEntitiesByChildId(media.Id, 0, 10, out long totalRecords).ToList(); Assert.AreEqual(1, totalRecords); Assert.AreEqual(1, parents.Count); @@ -249,14 +247,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Child_Entities_By_Parent_Id() { - CreateTestDataForPagingTests(out var createdContent, out var createdMembers, out _); + CreateTestDataForPagingTests(out List createdContent, out List createdMembers, out _); using (IScope scope = ScopeProvider.CreateScope()) { RelationRepository repository = CreateRepository(ScopeProvider, out _); // Get parent entities for child id - var parents = repository.GetPagedChildEntitiesByParentId(createdContent[0].Id, 0, 6, out var totalRecords).ToList(); + var parents = repository.GetPagedChildEntitiesByParentId(createdContent[0].Id, 0, 6, out long totalRecords).ToList(); Assert.AreEqual(3, totalRecords); Assert.AreEqual(3, parents.Count); @@ -293,7 +291,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor ContentTypeService.Save(contentType); for (int i = 0; i < 3; i++) { - var c1 = ContentBuilder.CreateBasicContent(contentType); + Content c1 = ContentBuilder.CreateBasicContent(contentType); ContentService.Save(c1); createdContent.Add(c1); } @@ -340,13 +338,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_RelationRepository() { // Arrange - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); // Act - var exists = repository.Exists(2); - var doesntExist = repository.Exists(5); + bool exists = repository.Exists(2); + bool doesntExist = repository.Exists(5); // Assert Assert.That(exists, Is.True); @@ -358,12 +356,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_RelationRepository() { // Arrange - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); // Act - var query = scope.SqlContext.Query().Where(x => x.ParentId == _textpage.Id); + IQuery query = scope.SqlContext.Query().Where(x => x.ParentId == _textpage.Id); int count = repository.Count(query); // Assert @@ -380,7 +378,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); // Act - global::Umbraco.Core.Persistence.Querying.IQuery query = scope.SqlContext.Query().Where(x => x.RelationTypeId == _relateContent.Id); + IQuery query = scope.SqlContext.Query().Where(x => x.RelationTypeId == _relateContent.Id); IEnumerable relations = repository.Get(query); // Assert @@ -403,8 +401,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor ContentService.Delete(content, 0); // Act - var shouldntExist = repository.Exists(1); - var shouldExist = repository.Exists(2); + bool shouldntExist = repository.Exists(1); + bool shouldExist = repository.Exists(2); // Assert Assert.That(shouldntExist, Is.False); @@ -440,6 +438,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); + // Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs index 8d436eeeed..8c28fad0de 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs @@ -1,9 +1,14 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; @@ -16,24 +21,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class RelationTypeRepositoryTest : UmbracoIntegrationTest { [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); - private RelationTypeRepository CreateRepository(IScopeProvider provider) - { - return new RelationTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); - } + private RelationTypeRepository CreateRepository(IScopeProvider provider) => + new RelationTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); [Test] public void Can_Perform_Add_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act var relateMemberToContent = new RelationType("Relate Member to Content", "relateMemberToContent", true, Constants.ObjectTypes.Member, Constants.ObjectTypes.Document); @@ -50,18 +50,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationType = repository.Get(3); - relationType.Alias = relationType.Alias + "Updated"; - relationType.Name = relationType.Name + " Updated"; + IRelationType relationType = repository.Get(3); + relationType.Alias += "Updated"; + relationType.Name += " Updated"; repository.Save(relationType); - var relationTypeUpdated = repository.Get(3); + IRelationType relationTypeUpdated = repository.Get(3); // Assert Assert.That(relationTypeUpdated, Is.Not.Null); @@ -75,16 +75,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationType = repository.Get(3); + IRelationType relationType = repository.Get(3); repository.Delete(relationType); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -95,13 +95,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationType = repository.Get(8); + IRelationType relationType = repository.Get(8); // Assert Assert.That(relationType, Is.Not.Null); @@ -118,13 +118,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationTypes = repository.GetMany(); + IEnumerable relationTypes = repository.GetMany(); // Assert Assert.That(relationTypes, Is.Not.Null); @@ -138,13 +138,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationTypes = repository.GetMany(2, 3); + IEnumerable relationTypes = repository.GetMany(2, 3); // Assert Assert.That(relationTypes, Is.Not.Null); @@ -158,14 +158,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(9); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(9); // Assert Assert.That(exists, Is.True); @@ -177,13 +177,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias.StartsWith("relate")); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias.StartsWith("relate")); int count = repository.Count(query); // Assert @@ -195,15 +195,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var childObjType = Constants.ObjectTypes.DocumentType; - var query = scope.SqlContext.Query().Where(x => x.ChildObjectType == childObjType); - var result = repository.Get(query); + System.Guid childObjType = Constants.ObjectTypes.DocumentType; + IQuery query = scope.SqlContext.Query().Where(x => x.ChildObjectType == childObjType); + IEnumerable result = repository.Get(query); // Assert Assert.That(result, Is.Not.Null); @@ -219,14 +219,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var relateContentType = new RelationType("Relate ContentType on Copy", "relateContentTypeOnCopy", true, Constants.ObjectTypes.DocumentType, Constants.ObjectTypes.DocumentType); var relateContentMedia = new RelationType("Relate Content to Media", "relateContentToMedia", true, Constants.ObjectTypes.Document, Constants.ObjectTypes.Media); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new RelationTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); + var repository = new RelationTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); - repository.Save(relateContent);//Id 2 - repository.Save(relateContentType);//Id 3 - repository.Save(relateContentMedia);//Id 4 + repository.Save(relateContent); // Id 2 + repository.Save(relateContentType); // Id 3 + repository.Save(relateContentMedia); // Id 4 scope.Complete(); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs index f9084332b7..514829a2dc 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -11,6 +15,7 @@ using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -29,10 +34,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SetUpFileSystem() { _fileSystems = Mock.Of(); - var path = GlobalSettings.UmbracoScriptsPath; + string path = GlobalSettings.UmbracoScriptsPath; _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory.CreateLogger(), HostingEnvironment.MapPathWebRoot(path), HostingEnvironment.ToAbsolute(path)); Mock.Get(_fileSystems).Setup(x => x.ScriptsFileSystem).Returns(_fileSystem); - using (var stream = CreateStream("Umbraco.Sys.registerNamespace(\"Umbraco.Utils\");")) + using (Stream stream = CreateStream("Umbraco.Sys.registerNamespace(\"Umbraco.Utils\");")) { _fileSystem.AddFile("test-script.js", stream); } @@ -41,8 +46,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [TearDown] public void TearDownFileSystem() { - //Delete all files - Purge(_fileSystems.ScriptsFileSystem, ""); + // Delete all files + Purge(_fileSystems.ScriptsFileSystem, string.Empty); _fileSystems = null; } @@ -56,11 +61,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { // Act - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Assert Assert.That(repository, Is.Not.Null); @@ -71,17 +76,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act var script = new Script("test-add-script.js") { Content = "/// " }; repository.Save(script); - - //Assert + // Assert Assert.That(_fileSystem.FileExists("test-add-script.js"), Is.True); } } @@ -90,21 +94,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act var script = new Script("test-updated-script.js") { Content = "/// " }; repository.Save(script); - script.Content = "/// "; repository.Save(script); - - var scriptUpdated = repository.Get("test-updated-script.js"); + IScript scriptUpdated = repository.Get("test-updated-script.js"); // Assert Assert.That(_fileSystem.FileExists("test-updated-script.js"), Is.True); @@ -116,18 +118,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act - var script = repository.Get("test-script.js"); + IScript script = repository.Get("test-script.js"); repository.Delete(script); - // Assert - Assert.IsFalse(repository.Exists("test-script.js")); } } @@ -136,13 +135,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act - var exists = repository.Get("test-script.js"); + IScript exists = repository.Get("test-script.js"); // Assert Assert.That(exists, Is.Not.Null); @@ -155,10 +153,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); var script = new Script("test-script1.js") { Content = "/// " }; repository.Save(script); @@ -167,9 +164,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var script3 = new Script("test-script3.js") { Content = "/// " }; repository.Save(script3); - // Act - var scripts = repository.GetMany(); + IEnumerable scripts = repository.GetMany(); // Assert Assert.That(scripts, Is.Not.Null); @@ -183,10 +179,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); var script = new Script("test-script1.js") { Content = "/// " }; repository.Save(script); @@ -195,9 +190,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var script3 = new Script("test-script3.js") { Content = "/// " }; repository.Save(script3); - // Act - var scripts = repository.GetMany("test-script1.js", "test-script2.js"); + IEnumerable scripts = repository.GetMany("test-script1.js", "test-script2.js"); // Assert Assert.That(scripts, Is.Not.Null); @@ -211,13 +205,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act - var exists = repository.Exists("test-script.js"); + bool exists = repository.Exists("test-script.js"); // Assert Assert.That(exists, Is.True); @@ -230,23 +223,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor const string content = "/// "; // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); IScript script = new Script("test-move-script.js") { Content = content }; repository.Save(script); - // Act script = repository.Get("test-move-script.js"); script.Path = "moved/test-move-script.js"; repository.Save(script); - - var existsOld = repository.Exists("test-move-script.js"); - var existsNew = repository.Exists("moved/test-move-script.js"); + bool existsOld = repository.Exists("test-move-script.js"); + bool existsNew = repository.Exists("moved/test-move-script.js"); script = repository.Get("moved/test-move-script.js"); @@ -262,11 +252,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void PathTests() { // unless noted otherwise, no changes / 7.2.8 - - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); IScript script = new Script("test-path-1.js") { Content = "// script" }; repository.Save(script); @@ -275,7 +263,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("test-path-1.js", script.Path); Assert.AreEqual("/scripts/test-path-1.js", script.VirtualPath); - //ensure you can prefix the same path as the root path name + // ensure you can prefix the same path as the root path name script = new Script("scripts/path-2/test-path-2.js") { Content = "// script" }; repository.Save(script); @@ -287,7 +275,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(script); Assert.IsTrue(_fileSystem.FileExists("path-2/test-path-2.js")); - Assert.AreEqual("path-2\\test-path-2.js".Replace("\\", $"{Path.DirectorySeparatorChar}"), script.Path);// fixed in 7.3 - 7.2.8 does not update the path + Assert.AreEqual("path-2\\test-path-2.js".Replace("\\", $"{Path.DirectorySeparatorChar}"), script.Path); // fixed in 7.3 - 7.2.8 does not update the path Assert.AreEqual("/scripts/path-2/test-path-2.js", script.VirtualPath); script = repository.Get("path-2/test-path-2.js"); @@ -314,34 +302,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor script = new Script("\\test-path-4.js") { Content = "// script" }; Assert.Throws(() => // fixed in 7.3 - 7.2.8 used to strip the \ - { - repository.Save(script); - }); + repository.Save(script)); script = repository.Get("missing.js"); Assert.IsNull(script); // fixed in 7.3 - 7.2.8 used to... - Assert.Throws(() => - { - script = repository.Get("\\test-path-4.js"); // outside the filesystem, does not exist - }); - Assert.Throws(() => - { - script = repository.Get("../packages.config"); // outside the filesystem, exists - }); + Assert.Throws(() => script = repository.Get("\\test-path-4.js")); + Assert.Throws(() => script = repository.Get("../packages.config")); } } private void Purge(IFileSystem fs, string path) { - var files = fs.GetFiles(path, "*.js"); - foreach (var file in files) + IEnumerable files = fs.GetFiles(path, "*.js"); + foreach (string file in files) { fs.DeleteFile(file); } - var dirs = fs.GetDirectories(path); - foreach (var dir in dirs) + + IEnumerable dirs = fs.GetDirectories(path); + foreach (string dir in dirs) { Purge(fs, dir); fs.DeleteDirectory(dir); @@ -351,9 +332,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor protected Stream CreateStream(string contents = null) { if (string.IsNullOrEmpty(contents)) + { contents = "/* test */"; + } - var bytes = Encoding.UTF8.GetBytes(contents); + byte[] bytes = Encoding.UTF8.GetBytes(contents); var stream = new MemoryStream(bytes); return stream; diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs index e5304e1e31..80226da9a5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using Microsoft.Extensions.Logging; @@ -25,19 +29,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor CreateTestData(); } - private ServerRegistrationRepository CreateRepository(IScopeProvider provider) - { - return new ServerRegistrationRepository((IScopeAccessor) provider, LoggerFactory.CreateLogger()); - } + private ServerRegistrationRepository CreateRepository(IScopeProvider provider) => + new ServerRegistrationRepository((IScopeAccessor)provider, LoggerFactory.CreateLogger()); [Test] public void Cannot_Add_Duplicate_Server_Identities() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); var server = new ServerRegistration("http://shazwazza.com", "COMPUTER1", DateTime.Now); @@ -49,12 +51,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Cannot_Update_To_Duplicate_Server_Identities() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); - var server = repository.Get(1); + IServerRegistration server = repository.Get(1); server.ServerIdentity = "COMPUTER2"; Assert.Throws(() => repository.Save(server)); @@ -65,10 +67,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Assert Assert.That(repository, Is.Not.Null); @@ -79,13 +81,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var server = repository.Get(1); + IServerRegistration server = repository.Get(1); // Assert Assert.That(server, Is.Not.Null); @@ -98,13 +100,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var servers = repository.GetMany(); + IEnumerable servers = repository.GetMany(); // Assert Assert.That(servers.Count(), Is.EqualTo(3)); @@ -112,49 +114,48 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } // queries are not supported due to in-memory caching + //// [Test] + //// public void Can_Perform_GetByQuery_On_Repository() + //// { + //// // Arrange + //// var provider = ScopeProvider; + //// using (var unitOfWork = provider.GetUnitOfWork()) + //// using (var repository = CreateRepository(provider)) + //// { + //// // Act + //// var query = Query.Builder.Where(x => x.ServerIdentity.ToUpper() == "COMPUTER3"); + //// var result = repository.GetByQuery(query); - //[Test] - //public void Can_Perform_GetByQuery_On_Repository() - //{ - // // Arrange - // var provider = ScopeProvider; - // using (var unitOfWork = provider.GetUnitOfWork()) - // using (var repository = CreateRepository(provider)) - // { - // // Act - // var query = Query.Builder.Where(x => x.ServerIdentity.ToUpper() == "COMPUTER3"); - // var result = repository.GetByQuery(query); + //// // Assert + //// Assert.AreEqual(1, result.Count()); + //// } + //// } - // // Assert - // Assert.AreEqual(1, result.Count()); - // } - //} + //// [Test] + //// public void Can_Perform_Count_On_Repository() + //// { + //// // Arrange + //// var provider = ScopeProvider; + //// using (var unitOfWork = provider.GetUnitOfWork()) + //// using (var repository = CreateRepository(provider)) + //// { + //// // Act + //// var query = Query.Builder.Where(x => x.ServerAddress.StartsWith("http://")); + //// int count = repository.Count(query); - //[Test] - //public void Can_Perform_Count_On_Repository() - //{ - // // Arrange - // var provider = ScopeProvider; - // using (var unitOfWork = provider.GetUnitOfWork()) - // using (var repository = CreateRepository(provider)) - // { - // // Act - // var query = Query.Builder.Where(x => x.ServerAddress.StartsWith("http://")); - // int count = repository.Count(query); - - // // Assert - // Assert.That(count, Is.EqualTo(2)); - // } - //} + //// // Assert + //// Assert.That(count, Is.EqualTo(2)); + //// } + //// } [Test] public void Can_Perform_Add_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act var server = new ServerRegistration("http://shazwazza.com", "COMPUTER4", DateTime.Now); @@ -162,7 +163,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(server.HasIdentity, Is.True); - Assert.That(server.Id, Is.EqualTo(4));//With 3 existing entries the Id should be 4 + Assert.That(server.Id, Is.EqualTo(4)); // With 3 existing entries the Id should be 4 } } @@ -170,19 +171,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var server = repository.Get(2); + IServerRegistration server = repository.Get(2); server.ServerAddress = "https://umbraco.com"; server.IsActive = true; repository.Save(server); - var serverUpdated = repository.Get(2); + IServerRegistration serverUpdated = repository.Get(2); // Assert Assert.That(serverUpdated, Is.Not.Null); @@ -195,17 +196,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var server = repository.Get(3); + IServerRegistration server = repository.Get(3); Assert.IsNotNull(server); repository.Delete(server); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -216,14 +217,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(10); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(10); // Assert Assert.That(exists, Is.True); @@ -233,10 +234,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void CreateTestData() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); repository.Save(new ServerRegistration("http://localhost", "COMPUTER1", DateTime.Now) { IsActive = true }); repository.Save(new ServerRegistration("http://www.mydomain.com", "COMPUTER2", DateTime.Now)); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs index 747bb542cd..215303d981 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs @@ -1,4 +1,6 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using NUnit.Framework; using Umbraco.Core.Persistence.Repositories.Implement; @@ -9,39 +11,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { public void Name_Is_Suffixed() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Zulu" } }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Zulu"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Zulu"); Assert.AreEqual("Zulu (1)", res); } [Test] public void Suffixed_Name_Is_Incremented() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Zulu" }, new SimilarNodeName { Id = 2, Name = "Kilo (1)" }, new SimilarNodeName { Id = 3, Name = "Kilo" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Kilo (1)"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Kilo (1)"); Assert.AreEqual("Kilo (2)", res); } [Test] public void Lower_Number_Suffix_Is_Inserted() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Golf" }, new SimilarNodeName { Id = 2, Name = "Golf (2)" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Golf"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Golf"); Assert.AreEqual("Golf (1)", res); } @@ -50,13 +52,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [TestCase(0, "alpha", "alpha (3)")] public void Case_Is_Ignored(int nodeId, string nodeName, string expected) { - var names = new[] - { + SimilarNodeName[] names = new[] + { new SimilarNodeName { Id = 1, Name = "Alpha" }, new SimilarNodeName { Id = 2, Name = "Alpha (1)" }, new SimilarNodeName { Id = 3, Name = "Alpha (2)" }, }; - var res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); + string res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); Assert.AreEqual(expected, res); } @@ -66,7 +68,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { var names = new SimilarNodeName[] { }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Charlie"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Charlie"); Assert.AreEqual("Charlie", res); } @@ -78,7 +80,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { var names = new SimilarNodeName[] { }; - var res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); + string res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); Assert.AreEqual(expected, res); } @@ -86,14 +88,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Matching_NoedId_Causes_No_Change() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Kilo (1)" }, new SimilarNodeName { Id = 2, Name = "Yankee" }, new SimilarNodeName { Id = 3, Name = "Kilo" }, }; - var res = SimilarNodeName.GetUniqueName(names, 1, "Kilo (1)"); + string res = SimilarNodeName.GetUniqueName(names, 1, "Kilo (1)"); Assert.AreEqual("Kilo (1)", res); } @@ -103,16 +105,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { // Sequesnce is: Test, Test (1), Test (2) // Ignore: Test (1) (1) - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Alpha (2)" }, - new SimilarNodeName { Id = 2, Name = "Test" }, - new SimilarNodeName { Id = 3, Name = "Test (1)" }, - new SimilarNodeName { Id = 4, Name = "Test (2)" }, - new SimilarNodeName { Id = 5, Name = "Test (1) (1)" }, + new SimilarNodeName { Id = 2, Name = "Test" }, + new SimilarNodeName { Id = 3, Name = "Test (1)" }, + new SimilarNodeName { Id = 4, Name = "Test (2)" }, + new SimilarNodeName { Id = 5, Name = "Test (1) (1)" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Test"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Test"); Assert.AreEqual("Test (3)", res); } @@ -120,12 +122,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Matched_Name_Is_Suffixed() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Test" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Test"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Test"); Assert.AreEqual("Test (1)", res); } @@ -136,13 +138,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // "Test (1)" is treated as the "original" version of the name. // "Test (1) (1)" is the suffixed result of a copy, and therefore is incremented // Hence this test result should be the same as Suffixed_Name_Is_Incremented - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Test (1)" }, new SimilarNodeName { Id = 2, Name = "Test (1) (1)" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Test (1) (1)"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Test (1) (1)"); Assert.AreEqual("Test (1) (2)", res); } @@ -150,32 +152,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Suffixed_Name_Causes_Secondary_Suffix() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 6, Name = "Alpha (1)" } }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Alpha (1)"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Alpha (1)"); Assert.AreEqual("Alpha (1) (1)", res); } - [TestCase("Test (0)", "Test (0) (1)")] [TestCase("Test (-1)", "Test (-1) (1)")] [TestCase("Test (1) (-1)", "Test (1) (-1) (1)")] public void NonPositive_Suffix_Is_Ignored(string suffix, string expected) { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 6, Name = suffix } }; - var res = SimilarNodeName.GetUniqueName(names, 0, suffix); + string res = SimilarNodeName.GetUniqueName(names, 0, suffix); Assert.AreEqual(expected, res); } - - /* Original Tests - Can be deleted, as new tests cover all cases */ [TestCase(0, "Charlie", "Charlie")] @@ -183,15 +182,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [TestCase(0, "Golf", "Golf (1)")] [TestCase(0, "Kilo", "Kilo (2)")] [TestCase(0, "Alpha", "Alpha (3)")] - //[TestCase(0, "Kilo (1)", "Kilo (1) (1)")] // though... we might consider "Kilo (2)" - [TestCase(0, "Kilo (1)", "Kilo (2)")] // names[] contains "Kilo" AND "Kilo (1)", which implies that result should be "Kilo (2)" + //// [TestCase(0, "Kilo (1)", "Kilo (1) (1)")] // though... we might consider "Kilo (2)" + [TestCase(0, "Kilo (1)", "Kilo (2)")] // names[] contains "Kilo" AND "Kilo (1)", which implies that result should be "Kilo (2)" [TestCase(6, "Kilo (1)", "Kilo (1)")] // because of the id [TestCase(0, "alpha", "alpha (3)")] [TestCase(0, "", " (1)")] [TestCase(0, null, " (1)")] public void Test(int nodeId, string nodeName, string expected) { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Alpha (2)" }, new SimilarNodeName { Id = 2, Name = "Alpha" }, @@ -212,7 +211,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Explicit("This test fails! We need to fix up the logic")] public void TestMany() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Alpha (2)" }, new SimilarNodeName { Id = 2, Name = "Test" }, @@ -221,7 +220,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new SimilarNodeName { Id = 22, Name = "Test (1) (1)" }, }; - //fixme - this will yield "Test (2)" which is already in use + // fixme - this will yield "Test (2)" which is already in use Assert.AreEqual("Test (3)", SimilarNodeName.GetUniqueName(names, 0, "Test")); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs index b4b8316f83..e142c2a1fa 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; @@ -25,25 +29,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IFileSystems _fileSystems; private IFileSystem _fileSystem; - private IIOHelper IOHelper => GetRequiredService(); private IHostingEnvironment HostingEnvironment => GetRequiredService(); [SetUp] public void SetUpFileSystem() { _fileSystems = Mock.Of(); - var path = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoCssPath); + string path = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoCssPath); _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), path, "/css"); Mock.Get(_fileSystems).Setup(x => x.StylesheetsFileSystem).Returns(_fileSystem); - var stream = CreateStream("body {background:#EE7600; color:#FFF;}"); + Stream stream = CreateStream("body {background:#EE7600; color:#FFF;}"); _fileSystem.AddFile("styles.css", stream); } [TearDown] public void TearDownFileSystem() { - //Delete all files - Purge((PhysicalFileSystem) _fileSystem, ""); + // Delete all files + Purge((PhysicalFileSystem)_fileSystem, string.Empty); _fileSystem = null; } @@ -60,8 +63,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var repository = CreateRepository(); - + IStylesheetRepository repository = CreateRepository(); // Assert Assert.That(repository, Is.Not.Null); @@ -74,14 +76,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-add.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - - //Assert + // Assert Assert.That(_fileSystem.FileExists("test-add.css"), Is.True); } } @@ -92,21 +93,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-update.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - - var stylesheetUpdate = repository.Get("test-update.css"); + IStylesheet stylesheetUpdate = repository.Get("test-update.css"); stylesheetUpdate.Content = "body { color:#000; }"; repository.Save(stylesheetUpdate); + IStylesheet stylesheetUpdated = repository.Get("test-update.css"); - var stylesheetUpdated = repository.Get("test-update.css"); - - //Assert + // Assert Assert.That(stylesheetUpdated, Is.Not.Null); Assert.That(stylesheetUpdated.HasIdentity, Is.True); Assert.That(stylesheetUpdated.Content, Is.EqualTo("body { color:#000; }")); @@ -119,22 +118,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act IStylesheet stylesheet = new Stylesheet("test-update.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - stylesheet.AddProperty(new StylesheetProperty("Test", "p", "font-size:2em;")); repository.Save(stylesheet); - - //re-get + // re-get stylesheet = repository.Get(stylesheet.Name); - //Assert + // Assert Assert.That(stylesheet.Content, Is.EqualTo("body { color:#000; } .bold {font-weight:bold;}\r\n\r\n/**umb_name:Test*/\r\np {\r\n\tfont-size:2em;\r\n}".Replace("\r\n", Environment.NewLine))); Assert.AreEqual(1, stylesheet.Properties.Count()); } @@ -146,13 +143,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-update.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - stylesheet.AddProperty(new StylesheetProperty("Test", "p", "font-size:2em;")); Assert.Throws(() => stylesheet.AddProperty(new StylesheetProperty("test", "p", "font-size:2em;"))); @@ -165,17 +161,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-delete.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - repository.Delete(stylesheet); - - //Assert + // Assert Assert.That(_fileSystem.FileExists("test-delete.css"), Is.False); } } @@ -186,16 +180,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act - var stylesheet = repository.Get("styles.css"); + IStylesheet stylesheet = repository.Get("styles.css"); // Assert Assert.That(stylesheet, Is.Not.Null); Assert.That(stylesheet.HasIdentity, Is.True); Assert.That(stylesheet.Content, Is.EqualTo("body {background:#EE7600; color:#FFF;}")); - //Assert.That(repository.ValidateStylesheet(stylesheet), Is.True); //TODO this can't be activated before we handle file systems correct + //// Assert.That(repository.ValidateStylesheet(stylesheet), Is.True); //TODO this can't be activated before we handle file systems correct } } @@ -205,14 +199,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); var stylesheet = new Stylesheet("styles-v2.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - // Act - var stylesheets = repository.GetMany(); + IEnumerable stylesheets = repository.GetMany(); // Assert Assert.That(stylesheets, Is.Not.Null); @@ -228,14 +221,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); var stylesheet = new Stylesheet("styles-v2.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - // Act - var stylesheets = repository.GetMany("styles-v2.css", "styles.css"); + IEnumerable stylesheets = repository.GetMany("styles-v2.css", "styles.css"); // Assert Assert.That(stylesheets, Is.Not.Null); @@ -251,10 +243,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act - var exists = repository.Exists("styles.css"); + bool exists = repository.Exists("styles.css"); // Assert Assert.That(exists, Is.True); @@ -265,10 +257,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void PathTests() { // unless noted otherwise, no changes / 7.2.8 - using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); IStylesheet stylesheet = new Stylesheet("test-path-1.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); @@ -281,7 +272,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(stylesheet); Assert.IsTrue(_fileSystem.FileExists("path-2/test-path-2.css")); - Assert.AreEqual("path-2\\test-path-2.css".Replace("\\", $"{Path.DirectorySeparatorChar}"), stylesheet.Path);// fixed in 7.3 - 7.2.8 does not update the path + Assert.AreEqual("path-2\\test-path-2.css".Replace("\\", $"{Path.DirectorySeparatorChar}"), stylesheet.Path); // fixed in 7.3 - 7.2.8 does not update the path Assert.AreEqual("/css/path-2/test-path-2.css", stylesheet.VirtualPath); stylesheet = repository.Get("path-2/test-path-2.css"); @@ -308,9 +299,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor stylesheet = new Stylesheet("\\test-path-4.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; Assert.Throws(() => // fixed in 7.3 - 7.2.8 used to strip the \ - { - repository.Save(stylesheet); - }); + repository.Save(stylesheet)); // fixed in 7.3 - 7.2.8 used to throw stylesheet = repository.Get("missing.css"); @@ -328,13 +317,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private void Purge(PhysicalFileSystem fs, string path) { - var files = fs.GetFiles(path, "*.css"); - foreach (var file in files) + IEnumerable files = fs.GetFiles(path, "*.css"); + foreach (string file in files) { fs.DeleteFile(file); } - var dirs = fs.GetDirectories(path); - foreach (var dir in dirs) + + IEnumerable dirs = fs.GetDirectories(path); + foreach (string dir in dirs) { Purge(fs, dir); fs.DeleteDirectory(dir); @@ -344,9 +334,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor protected Stream CreateStream(string contents = null) { if (string.IsNullOrEmpty(contents)) + { contents = "/* test */"; + } - var bytes = Encoding.UTF8.GetBytes(contents); + byte[] bytes = Encoding.UTF8.GetBytes(contents); var stream = new MemoryStream(bytes); return stream; diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs index 47164a0ee0..7744173f3f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs @@ -1,4 +1,8 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core.Cache; @@ -18,18 +22,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class TagRepositoryTest : UmbracoIntegrationTest { private IFileService FileService => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); + private IDocumentRepository DocumentRepository => GetRequiredService(); + private IMediaRepository MediaRepository => GetRequiredService(); + private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); [Test] public void Can_Perform_Add_On_Repository() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); var tag = new Tag { @@ -46,10 +54,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Multiple_Adds_On_Repository() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); var tag = new Tag { @@ -76,29 +84,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); Assert.AreEqual(2, repository.GetTagsForEntity(content.Id).Count()); } @@ -107,38 +117,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Append_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"}, - }, false); + tags2, + false); Assert.AreEqual(4, repository.GetTagsForEntity(content.Id).Count()); } @@ -147,40 +161,44 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Replace_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"}, - }, true); + tags2, + true); - var result = repository.GetTagsForEntity(content.Id).ToArray(); + ITag[] result = repository.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(2, result.Length); Assert.AreEqual("tag3", result[0].Text); Assert.AreEqual("tag4", result[1].Text); @@ -190,40 +208,44 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Merge_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - }, false); + tags2, + false); - var result = repository.GetTagsForEntity(content.Id); + IEnumerable result = repository.GetTagsForEntity(content.Id); Assert.AreEqual(3, result.Count()); } } @@ -231,36 +253,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Clear_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); - repository.Assign( - content.Id, - contentType.PropertyTypes.First().Id, - new[] + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; + repository.Assign( + content.Id, + contentType.PropertyTypes.First().Id, + tags, + false); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - Enumerable.Empty(), true); + Enumerable.Empty(), + true); - var result = repository.GetTagsForEntity(content.Id); + IEnumerable result = repository.GetTagsForEntity(content.Id); Assert.AreEqual(0, result.Count()); } } @@ -268,42 +293,45 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Remove_Specific_Tags_From_Property() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tagsToRemove = new[] + { + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Remove( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"} - }); + tagsToRemove); - var result = repository.GetTagsForEntity(content.Id).ToArray(); + ITag[] result = repository.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(2, result.Length); Assert.AreEqual("tag1", result[0].Text); Assert.AreEqual("tag4", result[1].Text); @@ -313,44 +341,48 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Content_By_Id() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result = repository.GetTagsForEntity(content2.Id); + IEnumerable result = repository.GetTagsForEntity(content2.Id); Assert.AreEqual(2, result.Count()); } } @@ -358,45 +390,49 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Content_By_Key() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - //get by key - var result = repository.GetTagsForEntity(content2.Key); + // get by key + IEnumerable result = repository.GetTagsForEntity(content2.Key); Assert.AreEqual(2, result.Count()); } } @@ -404,35 +440,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); - var result = repository.GetMany(); + IEnumerable result = repository.GetMany(); Assert.AreEqual(4, result.Count()); } } @@ -440,40 +478,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All_With_Ids() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); - var tags = new[] + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - tags, false); + tags, + false); // TODO: This would be nice to be able to map the ids back but unfortunately we are not doing this - //var result = repository.GetAll(new[] {tags[0].Id, tags[1].Id, tags[2].Id}); - var all = repository.GetMany().ToArray(); + // var result = repository.GetAll(new[] {tags[0].Id, tags[1].Id, tags[2].Id}); + ITag[] all = repository.GetMany().ToArray(); - var result = repository.GetMany(all[0].Id, all[1].Id, all[2].Id); + IEnumerable result = repository.GetMany(all[0].Id, all[1].Id, all[2].Id); Assert.AreEqual(3, result.Count()); } } @@ -481,44 +520,48 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Content_For_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result = repository.GetTagsForEntity(content1.Id, "test1"); + IEnumerable result = repository.GetTagsForEntity(content1.Id, "test1"); Assert.AreEqual(2, result.Count()); } } @@ -526,43 +569,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Property_By_Id() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias).ToArray(); - var result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias).ToArray(); + ITag[] result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias).ToArray(); + ITag[] result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias).ToArray(); Assert.AreEqual(4, result1.Length); Assert.AreEqual(2, result2.Length); } @@ -571,43 +618,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Property_By_Key() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.First().Alias).ToArray(); - var result2 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.Last().Alias).ToArray(); + ITag[] result1 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.First().Alias).ToArray(); + ITag[] result2 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.Last().Alias).ToArray(); Assert.AreEqual(4, result1.Length); Assert.AreEqual(2, result2.Length); } @@ -616,43 +667,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Property_For_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias, "test1").ToArray(); - var result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias, "test1").ToArray(); + ITag[] result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias, "test1").ToArray(); + ITag[] result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias, "test1").ToArray(); Assert.AreEqual(2, result1.Length); Assert.AreEqual(1, result2.Length); @@ -662,49 +717,53 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Entity_Type() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content).ToArray(); - var result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media).ToArray(); - var result3 = repository.GetTagsForEntityType(TaggableObjectTypes.All).ToArray(); + ITag[] result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content).ToArray(); + ITag[] result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media).ToArray(); + ITag[] result3 = repository.GetTagsForEntityType(TaggableObjectTypes.All).ToArray(); Assert.AreEqual(3, result1.Length); Assert.AreEqual(2, result2.Length); @@ -719,49 +778,53 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Entity_Type_For_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content, "test1").ToArray(); - var result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media, "test1").ToArray(); + ITag[] result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content, "test1").ToArray(); + ITag[] result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media, "test1").ToArray(); Assert.AreEqual(2, result1.Length); Assert.AreEqual(1, result2.Length); @@ -771,31 +834,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Cascade_Deletes_Tag_Relations() { - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); DocumentRepository.Delete(content1); @@ -808,79 +873,91 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tagged_Entities_For_Tag_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag {Text = "tag1", Group = "test"}, + new Tag {Text = "tag2", Group = "test1"}, + new Tag {Text = "tag3", Group = "test"} + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags2, + false); + Tag[] tags3 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags3, + false); - var contentTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test").ToArray(); - //there are two content items tagged against the 'test' group + TaggedEntity[] contentTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test").ToArray(); + + // there are two content items tagged against the 'test' group Assert.AreEqual(2, contentTestIds.Length); - //there are a total of two property types tagged against the 'test' group + + // there are a total of two property types tagged against the 'test' group Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 2 tags tagged against the 'test' group + + // there are a total of 2 tags tagged against the 'test' group Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var contentTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test1").ToArray(); - //there are two content items tagged against the 'test1' group + TaggedEntity[] contentTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test1").ToArray(); + + // there are two content items tagged against the 'test1' group Assert.AreEqual(2, contentTest1Ids.Length); - //there are a total of two property types tagged against the 'test1' group + + // there are a total of two property types tagged against the 'test1' group Assert.AreEqual(2, contentTest1Ids.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 1 tags tagged against the 'test1' group + + // there are a total of 1 tags tagged against the 'test1' group Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var mediaTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test"); + IEnumerable mediaTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test"); Assert.AreEqual(1, mediaTestIds.Count()); - var mediaTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test1"); + IEnumerable mediaTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test1"); Assert.AreEqual(1, mediaTest1Ids.Count()); } } @@ -888,86 +965,92 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tagged_Entities_For_Tag() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + }; repository.Assign( content2.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - }, false); + tags2, + false); + Tag[] tags3 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags3, + false); - var contentTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag1").ToArray(); - //there are two content items tagged against the 'tag1' tag + TaggedEntity[] contentTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag1").ToArray(); + + // there are two content items tagged against the 'tag1' tag Assert.AreEqual(2, contentTestIds.Length); - //there are a total of two property types tagged against the 'tag1' tag + + // there are a total of two property types tagged against the 'tag1' tag Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 1 tags since we're only looking against one tag + + // there are a total of 1 tags since we're only looking against one tag Assert.AreEqual(1, contentTestIds.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var contentTest1Ids = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag3").ToArray(); - //there are 1 content items tagged against the 'tag3' tag + TaggedEntity[] contentTest1Ids = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag3").ToArray(); + + // there are 1 content items tagged against the 'tag3' tag Assert.AreEqual(1, contentTest1Ids.Length); - //there are a total of two property types tagged against the 'tag3' tag + + // there are a total of two property types tagged against the 'tag3' tag Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 1 tags since we're only looking against one tag + + // there are a total of 1 tags since we're only looking against one tag Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var mediaTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, "tag1"); + IEnumerable mediaTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, "tag1"); Assert.AreEqual(1, mediaTestIds.Count()); } } - private TagRepository CreateRepository(IScopeProvider provider) - { - return new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); - } + private TagRepository CreateRepository(IScopeProvider provider) => + new TagRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs index 5cab23c4c9..9780b53997 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs @@ -1,10 +1,12 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; -using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; @@ -30,22 +32,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class TemplateRepositoryTest : UmbracoIntegrationTest { private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IFileSystems FileSystems => GetRequiredService(); - private ITemplateRepository CreateRepository(IScopeProvider provider) - { - return new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); - } + private ITemplateRepository CreateRepository(IScopeProvider provider) => + new TemplateRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); [Test] public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Assert Assert.That(repository, Is.Not.Null); @@ -56,18 +57,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_View() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test"); repository.Save(template); - - //Assert + // Assert Assert.That(repository.Get("test"), Is.Not.Null); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); } @@ -77,11 +77,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_View_With_Default_Content() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -90,7 +90,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(template); - //Assert + // Assert Assert.That(repository.Get("test"), Is.Not.Null); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); Assert.AreEqual( @@ -103,13 +103,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_View_With_Default_Content_With_Parent() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); - //NOTE: This has to be persisted first + // NOTE: This has to be persisted first var template = new Template(ShortStringHelper, "test", "test"); repository.Save(template); @@ -118,7 +118,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor template2.SetMasterTemplate(template); repository.Save(template2); - //Assert + // Assert Assert.That(repository.Get("test2"), Is.Not.Null); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test2.cshtml"), Is.True); Assert.AreEqual( @@ -131,11 +131,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_Unique_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -150,7 +150,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(template2); - //Assert + // Assert Assert.AreEqual("test1", template2.Alias); } } @@ -159,11 +159,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_Unique_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -181,7 +181,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor template.Alias = "test1"; repository.Save(template); - //Assert + // Assert Assert.AreEqual("test11", template.Alias); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test11.cshtml"), Is.True); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.False); @@ -192,11 +192,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_View() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -208,7 +208,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor template.Content += ""; repository.Save(template); - var updated = repository.Get("test"); + ITemplate updated = repository.Get("test"); // Assert Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); @@ -220,11 +220,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_View() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var template = new Template(ShortStringHelper, "test", "test") { @@ -233,7 +233,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(template); // Act - var templates = repository.Get("test"); + ITemplate templates = repository.Get("test"); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); repository.Delete(templates); @@ -247,14 +247,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_When_Assigned_To_Doc() { // Arrange - var provider = ScopeProvider; - var scopeAccessor = (IScopeAccessor) provider; - var dataTypeService = GetRequiredService(); - var fileService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; + var scopeAccessor = (IScopeAccessor)provider; + IDataTypeService dataTypeService = GetRequiredService(); + IFileService fileService = GetRequiredService(); using (provider.CreateScope()) { - var templateRepository = CreateRepository(provider); + ITemplateRepository templateRepository = CreateRepository(provider); var globalSettings = new GlobalSettings(); var serializer = new JsonNetSerializer(); var tagRepository = new TagRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory.CreateLogger()); @@ -268,20 +268,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty()); var contentRepo = new DocumentRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, contentTypeRepository, templateRepository, tagRepository, languageRepository, relationRepository, relationTypeRepository, propertyEditors, dataValueReferences, dataTypeService, serializer); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); // else, FK violation on contentType! - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - var textpage = ContentBuilder.CreateSimpleContent(contentType); + Content textpage = ContentBuilder.CreateSimpleContent(contentType); contentRepo.Save(textpage); textpage.TemplateId = template.Id; contentRepo.Save(textpage); // Act - var templates = templateRepository.Get("textPage"); + ITemplate templates = templateRepository.Get("textPage"); templateRepository.Delete(templates); // Assert @@ -293,11 +293,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_Nested_Templates() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent") { @@ -320,7 +320,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(baby); // Act - var templates = repository.Get("parent"); + ITemplate templates = repository.Get("parent"); repository.Delete(templates); // Assert @@ -332,18 +332,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_All() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); - var created = CreateHierarchy(repository).ToArray(); + ITemplate[] created = CreateHierarchy(repository).ToArray(); // Act - var all = repository.GetAll(); - var allByAlias = repository.GetAll("parent", "child2", "baby2", "notFound"); - var allById = repository.GetMany(created[0].Id, created[2].Id, created[4].Id, created[5].Id, 999999); + IEnumerable all = repository.GetAll(); + IEnumerable allByAlias = repository.GetAll("parent", "child2", "baby2", "notFound"); + IEnumerable allById = repository.GetMany(created[0].Id, created[2].Id, created[4].Id, created[5].Id, 999999); // Assert Assert.AreEqual(9, all.Count()); @@ -361,17 +361,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_Children() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); - var created = CreateHierarchy(repository).ToArray(); + ITemplate[] created = CreateHierarchy(repository).ToArray(); // Act - var childrenById = repository.GetChildren(created[1].Id); - var childrenByAlias = repository.GetChildren(created[1].Alias); + IEnumerable childrenById = repository.GetChildren(created[1].Id); + IEnumerable childrenByAlias = repository.GetChildren(created[1].Alias); // Assert Assert.AreEqual(2, childrenById.Count()); @@ -385,16 +385,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_Children_At_Root() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); CreateHierarchy(repository).ToArray(); // Act - var children = repository.GetChildren(-1); + IEnumerable children = repository.GetChildren(-1); // Assert Assert.AreEqual(1, children.Count()); @@ -406,16 +406,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_Descendants() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); - var created = CreateHierarchy(repository).ToArray(); + ITemplateRepository repository = CreateRepository(provider); + ITemplate[] created = CreateHierarchy(repository).ToArray(); // Act - var descendantsById = repository.GetDescendants(created[1].Id); - var descendantsByAlias = repository.GetDescendants(created[1].Alias); + IEnumerable descendantsById = repository.GetDescendants(created[1].Id); + IEnumerable descendantsByAlias = repository.GetDescendants(created[1].Alias); // Assert Assert.AreEqual(3, descendantsById.Count()); @@ -430,11 +430,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Path_Is_Set_Correctly_On_Creation() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent"); var child1 = new Template(ShortStringHelper, "child1", "child1"); @@ -492,11 +492,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Path_Is_Set_Correctly_On_Update() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent"); var child1 = new Template(ShortStringHelper, "child1", "child1"); @@ -519,11 +519,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(toddler1); repository.Save(toddler2); - //Act + // Act toddler2.SetMasterTemplate(child2); repository.Save(toddler2); - //Assert + // Assert Assert.AreEqual($"-1,{parent.Id},{child2.Id},{toddler2.Id}", toddler2.Path); } } @@ -532,26 +532,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Path_Is_Set_Correctly_On_Update_With_Master_Template_Removal() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent"); - var child1 = new Template(ShortStringHelper, "child1", "child1"); - - child1.MasterTemplateAlias = parent.Alias; - child1.MasterTemplateId = new Lazy(() => parent.Id); + var child1 = new Template(ShortStringHelper, "child1", "child1") + { + MasterTemplateAlias = parent.Alias, + MasterTemplateId = new Lazy(() => parent.Id) + }; repository.Save(parent); repository.Save(child1); - //Act + // Act child1.SetMasterTemplate(null); repository.Save(child1); - //Assert + // Assert Assert.AreEqual($"-1,{child1.Id}", child1.Path); } } @@ -561,19 +562,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { var testHelper = new TestHelper(); - //Delete all files + // Delete all files var fsViews = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory.CreateLogger(), HostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews), HostingEnvironment.ToAbsolute(Constants.SystemDirectories.MvcViews)); - var views = fsViews.GetFiles("", "*.cshtml"); - foreach (var file in views) + IEnumerable views = fsViews.GetFiles(string.Empty, "*.cshtml"); + foreach (string file in views) + { fsViews.DeleteFile(file); + } } protected Stream CreateStream(string contents = null) { if (string.IsNullOrEmpty(contents)) + { contents = "/* test */"; + } - var bytes = Encoding.UTF8.GetBytes(contents); + byte[] bytes = Encoding.UTF8.GetBytes(contents); var stream = new MemoryStream(bytes); return stream; @@ -620,7 +625,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Content = @"<%@ Master Language=""C#"" %>" }; - child1.MasterTemplateAlias = parent.Alias; child1.MasterTemplateId = new Lazy(() => parent.Id); child2.MasterTemplateAlias = parent.Alias; @@ -652,8 +656,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(baby1); repository.Save(baby2); - - return new[] {parent, child1, child2, toddler1, toddler2, toddler3, toddler4, baby1, baby2}; + return new[] { parent, child1, child2, toddler1, toddler2, toddler3, toddler4, baby1, baby2 }; } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs index e67b9f9b60..72a2d073be 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs @@ -1,7 +1,12 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core.Models.Membership; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; @@ -15,21 +20,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class UserGroupRepositoryTest : UmbracoIntegrationTest { - private UserGroupRepository CreateRepository(IScopeProvider provider) - { - return new UserGroupRepository((IScopeAccessor) provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); - } + private UserGroupRepository CreateRepository(IScopeProvider provider) => + new UserGroupRepository((IScopeAccessor)provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); [Test] public void Can_Perform_Add_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); // Act repository.Save(userGroup); @@ -44,13 +47,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Multiple_Adds_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); - var userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); + UserGroup userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); + UserGroup userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); // Act repository.Save(userGroup1); @@ -68,17 +71,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Fresh_Entity_Is_Not_Dirty() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); repository.Save(userGroup); scope.Complete(); // Act - var resolved = repository.Get((int) userGroup.Id); + IUserGroup resolved = repository.Get((int)userGroup.Id); bool dirty = ((UserGroup)resolved).IsDirty(); // Assert @@ -90,21 +93,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); repository.Save(userGroup); // Act - var resolved = repository.Get((int) userGroup.Id); + IUserGroup resolved = repository.Get((int)userGroup.Id); resolved.Name = "New Name"; resolved.Permissions = new[] { "Z", "Y", "X" }; repository.Save(resolved); scope.Complete(); - var updatedItem = repository.Get((int) userGroup.Id); + IUserGroup updatedItem = repository.Get((int)userGroup.Id); // Assert Assert.That(updatedItem.Id, Is.EqualTo(resolved.Id)); @@ -116,23 +119,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Delete_On_UserGroupRepository() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); // Act repository.Save(userGroup); - var id = userGroup.Id; + int id = userGroup.Id; - var repository2 = new UserGroupRepository((IScopeAccessor) provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); + var repository2 = new UserGroupRepository((IScopeAccessor)provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); repository2.Delete(userGroup); scope.Complete(); - var resolved = repository2.Get((int) id); + IUserGroup resolved = repository2.Get((int)id); // Assert Assert.That(resolved, Is.Null); @@ -143,22 +146,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); repository.Save(userGroup); scope.Complete(); // Act - var resolved = repository.Get((int) userGroup.Id); + IUserGroup resolved = repository.Get((int)userGroup.Id); // Assert Assert.That(resolved.Id, Is.EqualTo(userGroup.Id)); - //Assert.That(resolved.CreateDate, Is.GreaterThan(DateTime.MinValue)); - //Assert.That(resolved.UpdateDate, Is.GreaterThan(DateTime.MinValue)); + //// Assert.That(resolved.CreateDate, Is.GreaterThan(DateTime.MinValue)); + //// Assert.That(resolved.UpdateDate, Is.GreaterThan(DateTime.MinValue)); Assert.That(resolved.Name, Is.EqualTo(userGroup.Name)); Assert.That(resolved.Alias, Is.EqualTo(userGroup.Alias)); Assert.That(resolved.Permissions, Is.EqualTo(userGroup.Permissions)); @@ -169,16 +172,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); CreateAndCommitMultipleUserGroups(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1"); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(1)); @@ -189,15 +192,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Param_Ids_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] userGroups = CreateAndCommitMultipleUserGroups(repository); // Act - var result = repository.GetMany(userGroups[0].Id, userGroups[1].Id); + IEnumerable result = repository.GetMany(userGroups[0].Id, userGroups[1].Id); // Assert Assert.That(result, Is.Not.Null); @@ -210,15 +213,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); CreateAndCommitMultipleUserGroups(repository); // Act - var result = repository.GetMany(); + IEnumerable result = repository.GetMany(); // Assert Assert.That(result, Is.Not.Null); @@ -231,15 +234,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] userGroups = CreateAndCommitMultipleUserGroups(repository); // Act - var exists = repository.Exists(userGroups[0].Id); + bool exists = repository.Exists(userGroups[0].Id); // Assert Assert.That(exists, Is.True); @@ -250,16 +253,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] userGroups = CreateAndCommitMultipleUserGroups(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1" || x.Alias == "testGroup2"); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1" || x.Alias == "testGroup2"); + int result = repository.Count(query); // Assert Assert.That(result, Is.GreaterThanOrEqualTo(2)); @@ -270,16 +273,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Remove_Section_For_Group() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var groups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] groups = CreateAndCommitMultipleUserGroups(repository); // Act - //add and remove a few times, this tests the internal collection + // add and remove a few times, this tests the internal collection groups[0].RemoveAllowedSection("content"); groups[0].RemoveAllowedSection("content"); groups[0].AddAllowedSection("content"); @@ -293,7 +296,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); // Assert - var result = repository.GetMany((int)groups[0].Id, (int)groups[1].Id).ToArray(); + IUserGroup[] result = repository.GetMany((int)groups[0].Id, (int)groups[1].Id).ToArray(); Assert.AreEqual(1, result[0].AllowedSections.Count()); Assert.AreEqual("media", result[0].AllowedSections.First()); Assert.AreEqual(1, result[1].AllowedSections.Count()); @@ -305,16 +308,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_Section_ForGroup() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var groups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] groups = CreateAndCommitMultipleUserGroups(repository); // Act - //add and remove a few times, this tests the internal collection + // add and remove a few times, this tests the internal collection groups[0].ClearAllowedSections(); groups[0].AddAllowedSection("content"); groups[0].AddAllowedSection("media"); @@ -322,7 +325,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor groups[0].AddAllowedSection("content"); groups[0].AddAllowedSection("settings"); - //add the same even though it's already there + // add the same even though it's already there groups[0].AddAllowedSection("content"); groups[1].ClearAllowedSections(); @@ -335,11 +338,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(groups[2]); scope.Complete(); - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) + { Assert.IsNotNull(repository.Get(groups[i].Id)); + } // Assert - var result = repository.GetMany(groups[0].Id, groups[1].Id, groups[2].Id).ToArray(); + IUserGroup[] result = repository.GetMany(groups[0].Id, groups[1].Id, groups[2].Id).ToArray(); Assert.AreEqual(3, result.Length); Assert.AreEqual(3, result[0].AllowedSections.Count()); @@ -356,15 +361,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_Section_For_Group() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var groups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] groups = CreateAndCommitMultipleUserGroups(repository); // Act - groups[0].RemoveAllowedSection("content"); groups[0].AddAllowedSection("settings"); @@ -372,7 +376,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); // Assert - var result = repository.Get(groups[0].Id); + IUserGroup result = repository.Get(groups[0].Id); Assert.AreEqual(2, result.AllowedSections.Count()); Assert.IsTrue(result.AllowedSections.Contains("settings")); Assert.IsTrue(result.AllowedSections.Contains("media")); @@ -383,25 +387,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Get_Groups_Assigned_To_Section() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var user1 = UserGroupBuilder.CreateUserGroup(suffix: "1", allowedSections: new[] { "test1" }); - var user2 = UserGroupBuilder.CreateUserGroup(suffix: "2", allowedSections: new[] { "test2" }); - var user3 = UserGroupBuilder.CreateUserGroup(suffix: "3", allowedSections: new[] { "test1" }); + UserGroup user1 = UserGroupBuilder.CreateUserGroup(suffix: "1", allowedSections: new[] { "test1" }); + UserGroup user2 = UserGroupBuilder.CreateUserGroup(suffix: "2", allowedSections: new[] { "test2" }); + UserGroup user3 = UserGroupBuilder.CreateUserGroup(suffix: "3", allowedSections: new[] { "test1" }); repository.Save(user1); repository.Save(user2); repository.Save(user3); scope.Complete(); // Act - var groups = repository.GetGroupsAssignedToSection("test1"); + IEnumerable groups = repository.GetGroupsAssignedToSection("test1"); // Assert Assert.AreEqual(2, groups.Count()); - var names = groups.Select(x => x.Name).ToArray(); + string[] names = groups.Select(x => x.Name).ToArray(); Assert.IsTrue(names.Contains("Test Group1")); Assert.IsFalse(names.Contains("Test Group2")); Assert.IsTrue(names.Contains("Test Group3")); @@ -410,9 +414,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IUserGroup[] CreateAndCommitMultipleUserGroups(IUserGroupRepository repository) { - var userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); - var userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); - var userGroup3 = UserGroupBuilder.CreateUserGroup(suffix: "3"); + UserGroup userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); + UserGroup userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); + UserGroup userGroup3 = UserGroupBuilder.CreateUserGroup(suffix: "3"); repository.Save(userGroup1); repository.Save(userGroup2); repository.Save(userGroup3); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs index ba773716fd..a5164e0244 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs @@ -1,16 +1,22 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; -using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Mappers; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; @@ -27,20 +33,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class UserRepositoryTest : UmbracoIntegrationTest { private IDocumentRepository DocumentRepository => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); + private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); + private IMediaRepository MediaRepository => GetRequiredService(); private UserRepository CreateRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; + var accessor = (IScopeAccessor)provider; var repository = new UserRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), Mappers, Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); return repository; } private UserGroupRepository CreateUserGroupRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; + var accessor = (IScopeAccessor)provider; return new UserGroupRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); } @@ -48,17 +57,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user = UserBuilderInstance.Build(); + User user = UserBuilderInstance.Build(); // Act repository.Save(user); - // Assert Assert.That(user.HasIdentity, Is.True); } @@ -68,20 +76,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Multiple_Adds_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user1 = UserBuilderInstance.WithSuffix("1").Build(); - var use2 = UserBuilderInstance.WithSuffix("2").Build(); + User user1 = UserBuilderInstance.WithSuffix("1").Build(); + User use2 = UserBuilderInstance.WithSuffix("2").Build(); // Act repository.Save(user1); repository.Save(use2); - // Assert Assert.That(user1.HasIdentity, Is.True); Assert.That(use2.HasIdentity, Is.True); @@ -92,17 +99,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Fresh_Entity_Is_Not_Dirty() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user = UserBuilderInstance.WithoutIdentity().Build(); + User user = UserBuilderInstance.WithoutIdentity().Build(); repository.Save(user); - // Act - var resolved = repository.Get((int)user.Id); + IUser resolved = repository.Get((int)user.Id); bool dirty = ((User)resolved).IsDirty(); // Assert @@ -114,24 +120,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user = UserBuilderInstance.Build(); + User user = UserBuilderInstance.Build(); // Act repository.Save(user); - var id = user.Id; + int id = user.Id; - var repository2 = new UserRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Mock.Of(), Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); + var repository2 = new UserRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Mock.Of(), Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); repository2.Delete(user); - - var resolved = repository2.Get((int) id); + IUser resolved = repository2.Get((int)id); // Assert Assert.That(resolved, Is.Null); @@ -142,16 +147,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); - var userGroupRepository = CreateUserGroupRepository(provider); + UserRepository repository = CreateRepository(provider); + UserGroupRepository userGroupRepository = CreateUserGroupRepository(provider); - var user = CreateAndCommitUserWithGroup(repository, userGroupRepository); + User user = CreateAndCommitUserWithGroup(repository, userGroupRepository); // Act - var updatedItem = repository.Get(user.Id); + IUser updatedItem = repository.Get(user.Id); // FIXME: this test cannot work, user has 2 sections but the way it's created, // they don't show, so the comparison with updatedItem fails - fix! @@ -165,16 +170,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); CreateAndCommitMultipleUsers(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1"); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(1)); @@ -185,15 +190,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Param_Ids_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); // Act - var result = repository.GetMany((int) users[0].Id, (int) users[1].Id); + IEnumerable result = repository.GetMany((int)users[0].Id, (int)users[1].Id); // Assert Assert.That(result, Is.Not.Null); @@ -206,15 +211,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); CreateAndCommitMultipleUsers(repository); // Act - var result = repository.GetMany(); + IEnumerable result = repository.GetMany(); // Assert Assert.That(result, Is.Not.Null); @@ -227,15 +232,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); // Act - var exists = repository.Exists(users[0].Id); + bool exists = repository.Exists(users[0].Id); // Assert Assert.That(exists, Is.True); @@ -246,16 +251,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); + int result = repository.Count(query); // Assert Assert.AreEqual(2, result); @@ -265,13 +270,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Paged_Results_By_Query_And_Filter_And_Groups() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); - var query = provider.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); + IUser[] users = CreateAndCommitMultipleUsers(repository); + IQuery query = provider.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); try { @@ -279,9 +284,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlCount = true; // Act - var result = repository.GetPagedResultsByQuery(query, 0, 10, out var totalRecs, user => user.Id, Direction.Ascending, - excludeUserGroups: new[] { Constants.Security.TranslatorGroupAlias }, - filter: provider.SqlContext.Query().Where(x => x.Id > -1)); + IEnumerable result = repository.GetPagedResultsByQuery( + query, + 0, + 10, + out long totalRecs, + user => user.Id, + Direction.Ascending, + excludeUserGroups: new[] { Constants.Security.TranslatorGroupAlias }, + filter: provider.SqlContext.Query().Where(x => x.Id > -1)); // Assert Assert.AreEqual(2, totalRecs); @@ -292,18 +303,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlCount = false; } } - } [Test] public void Can_Get_Paged_Results_With_Filter_And_Groups() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); try { @@ -311,7 +321,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlCount = true; // Act - var result = repository.GetPagedResultsByQuery(null, 0, 10, out var totalRecs, user => user.Id, Direction.Ascending, + IEnumerable result = repository.GetPagedResultsByQuery( + null, + 0, + 10, + out long totalRecs, + user => user.Id, + Direction.Ascending, includeUserGroups: new[] { Constants.Security.AdminGroupAlias, Constants.Security.SensitiveDataGroupAlias }, excludeUserGroups: new[] { Constants.Security.TranslatorGroupAlias }, filter: provider.SqlContext.Query().Where(x => x.Id == -1)); @@ -331,25 +347,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Invalidate_SecurityStamp_On_Username_Change() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); - var userGroupRepository = CreateUserGroupRepository(provider); + UserRepository repository = CreateRepository(provider); + UserGroupRepository userGroupRepository = CreateUserGroupRepository(provider); - var user = CreateAndCommitUserWithGroup(repository, userGroupRepository); - var originalSecurityStamp = user.SecurityStamp; + User user = CreateAndCommitUserWithGroup(repository, userGroupRepository); + string originalSecurityStamp = user.SecurityStamp; // Ensure when user generated a security stamp is present Assert.That(user.SecurityStamp, Is.Not.Null); Assert.That(user.SecurityStamp, Is.Not.Empty); // Update username - user.Username = user.Username + "UPDATED"; + user.Username += "UPDATED"; repository.Save(user); // Get the user - var updatedUser = repository.Get(user.Id); + IUser updatedUser = repository.Get(user.Id); // Ensure the Security Stamp is invalidated & no longer the same Assert.AreNotEqual(originalSecurityStamp, updatedUser.SecurityStamp); @@ -360,25 +376,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Validate_Login_Session() { // Arrange - var provider = ScopeProvider; - var user = UserBuilder.CreateUser(); - using (var scope = provider.CreateScope(autoComplete: true)) + IScopeProvider provider = ScopeProvider; + User user = UserBuilder.CreateUser(); + using (IScope scope = provider.CreateScope(autoComplete: true)) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); repository.Save(user); } - using (var scope = provider.CreateScope(autoComplete: true)) + using (IScope scope = provider.CreateScope(autoComplete: true)) { - var repository = CreateRepository(provider); - var sessionId = repository.CreateLoginSession(user.Id, "1.2.3.4"); + UserRepository repository = CreateRepository(provider); + Guid sessionId = repository.CreateLoginSession(user.Id, "1.2.3.4"); // manually update this record to be in the past scope.Database.Execute(scope.SqlContext.Sql() .Update(u => u.Set(x => x.LoggedOutUtc, DateTime.UtcNow.AddDays(-100))) .Where(x => x.SessionId == sessionId)); - var isValid = repository.ValidateLoginSession(user.Id, sessionId); + bool isValid = repository.ValidateLoginSession(user.Id, sessionId); Assert.IsFalse(isValid); // create a new one @@ -391,33 +407,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Update_On_UserRepository() { - var ct = ContentTypeBuilder.CreateBasicContentType("test"); - var mt = MediaTypeBuilder.CreateSimpleMediaType("testmedia", "TestMedia"); + ContentType ct = ContentTypeBuilder.CreateBasicContentType("test"); + MediaType mt = MediaTypeBuilder.CreateSimpleMediaType("testmedia", "TestMedia"); // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope(autoComplete: true)) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope(autoComplete: true)) { - var userRepository = CreateRepository(provider); - var userGroupRepository = CreateUserGroupRepository(provider); + UserRepository userRepository = CreateRepository(provider); + UserGroupRepository userGroupRepository = CreateUserGroupRepository(provider); ContentTypeRepository.Save(ct); MediaTypeRepository.Save(mt); - var content = ContentBuilder.CreateBasicContent(ct); - var media = MediaBuilder.CreateSimpleMedia(mt, "asdf", -1); + Content content = ContentBuilder.CreateBasicContent(ct); + Media media = MediaBuilder.CreateSimpleMedia(mt, "asdf", -1); DocumentRepository.Save(content); MediaRepository.Save(media); - var user = CreateAndCommitUserWithGroup(userRepository, userGroupRepository); + User user = CreateAndCommitUserWithGroup(userRepository, userGroupRepository); // Act - var resolved = (User) userRepository.Get(user.Id); + var resolved = (User)userRepository.Get(user.Id); resolved.Name = "New Name"; - //the db column is not used, default permissions are taken from the user type's permissions, this is a getter only - //resolved.DefaultPermissions = "ZYX"; + + // the db column is not used, default permissions are taken from the user type's permissions, this is a getter only + //// resolved.DefaultPermissions = "ZYX"; + resolved.Language = "fr"; resolved.IsApproved = false; resolved.RawPasswordValue = "new"; @@ -429,7 +447,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor userRepository.Save(resolved); - var updatedItem = (User) userRepository.Get(user.Id); + var updatedItem = (User)userRepository.Get(user.Id); // Assert Assert.That(updatedItem.Id, Is.EqualTo(resolved.Id)); @@ -443,8 +461,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(updatedItem.Email, Is.EqualTo(resolved.Email)); Assert.That(updatedItem.Username, Is.EqualTo(resolved.Username)); Assert.That(updatedItem.AllowedSections.Count(), Is.EqualTo(resolved.AllowedSections.Count())); - foreach (var allowedSection in resolved.AllowedSections) + foreach (string allowedSection in resolved.AllowedSections) + { Assert.IsTrue(updatedItem.AllowedSections.Contains(allowedSection)); + } } } @@ -461,16 +481,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(updatedItem.Email, Is.EqualTo(originalUser.Email)); Assert.That(updatedItem.Username, Is.EqualTo(originalUser.Username)); Assert.That(updatedItem.AllowedSections.Count(), Is.EqualTo(originalUser.AllowedSections.Count())); - foreach (var allowedSection in originalUser.AllowedSections) + foreach (string allowedSection in originalUser.AllowedSections) + { Assert.IsTrue(updatedItem.AllowedSections.Contains(allowedSection)); + } } private User CreateAndCommitUserWithGroup(IUserRepository repository, IUserGroupRepository userGroupRepository) { - var user = UserBuilderInstance.WithoutIdentity().Build(); + User user = UserBuilderInstance.WithoutIdentity().Build(); repository.Save(user); - var group = UserGroupBuilderInstance.Build(); + IUserGroup group = UserGroupBuilderInstance.Build(); userGroupRepository.AddOrUpdateGroupWithUsers(@group, new[] { user.Id }); user.AddGroup(UserGroupBuilderInstance.BuildReadOnly(group)); @@ -480,9 +502,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IUser[] CreateAndCommitMultipleUsers(IUserRepository repository) { - var user1 = UserBuilderInstance.WithoutIdentity().WithSuffix("1").Build(); - var user2 = UserBuilderInstance.WithoutIdentity().WithSuffix("2").Build(); - var user3 = UserBuilderInstance.WithoutIdentity().WithSuffix("3").Build(); + User user1 = UserBuilderInstance.WithoutIdentity().WithSuffix("1").Build(); + User user2 = UserBuilderInstance.WithoutIdentity().WithSuffix("2").Build(); + User user3 = UserBuilderInstance.WithoutIdentity().WithSuffix("3").Build(); repository.Save(user1); repository.Save(user2); repository.Save(user3); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs index f6197e0193..aad6938d18 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -13,10 +17,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void ReadLockNonExisting() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; Assert.Throws(() => { - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { scope.ReadLock(-666); scope.Complete(); @@ -27,8 +31,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void ReadLockExisting() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.ReadLock(Constants.Locks.Servers); scope.Complete(); @@ -38,10 +42,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void WriteLockNonExisting() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; Assert.Throws(() => { - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { scope.WriteLock(-666); scope.Complete(); @@ -52,8 +56,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void WriteLockExisting() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.WriteLock(Constants.Locks.Servers); scope.Complete(); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs index 1c398f681a..3b486b565e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs @@ -1,17 +1,18 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.IO; using System.Text; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Scoping; -using Umbraco.Tests.Testing; using Umbraco.Tests.Integration.Testing; +using Umbraco.Tests.Testing; using FileSystems = Umbraco.Core.IO.FileSystems; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping @@ -21,6 +22,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public class ScopeFileSystemsTests : UmbracoIntegrationTest { private IMediaFileSystem MediaFileSystem => GetRequiredService(); + private IHostingEnvironment HostingEnvironment => GetRequiredService(); [SetUp] @@ -46,19 +48,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping } [Test] - public void test_MediaFileSystem_does_not_write_to_physical_file_system_when_scoped_if_scope_does_not_complete() + public void MediaFileSystem_does_not_write_to_physical_file_system_when_scoped_if_scope_does_not_complete() { - var rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); - var rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); + string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); + string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), rootPath, rootUrl); - var mediaFileSystem = MediaFileSystem; + IMediaFileSystem mediaFileSystem = MediaFileSystem; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); using (ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f1.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); @@ -72,19 +77,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping } [Test] - public void test_MediaFileSystem_writes_to_physical_file_system_when_scoped_and_scope_is_completed() + public void MediaFileSystem_writes_to_physical_file_system_when_scoped_and_scope_is_completed() { - var rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); - var rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); + string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); + string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), rootPath, rootUrl); - var mediaFileSystem = MediaFileSystem; + IMediaFileSystem mediaFileSystem = MediaFileSystem; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); - using (var scope = ScopeProvider.CreateScope(scopeFileSystems: true)) + using (IScope scope = ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f1.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); @@ -102,16 +110,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void MultiThread() { - var rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); - var rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); + string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); + string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), rootPath, rootUrl); - var mediaFileSystem = MediaFileSystem; + IMediaFileSystem mediaFileSystem = MediaFileSystem; - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope(scopeFileSystems: true)) + IScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f1.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); @@ -120,7 +131,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsFalse(mediaFileSystem.FileExists("f1.txt")); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f2.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f2.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f2.txt")); } @@ -133,13 +147,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void SingleShadow() { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope(scopeFileSystems: true)) + IScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (new SafeCallContext()) // not nesting! { // ok to create a 'normal' other scope - using (var other = scopeProvider.CreateScope()) + using (IScope other = scopeProvider.CreateScope()) { other.Complete(); } @@ -148,7 +162,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping // because at the moment we don't support concurrent scoped filesystems Assert.Throws(() => { - var other = scopeProvider.CreateScope(scopeFileSystems: true); + IScope other = scopeProvider.CreateScope(scopeFileSystems: true); }); } } @@ -158,7 +172,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public void SingleShadowEvenDetached() { var scopeProvider = (ScopeProvider)ScopeProvider; - using (var scope = scopeProvider.CreateScope(scopeFileSystems: true)) + using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (new SafeCallContext()) // not nesting! { @@ -167,20 +181,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping // even a detached one Assert.Throws(() => { - var other = scopeProvider.CreateDetachedScope(scopeFileSystems: true); + IScope other = scopeProvider.CreateDetachedScope(scopeFileSystems: true); }); } } - var detached = scopeProvider.CreateDetachedScope(scopeFileSystems: true); + IScope detached = scopeProvider.CreateDetachedScope(scopeFileSystems: true); Assert.IsNull(scopeProvider.AmbientScope); Assert.Throws(() => { // even if there is no ambient scope, there's a single shadow - using (var other = scopeProvider.CreateScope(scopeFileSystems: true)) - { } + using (IScope other = scopeProvider.CreateScope(scopeFileSystems: true)) + { + } }); scopeProvider.AttachScope(detached); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.cs index 85331bb2af..bb3bc99e19 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Persistence; @@ -12,36 +15,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [UmbracoTest(Database = UmbracoTestOptions.Database.NewEmptyPerFixture)] public class ScopeTests : UmbracoIntegrationTest { - private new ScopeProvider ScopeProvider => (ScopeProvider) base.ScopeProvider; + private new ScopeProvider ScopeProvider => (ScopeProvider)base.ScopeProvider; [SetUp] - public void SetUp() - { - Assert.IsNull(ScopeProvider.AmbientScope); // gone - } + public void SetUp() => Assert.IsNull(ScopeProvider.AmbientScope); // gone [Test] public void SimpleCreateScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(ScopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); } + Assert.IsNull(scopeProvider.AmbientScope); } [Test] public void SimpleCreateScopeContext() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -50,6 +51,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); Assert.IsNotNull(scopeProvider.Context); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } @@ -57,12 +59,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void SimpleCreateScopeDatabase() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; IUmbracoDatabase database; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -71,6 +73,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(database); Assert.IsNotNull(database.Connection); // in a transaction } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(database.Connection); // poof gone } @@ -78,15 +81,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedCreateScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -94,51 +97,54 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreSame(scope, ((Scope)nested).ParentScope); } } + Assert.IsNull(scopeProvider.AmbientScope); } [Test] public void NestedMigrateScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); - // only if Core.DEBUG_SCOPES are defined - //Assert.IsEmpty(scopeProvider.CallContextObjects); - using (var nested = scopeProvider.CreateScope(callContext: true)) + // only if Core.DEBUG_SCOPES are defined + //// Assert.IsEmpty(scopeProvider.CallContextObjects); + + using (IScope nested = scopeProvider.CreateScope(callContext: true)) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); // it's moved over to call context - var callContextScope = CallContext.GetData(ScopeProvider.ScopeItemKey); + IScope callContextScope = CallContext.GetData(ScopeProvider.ScopeItemKey); Assert.IsNotNull(callContextScope); // only if Core.DEBUG_SCOPES are defined - //var ccnested = scopeProvider.CallContextObjects[callContextKey]; - //Assert.AreSame(nested, ccnested); + // var ccnested = scopeProvider.CallContextObjects[callContextKey]; + // Assert.AreSame(nested, ccnested); } // it's naturally back in http context } + Assert.IsNull(scopeProvider.AmbientScope); } [Test] public void NestedCreateScopeContext() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -146,12 +152,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); IScopeContext context; - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); Assert.IsNotNull(scopeProvider.Context); Assert.IsNotNull(scopeProvider.AmbientContext); @@ -161,6 +167,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); Assert.AreSame(context, scopeProvider.AmbientContext); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } @@ -168,37 +175,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedCreateScopeInnerException() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? scopeCompleted = null; Assert.IsNull(scopeProvider.AmbientScope); try { - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scopeProvider.Context.Enlist("test", completed => scopeCompleted = completed); Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); nested.Complete(); throw new Exception("bang!"); } + scope.Complete(); } + Assert.Fail("Expected exception."); } catch (Exception e) { if (e.Message != "bang!") + { Assert.Fail("Wrong exception."); + } } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNotNull(scopeCompleted); Assert.IsFalse(scopeCompleted.Value); @@ -207,12 +219,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedCreateScopeDatabase() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; IUmbracoDatabase database; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -220,16 +232,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping database = scope.Database; // populates scope's database Assert.IsNotNull(database); Assert.IsNotNull(database.Connection); // in a transaction - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); Assert.AreSame(database, nested.Database); } + Assert.IsNotNull(database.Connection); // still } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(database.Connection); // poof gone } @@ -237,36 +251,36 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void Transaction() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("CREATE TABLE tmp3 (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp3 (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); Assert.AreEqual("a", n); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); Assert.IsNull(n); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp3 (id, name) VALUES (1, 'a')"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); Assert.AreEqual("a", n); } } @@ -274,24 +288,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedTransactionInnerFail() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute($"CREATE TABLE tmp1 (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp1 (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); Assert.AreEqual("a", n); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { nested.Database.Execute("INSERT INTO tmp1 (id, name) VALUES (2, 'b')"); - var nn = nested.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=2"); + string nn = nested.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=2"); Assert.AreEqual("b", nn); } @@ -301,9 +315,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); Assert.IsNull(n); n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=2"); Assert.IsNull(n); @@ -313,24 +327,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedTransactionOuterFail() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("CREATE TABLE tmp2 (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp2 (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); Assert.AreEqual("a", n); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { nested.Database.Execute("INSERT INTO tmp2 (id, name) VALUES (2, 'b')"); - var nn = nested.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=2"); + string nn = nested.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=2"); Assert.AreEqual("b", nn); nested.Complete(); } @@ -339,9 +353,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual("b", n); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); Assert.IsNull(n); n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=2"); Assert.IsNull(n); @@ -351,24 +365,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedTransactionComplete() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("CREATE TABLE tmp (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); Assert.AreEqual("a", n); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { nested.Database.Execute("INSERT INTO tmp (id, name) VALUES (2, 'b')"); - var nn = nested.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=2"); + string nn = nested.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=2"); Assert.AreEqual("b", nn); nested.Complete(); } @@ -378,9 +392,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); Assert.AreEqual("a", n); n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=2"); Assert.AreEqual("b", n); @@ -390,8 +404,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void CallContextScope1() { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + ScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNotNull(scopeProvider.AmbientContext); @@ -400,7 +414,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); - using (var newScope = scopeProvider.CreateScope()) + using (IScope newScope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientScope.ParentScope); @@ -410,6 +424,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } + Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); } @@ -421,10 +436,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void CallContextScope2() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNotNull(scopeProvider.AmbientContext); @@ -433,7 +448,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); - using (var newScope = scopeProvider.CreateScope()) + using (IScope newScope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientScope.ParentScope); @@ -443,33 +458,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } + Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); } Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); - - } [Test] public void ScopeReference() { - var scopeProvider = ScopeProvider; - var scope = scopeProvider.CreateScope(); - var nested = scopeProvider.CreateScope(); + ScopeProvider scopeProvider = ScopeProvider; + IScope scope = scopeProvider.CreateScope(); + IScope nested = scopeProvider.CreateScope(); Assert.IsNotNull(scopeProvider.AmbientScope); var scopeRef = new ScopeReference(scopeProvider); scopeRef.Dispose(); Assert.IsNull(scopeProvider.AmbientScope); Assert.Throws(() => { - var db = scope.Database; + IUmbracoDatabase db = scope.Database; }); Assert.Throws(() => { - var db = nested.Database; + IUmbracoDatabase db = nested.Database; }); } @@ -477,14 +491,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [TestCase(false)] public void ScopeContextEnlist(bool complete) { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? completed = null; IScope ambientScope = null; IScopeContext ambientContext = null; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scopeProvider.Context.Enlist("name", c => { @@ -493,8 +507,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping ambientContext = scopeProvider.AmbientContext; }); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); Assert.IsNotNull(completed); @@ -507,66 +524,61 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [TestCase(false)] public void ScopeContextEnlistAgain(bool complete) { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? completed = null; bool? completed2 = null; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scopeProvider.Context.Enlist("name", c => { completed = c; // at that point the scope is gone, but the context is still there - var ambientContext = scopeProvider.AmbientContext; - ambientContext.Enlist("another", c2 => { completed2 = c2; }); + IScopeContext ambientContext = scopeProvider.AmbientContext; + ambientContext.Enlist("another", c2 => completed2 = c2); }); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); Assert.IsNotNull(completed); - Assert.AreEqual(complete,completed.Value); + Assert.AreEqual(complete, completed.Value); Assert.AreEqual(complete, completed2.Value); } [Test] public void ScopeContextException() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? completed = null; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var detached = scopeProvider.CreateDetachedScope(); + IScope detached = scopeProvider.CreateDetachedScope(); scopeProvider.AttachScope(detached); + // the exception does not prevent other enlisted items to run // *and* it does not prevent the scope from properly going down - scopeProvider.Context.Enlist("name", c => - { - throw new Exception("bang"); - }); - scopeProvider.Context.Enlist("other", c => - { - completed = c; - }); + scopeProvider.Context.Enlist("name", c => throw new Exception("bang")); + scopeProvider.Context.Enlist("other", c => completed = c); detached.Complete(); - Assert.Throws(() => - { - detached.Dispose(); - }); + Assert.Throws(() => detached.Dispose()); // even though disposing of the scope has thrown, it has exited // properly ie it has removed itself, and the app remains clean - Assert.AreSame(scope, scopeProvider.AmbientScope); scope.Complete(); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); @@ -577,10 +589,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void DetachableScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -588,22 +600,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); // the ambient context Assert.IsNotNull(scopeProvider.Context); // the ambient context too (getter only) - var context = scopeProvider.Context; + IScopeContext context = scopeProvider.Context; - var detached = scopeProvider.CreateDetachedScope(); + IScope detached = scopeProvider.CreateDetachedScope(); scopeProvider.AttachScope(detached); Assert.AreEqual(detached, scopeProvider.AmbientScope); Assert.AreNotSame(context, scopeProvider.Context); // nesting under detached! - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.Throws(() => - { + // cannot detach a non-detachable scope - scopeProvider.DetachScope(); - }); + scopeProvider.DetachScope()); nested.Complete(); } @@ -617,21 +628,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreSame(context, scopeProvider.AmbientContext); Assert.Throws(() => - { + // cannot disposed a non-attached scope // in fact, only the ambient scope can be disposed - detached.Dispose(); - }); + detached.Dispose()); scopeProvider.AttachScope(detached); detached.Complete(); detached.Dispose(); // has self-detached, and is gone! - Assert.AreSame(scope, scopeProvider.AmbientScope); Assert.AreSame(context, scopeProvider.AmbientContext); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs index 0a1e46274b..051ffa0a24 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs @@ -1,4 +1,6 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; @@ -29,7 +31,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping private ILocalizationService LocalizationService => GetRequiredService(); private IServerMessenger ServerMessenger { get; } = new LocalServerMessenger(); - private CacheRefresherCollection CacheRefresherCollection => GetRequiredService(); protected override AppCaches GetAppCaches() @@ -56,12 +57,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping { var scopeProvider = (ScopeProvider)ScopeProvider; var service = (UserService)UserService; - var globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IUser)); + IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IUser)); var user = (IUser)new User(GlobalSettings, "name", "email", "username", "rawPassword"); service.Save(user); // global cache contains the entity - var globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + var globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); @@ -73,37 +74,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping _distributedCacheBinder.BindEvents(true); Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) + using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IUser)); + IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(IUser)); Assert.AreNotSame(globalCache, scopedCache); user.Name = "changed"; service.Save(user); // scoped cache contains the "new" entity - var scopeCached = (IUser) scopedCache.Get(GetCacheIdKey(user.Id), () => null); + var scopeCached = (IUser)scopedCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(user.Id, scopeCached.Id); Assert.AreEqual("changed", scopeCached.Name); // global cache is unchanged - globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); if (complete) { // global cache has been cleared @@ -120,7 +124,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(complete ? "changed" : "name", user.Name); // global cache contains the entity again - globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual(complete ? "changed" : "name", globalCached.Name); @@ -131,21 +135,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public void FullDataSetRepositoryCachePolicy(bool complete) { var scopeProvider = (ScopeProvider)ScopeProvider; - var service = LocalizationService; - var globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof (ILanguage)); + ILocalizationService service = LocalizationService; + IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(ILanguage)); - var lang = (ILanguage) new Language(GlobalSettings, "fr-FR"); + var lang = (ILanguage)new Language(GlobalSettings, "fr-FR"); service.Save(lang); // global cache has been flushed, reload - var globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + var globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(globalFullCached); - var reload = service.GetLanguageById(lang.Id); + ILanguage reload = service.GetLanguageById(lang.Id); // global cache contains the entity - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); - var globalCached = globalFullCached.First(x => x.Id == lang.Id); + ILanguage globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); Assert.AreEqual(lang.Id, globalCached.Id); Assert.AreEqual("fr-FR", globalCached.IsoCode); @@ -154,35 +158,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping _distributedCacheBinder.BindEvents(true); Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) + using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (ILanguage)); + IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(ILanguage)); Assert.AreNotSame(globalCache, scopedCache); - //Use IsMandatory of isocode to ensure publishedContent cache is not also rebuild + // Use IsMandatory of isocode to ensure publishedContent cache is not also rebuild lang.IsMandatory = true; service.Save(lang); // scoped cache has been flushed, reload - var scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); + var scopeFullCached = (IEnumerable)scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(scopeFullCached); reload = service.GetLanguageById(lang.Id); // scoped cache contains the "new" entity - scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); + scopeFullCached = (IEnumerable)scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(scopeFullCached); - var scopeCached = scopeFullCached.First(x => x.Id == lang.Id); + ILanguage scopeCached = scopeFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(scopeCached); Assert.AreEqual(lang.Id, scopeCached.Id); Assert.AreEqual(true, scopeCached.IsMandatory); // global cache is unchanged - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -190,11 +194,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(false, globalCached.IsMandatory); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); if (complete) { // global cache has been cleared @@ -211,7 +218,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(complete ? true : false, lang.IsMandatory); // global cache contains the entity again - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -224,13 +231,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public void SingleItemsOnlyRepositoryCachePolicy(bool complete) { var scopeProvider = (ScopeProvider)ScopeProvider; - var service = LocalizationService; - var globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); + ILocalizationService service = LocalizationService; + IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IDictionaryItem)); var lang = (ILanguage)new Language(GlobalSettings, "fr-FR"); service.Save(lang); - var item = (IDictionaryItem) new DictionaryItem("item-key"); + var item = (IDictionaryItem)new DictionaryItem("item-key"); item.Translations = new IDictionaryTranslation[] { new DictionaryTranslation(lang.Id, "item-value"), @@ -238,7 +245,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping service.Save(item); // global cache contains the entity - var globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + var globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); @@ -247,37 +254,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping _distributedCacheBinder.BindEvents(true); Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) + using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); + IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(IDictionaryItem)); Assert.AreNotSame(globalCache, scopedCache); item.ItemKey = "item-changed"; service.Save(item); // scoped cache contains the "new" entity - var scopeCached = (IDictionaryItem) scopedCache.Get(GetCacheIdKey(item.Id), () => null); + var scopeCached = (IDictionaryItem)scopedCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(item.Id, scopeCached.Id); Assert.AreEqual("item-changed", scopeCached.ItemKey); // global cache is unchanged - globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); if (complete) { // global cache has been cleared @@ -294,27 +304,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(complete ? "item-changed" : "item-key", item.ItemKey); // global cache contains the entity again - globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual(complete ? "item-changed" : "item-key", globalCached.ItemKey); } - public static string GetCacheIdKey(object id) - { - return $"{GetCacheTypeKey()}{id}"; - } + public static string GetCacheIdKey(object id) => $"{GetCacheTypeKey()}{id}"; - public static string GetCacheTypeKey() - { - return $"uRepo_{typeof (T).Name}_"; - } + public static string GetCacheTypeKey() => $"uRepo_{typeof(T).Name}_"; public class PassiveEventDispatcher : QueuingEventDispatcherBase { public PassiveEventDispatcher() : base(false) - { } + { + } protected override void ScopeExitCompleted() { @@ -334,7 +339,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) { - throw new NotImplementedException(); } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs index d7385a7acf..6260d8adbb 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; @@ -18,24 +21,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void GetPage() { - var sut = (AuditService) GetRequiredService(); - var expected = new AuditEntryBuilder().Build(); + var sut = (AuditService)GetRequiredService(); + IAuditEntry expected = new AuditEntryBuilder().Build(); - - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { sut.Write( expected.PerformingUserId + i, expected.PerformingDetails, expected.PerformingIp, expected.EventDateUtc.AddMinutes(i), - expected.AffectedUserId+ i, + expected.AffectedUserId + i, expected.AffectedDetails, expected.EventType, expected.EventDetails); } - var entries = sut.GetPage(2, 2, out var count).ToArray(); + IAuditEntry[] entries = sut.GetPage(2, 2, out long count).ToArray(); Assert.Multiple(() => { @@ -48,20 +50,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void GetUserLogs() { - var sut = (AuditService) Services.GetRequiredService(); + var sut = (AuditService)Services.GetRequiredService(); - var eventDateUtc = DateTime.UtcNow.AddDays(-1); + DateTime eventDateUtc = DateTime.UtcNow.AddDays(-1); - var numberOfEntries = 10; - for (var i = 0; i < numberOfEntries; i++) + int numberOfEntries = 10; + for (int i = 0; i < numberOfEntries; i++) { eventDateUtc = eventDateUtc.AddMinutes(1); - sut.Add(AuditType.Unpublish, -1, 33, "", "blah"); + sut.Add(AuditType.Unpublish, -1, 33, string.Empty, "blah"); } - sut.Add(AuditType.Publish, -1, 33, "", "blah"); + sut.Add(AuditType.Publish, -1, 33, string.Empty, "blah"); - var logs = sut.GetUserLogs(-1, AuditType.Unpublish).ToArray(); + IAuditItem[] logs = sut.GetUserLogs(-1, AuditType.Unpublish).ToArray(); Assert.Multiple(() => { @@ -75,10 +77,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Write_and_GetAll() { - var sut = (AuditService) Services.GetRequiredService(); - var expected = new AuditEntryBuilder().Build(); + var sut = (AuditService)Services.GetRequiredService(); + IAuditEntry expected = new AuditEntryBuilder().Build(); - var actual = sut.Write( + IAuditEntry actual = sut.Write( expected.PerformingUserId, expected.PerformingDetails, expected.PerformingIp, @@ -88,7 +90,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services expected.EventType, expected.EventDetails); - var entries = sut.GetAll().ToArray(); + IAuditEntry[] entries = sut.GetAll().ToArray(); Assert.Multiple(() => { diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs index 3c03be2a95..c57eac686b 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs @@ -1,4 +1,8 @@ -using System.Threading; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Threading; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; @@ -18,9 +22,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class CachedDataTypeServiceTests : UmbracoIntegrationTest { private IDataTypeService DataTypeService => GetRequiredService(); + private ILocalizedTextService LocalizedTextService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); /// @@ -33,9 +41,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IDataType dataType = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = "Testing Textfield", DatabaseType = ValueStorageType.Ntext }; DataTypeService.Save(dataType); - //Get all the first time (no cache) - var all = DataTypeService.GetAll(); - //Get all a second time (with cache) + // Get all the first time (no cache) + IEnumerable all = DataTypeService.GetAll(); + + // Get all a second time (with cache) all = DataTypeService.GetAll(); Assert.Pass(); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs index 905697159d..c489fe68af 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using NUnit.Framework; using Umbraco.Core.Models; @@ -18,8 +21,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void CanCrudConsent() { // can register - - var consent = ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Granted, "no comment"); + IConsent consent = ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Granted, "no comment"); Assert.AreNotEqual(0, consent.Id); Assert.IsTrue(consent.Current); @@ -32,14 +34,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consent.IsGranted()); // can register more - ConsentService.RegisterConsent("user/1234", "app1", "do-something-else", ConsentState.Granted, "no comment"); ConsentService.RegisterConsent("user/1236", "app1", "do-something", ConsentState.Granted, "no comment"); ConsentService.RegisterConsent("user/1237", "app2", "do-something", ConsentState.Granted, "no comment"); // can get by source - - var consents = ConsentService.LookupConsent(source: "user/1235").ToArray(); + IConsent[] consents = ConsentService.LookupConsent(source: "user/1235").ToArray(); Assert.IsEmpty(consents); consents = ConsentService.LookupConsent(source: "user/1234").ToArray(); @@ -49,7 +49,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consents.Any(x => x.Action == "do-something-else")); // can get by context - consents = ConsentService.LookupConsent(context: "app3").ToArray(); Assert.IsEmpty(consents); @@ -62,7 +61,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consents.Any(x => x.Action == "do-something-else")); // can get by action - consents = ConsentService.LookupConsent(action: "do-whatever").ToArray(); Assert.IsEmpty(consents); @@ -73,7 +71,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consents.Any(x => x.Source == "user/1236")); // can revoke - consent = ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Revoked, "no comment"); consents = ConsentService.LookupConsent(source: "user/1234", context: "app1", action: "do-something").ToArray(); @@ -82,27 +79,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(ConsentState.Revoked, consents[0].State); // can filter - consents = ConsentService.LookupConsent(context: "app1", action: "do-", actionStartsWith: true).ToArray(); Assert.AreEqual(3, consents.Length); Assert.IsTrue(consents.All(x => x.Context == "app1")); Assert.IsTrue(consents.All(x => x.Action.StartsWith("do-"))); // can get history - consents = ConsentService.LookupConsent(source: "user/1234", context: "app1", action: "do-something", includeHistory: true).ToArray(); Assert.AreEqual(1, consents.Length); Assert.IsTrue(consents[0].Current); Assert.AreEqual(ConsentState.Revoked, consents[0].State); Assert.IsTrue(consents[0].IsRevoked()); Assert.IsNotNull(consents[0].History); - var history = consents[0].History.ToArray(); + IConsent[] history = consents[0].History.ToArray(); Assert.AreEqual(1, history.Length); Assert.IsFalse(history[0].Current); Assert.AreEqual(ConsentState.Granted, history[0].State); // cannot be stupid - Assert.Throws(() => ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Granted | ConsentState.Revoked, "no comment")); } @@ -114,7 +108,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ConsentService.RegisterConsent("user/1234", "app1", "consentWithoutComment", ConsentState.Granted); // Attempt to retrieve the consent we just added without a comment - var consents = ConsentService.LookupConsent(source: "user/1234", action: "consentWithoutComment").ToArray(); + IConsent[] consents = ConsentService.LookupConsent(source: "user/1234", action: "consentWithoutComment").ToArray(); // Confirm we got our expected consent record Assert.AreEqual(1, consents.Length); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs index 68ec7fcf5f..aaaa73416f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs @@ -1,3 +1,8 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + +#pragma warning disable SA1124 // Do not use regions (justification: regions are currently adding some useful organisation to this file) + using System; using System.Collections.Generic; using System.Linq; @@ -31,8 +36,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [SetUp] public void SetUp() { - _h1 = new DistributedCacheBinder(new DistributedCache(new LocalServerMessenger(), CacheRefresherCollection), UmbracoContextFactory, GetRequiredService>()); - _h1.BindEvents(true); + _distributedCacheBinder = new DistributedCacheBinder(new DistributedCache(new LocalServerMessenger(), CacheRefresherCollection), UmbracoContextFactory, GetRequiredService>()); + _distributedCacheBinder.BindEvents(true); _events = new List(); @@ -42,7 +47,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentCacheRefresher.CacheUpdated += ContentCacheUpdated; // prepare content type - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); _contentType = ContentTypeBuilder.CreateSimpleContentType("whatever", "Whatever", defaultTemplateId: template.Id); @@ -54,17 +59,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TearDown] public void TearDownTest() { - _h1?.UnbindEvents(); - - // clear ALL events + _distributedCacheBinder?.UnbindEvents(); + // Clear ALL events DocumentRepository.ScopedEntityRefresh -= ContentRepositoryRefreshed; DocumentRepository.ScopeEntityRemove -= ContentRepositoryRemoved; DocumentRepository.ScopeVersionRemove -= ContentRepositoryRemovedVersion; ContentCacheRefresher.CacheUpdated -= ContentCacheUpdated; } - private DistributedCacheBinder _h1; + private DistributedCacheBinder _distributedCacheBinder; private IList _events; private int _msgCount; private IContentType _contentType; @@ -78,56 +82,56 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private IContent CreateContent(int parentId = -1) { - var content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1", parentId); + Content content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1", parentId); ContentService.Save(content1); return content1; } private IContent CreateBranch() { - var content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1"); + Content content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1"); ContentService.SaveAndPublish(content1); // 2 (published) // .1 (published) // .2 (not published) - var content2 = ContentBuilder.CreateSimpleContent(_contentType, "Content2", content1); + Content content2 = ContentBuilder.CreateSimpleContent(_contentType, "Content2", content1); ContentService.SaveAndPublish(content2); - var content21 = ContentBuilder.CreateSimpleContent(_contentType, "Content21", content2); + Content content21 = ContentBuilder.CreateSimpleContent(_contentType, "Content21", content2); ContentService.SaveAndPublish(content21); - var content22 = ContentBuilder.CreateSimpleContent(_contentType, "Content22", content2); + Content content22 = ContentBuilder.CreateSimpleContent(_contentType, "Content22", content2); ContentService.Save(content22); // 3 (not published) // .1 (not published) // .2 (not published) - var content3 = ContentBuilder.CreateSimpleContent(_contentType, "Content3", content1); + Content content3 = ContentBuilder.CreateSimpleContent(_contentType, "Content3", content1); ContentService.Save(content3); - var content31 = ContentBuilder.CreateSimpleContent(_contentType, "Content31", content3); + Content content31 = ContentBuilder.CreateSimpleContent(_contentType, "Content31", content3); ContentService.Save(content31); - var content32 = ContentBuilder.CreateSimpleContent(_contentType, "Content32", content3); + Content content32 = ContentBuilder.CreateSimpleContent(_contentType, "Content32", content3); ContentService.Save(content32); // 4 (published + saved) // .1 (published) // .2 (not published) - var content4 = ContentBuilder.CreateSimpleContent(_contentType, "Content4", content1); + Content content4 = ContentBuilder.CreateSimpleContent(_contentType, "Content4", content1); ContentService.SaveAndPublish(content4); content4.Name = "Content4X"; ContentService.Save(content4); - var content41 = ContentBuilder.CreateSimpleContent(_contentType, "Content41", content4); + Content content41 = ContentBuilder.CreateSimpleContent(_contentType, "Content41", content4); ContentService.SaveAndPublish(content41); - var content42 = ContentBuilder.CreateSimpleContent(_contentType, "Content42", content4); + Content content42 = ContentBuilder.CreateSimpleContent(_contentType, "Content42", content4); ContentService.Save(content42); // 5 (not published) // .1 (published) // .2 (not published) - var content5 = ContentBuilder.CreateSimpleContent(_contentType, "Content5", content1); + Content content5 = ContentBuilder.CreateSimpleContent(_contentType, "Content5", content1); ContentService.SaveAndPublish(content5); - var content51 = ContentBuilder.CreateSimpleContent(_contentType, "Content51", content5); + Content content51 = ContentBuilder.CreateSimpleContent(_contentType, "Content51", content5); ContentService.SaveAndPublish(content51); - var content52 = ContentBuilder.CreateSimpleContent(_contentType, "Content52", content5); + Content content52 = ContentBuilder.CreateSimpleContent(_contentType, "Content52", content5); ContentService.Save(content52); ContentService.Unpublish(content5); @@ -141,29 +145,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CreatedBranchIsOk() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); - var children1 = Children(content1).ToArray(); + IContent[] children1 = Children(content1).ToArray(); - var content2 = children1[0]; - var children2 = Children(content2).ToArray(); - var content21 = children2[0]; - var content22 = children2[1]; + IContent content2 = children1[0]; + IContent[] children2 = Children(content2).ToArray(); + IContent content21 = children2[0]; + IContent content22 = children2[1]; - var content3 = children1[1]; - var children3 = Children(content3).ToArray(); - var content31 = children3[0]; - var content32 = children3[1]; + IContent content3 = children1[1]; + IContent[] children3 = Children(content3).ToArray(); + IContent content31 = children3[0]; + IContent content32 = children3[1]; - var content4 = children1[2]; - var children4 = Children(content4).ToArray(); - var content41 = children4[0]; - var content42 = children4[1]; + IContent content4 = children1[2]; + IContent[] children4 = Children(content4).ToArray(); + IContent content41 = children4[0]; + IContent content42 = children4[1]; - var content5 = children1[3]; - var children5 = Children(content5).ToArray(); - var content51 = children5[0]; - var content52 = children5[1]; + IContent content5 = children1[3]; + IContent[] children5 = Children(content5).ToArray(); + IContent content51 = children5[0]; + IContent content52 = children5[1]; Assert.IsTrue(content1.Published); Assert.IsFalse(content1.Edited); @@ -203,23 +207,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private class EventInstance { - // ReSharper disable MemberCanBePrivate.Local - // ReSharper disable UnusedAutoPropertyAccessor.Local public int Message { get; set; } - public string Sender { get; set; } - public string Name { get; set; } - public string Args { get; set; } - public object EventArgs { get; set; } - // ReSharper restore MemberCanBePrivate.Local - // ReSharper restore UnusedAutoPropertyAccessor.Local - public override string ToString() - { - return $"{Message:000}: {Sender.Replace(" ", "")}/{Name}/{Args}"; - } + public string Sender { get; set; } + + public string Name { get; set; } + + public string Args { get; set; } + + public object EventArgs { get; set; } + + public override string ToString() => $"{Message:000}: {Sender.Replace(" ", string.Empty)}/{Name}/{Args}"; } - private static readonly string[] PropertiesImpactingAllVersions = { "SortOrder", "ParentId", "Level", "Path", "Trashed" }; + private static readonly string[] s_propertiesImpactingAllVersions = { "SortOrder", "ParentId", "Level", "Path", "Trashed" }; private static bool HasChangesImpactingAllVersions(IContent icontent) { @@ -228,10 +229,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // UpdateDate will be dirty // Published may be dirty if saving a Published entity // so cannot do this (would always be true): - //return content.IsEntityDirty(); + ////return content.IsEntityDirty(); // have to be more precise & specify properties - return PropertiesImpactingAllVersions.Any(content.IsPropertyDirty); + return s_propertiesImpactingAllVersions.Any(content.IsPropertyDirty); } private void ContentRepositoryRefreshed(DocumentRepository sender, DocumentRepository.ScopedEntityEventArgs args) @@ -256,8 +257,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // x is u|p and is the (un)published state of the event content // y is +|-|= and is the action (publish, unpublish, no change) // z is u|p|m and is the (un)published state after the event - - var entities = new[] { args.Entity }; // args.Entities + IContent[] entities = new[] { args.Entity }; // args.Entities var e = new EventInstance { @@ -266,95 +266,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Name = "Refresh", Args = string.Join(",", entities.Select(x => { - var publishedState = ((Content) x).PublishedState; + PublishedState publishedState = ((Content)x).PublishedState; - var xstate = x.Published ? "p" : "u"; + string xstate = x.Published ? "p" : "u"; if (publishedState == PublishedState.Publishing) - xstate += "+" + (x.ParentId == - 1 || sender.IsPathPublished(sender.Get(x.ParentId)) ? "p" : "m"); + { + xstate += "+" + (x.ParentId == -1 || sender.IsPathPublished(sender.Get(x.ParentId)) ? "p" : "m"); + } else if (publishedState == PublishedState.Unpublishing) + { xstate += "-u"; + } else + { xstate += "=" + (x.Published ? (sender.IsPathPublished(x) ? "p" : "m") : "u"); + } return $"{x.Id}.{xstate}"; - - - var willBePublished = publishedState == PublishedState.Publishing || x.Published; // && ((Content) x).PublishedState == PublishedState.Unpublishing; - - // saved content - var state = willBePublished ? "p" : "u"; - - if (publishedState == PublishedState.Publishing) - { - // content is published and x is the published version - // figure out whether it is masked or not - what to do exactly in each case - // would depend on the handler implementation - ie is it still updating - // data for masked version or not - var isPathPublished = sender.IsPathPublished(x); // expensive! - if (isPathPublished) - state += "p"; // refresh (using x) - else - state += "m"; // masked - } - else if (publishedState == PublishedState.Unpublishing) - { - // unpublishing content, clear - // handlers would probably clear data - state += "x"; - } - else if (publishedState == PublishedState.Published) - { - var isPathPublished = sender.IsPathPublished(x); // expensive! - if (isPathPublished == false) - state += "m"; // masked - else if (HasChangesImpactingAllVersions(x)) - state += "p"; // refresh (using published = sender.GetByVersion(x.PublishedVersionGuid)) - else - state += "u"; // no impact on published version - } - else // Unpublished - { - state += "u"; // no published version - } - - //// published version - //if (x.Published == false) - //{ - // // x is not a published version - - // // unpublishing content, clear - // // handlers would probably clear data - // if (((Content)x).PublishedState == PublishedState.Unpublishing) - // { - // state += "x"; - // } - // else if (x.Published) - // { - // var isPathPublished = sender.IsPathPublished(x); // expensive! - // if (isPathPublished == false) - // state += "m"; // masked - // else if (HasChangesImpactingAllVersions(x)) - // state += "p"; // refresh (using published = sender.GetByVersion(x.PublishedVersionGuid)) - // else - // state += "u"; // no impact on published version - // } - // else - // state += "u"; // no published version - //} - //else - //{ - // // content is published and x is the published version - // // figure out whether it is masked or not - what to do exactly in each case - // // would depend on the handler implementation - ie is it still updating - // // data for masked version or not - // var isPathPublished = sender.IsPathPublished(x); // expensive! - // if (isPathPublished) - // state += "p"; // refresh (using x) - // else - // state += "m"; // masked - //} - - return $"{state}-{x.Id}"; })) }; _events.Add(e); @@ -365,8 +293,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // reports the event as : "ContentRepository/Remove/X" // where // X is the event content ID - - var entities = new[] { args.Entity }; // args.Entities + IContent[] entities = new[] { args.Entity }; // args.Entities var e = new EventInstance { @@ -374,7 +301,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Sender = "ContentRepository", EventArgs = args, Name = "Remove", - //Args = string.Join(",", args.Entities.Select(x => (x.Published ? "p" : "u") + x.Id)) Args = string.Join(",", entities.Select(x => x.Id)) }; _events.Add(e); @@ -386,14 +312,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // where // X is the event content ID // Y is the event content version GUID - var e = new EventInstance { Message = _msgCount++, Sender = "ContentRepository", EventArgs = args, Name = "RemoveVersion", - //Args = string.Join(",", args.Versions.Select(x => string.Format("{0}:{1}", x.Item1, x.Item2))) Args = $"{args.EntityId}:{args.VersionId}" }; _events.Add(e); @@ -405,18 +329,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // where // is(are) the action(s) // X is the event content ID - if (args.MessageType != MessageType.RefreshByPayload) + { throw new NotSupportedException(); + } - foreach (var payload in (ContentCacheRefresher.JsonPayload[]) args.MessageObject) + foreach (ContentCacheRefresher.JsonPayload payload in (ContentCacheRefresher.JsonPayload[])args.MessageObject) { var e = new EventInstance { Message = _msgCount, Sender = sender.Name, EventArgs = payload, - Name = payload.ChangeTypes.ToString().Replace(" ", ""), + Name = payload.ChangeTypes.ToString().Replace(" ", string.Empty), Args = payload.Id.ToInvariantString() }; _events.Add(e); @@ -428,8 +353,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void WriteEvents() { Console.WriteLine("EVENTS"); - foreach (var e in _events) + foreach (EventInstance e in _events) + { Console.WriteLine(e); + } } #endregion @@ -437,7 +364,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services #region Utils private IEnumerable Children(IContent content) - => ContentService.GetPagedChildren(content.Id, 0, int.MaxValue, out var total); + => ContentService.GetPagedChildren(content.Id, 0, int.MaxValue, out long total); #endregion @@ -449,8 +376,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh u=u // - content cache : refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ResetEvents(); @@ -459,8 +385,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -472,8 +398,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh (u) // - content cache :: refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -483,8 +408,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -508,8 +433,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh (u) // - content cache :: refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -519,8 +443,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -544,8 +468,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh (u) // - content cache :: refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -555,8 +478,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -580,8 +503,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved&published, // - repository : refresh (p) // - content cache :: refresh published, newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ResetEvents(); @@ -590,8 +512,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i++].ToString()); @@ -603,8 +525,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved&published, // - repository : refresh (p) // - content cache :: refresh published, newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -614,8 +535,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i++].ToString()); @@ -630,8 +551,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // note: whenever the published cache is refreshed, subscribers must // assume that the unpublished cache is also refreshed, with the same // values, and deal with it. - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ResetEvents(); @@ -640,8 +560,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i++].ToString()); @@ -653,8 +573,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is unpublished, // - repository : refresh (u) // - content cache :: refresh newest, remove published - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -663,8 +582,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p-u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); @@ -676,8 +595,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is unpublished, // - repository : refresh (u) // - content cache :: refresh newest, remove published - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); content.Name = "changed"; @@ -688,12 +606,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p-u", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content.Id), _events[i++].ToString()); - //Assert.AreEqual("changed", ContentService.GetById(((ContentCacheRefresher.JsonPayload)_events[i - 1].EventArgs).Id).Name); + ////Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content.Id), _events[i++].ToString()); + ////Assert.AreEqual("changed", ContentService.GetById(((ContentCacheRefresher.JsonPayload)_events[i - 1].EventArgs).Id).Name); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); } @@ -712,19 +630,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // the whole branch by themselves. Examine does it in UmbracoContentIndexer, // content caches have to do it too... wondering whether we should instead // trigger RemovePublished for all of the removed content? - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ResetEvents(); ContentService.Unpublish(content1); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p-u", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1.Id), _events[i++].ToString()); + ////Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1.Id), _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); } @@ -734,8 +651,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content branch is published, // - repository :: refresh root (p) // - published page cache :: refresh root & descendants, database (level, sortOrder) order - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ContentService.Unpublish(content1); ResetEvents(); @@ -743,8 +659,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); // repub content1 @@ -766,77 +682,82 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void PublishContentBranchWithPublishedChildren() { // rule? - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ContentService.Unpublish(content1); // branch is: - ResetEvents(); ContentService.SaveAndPublishBranch(content1, force: false); // force = false, don't publish unpublished items - foreach (var e in _events) + foreach (EventInstance e in _events) + { Console.WriteLine(e); + } Assert.AreEqual(3, _msgCount); Assert.AreEqual(3, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); // force:false => only republish the root node + nodes that are edited +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.u+p", _events[i++].ToString()); // content1 was unpublished, now published // change: only content4 shows here, because it has changes - others don't need to be published - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); // content1/content2 + ////Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); // content1/content2 Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[2].Id}.p+p", _events[i++].ToString()); // content1/content4 - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); // content1/content2/content21 - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); // content1/content4/content41 - + ////Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); // content1/content2/content21 + ////Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); // content1/content4/content41 Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); // repub content1 +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void PublishContentBranchWithAllChildren() { // rule? - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ContentService.Unpublish(content1); ResetEvents(); ContentService.SaveAndPublishBranch(content1, force: true); // force = true, also publish unpublished items - foreach (var e in _events) + foreach (EventInstance e in _events) + { Console.WriteLine(e); + } Assert.AreEqual(10, _msgCount); Assert.AreEqual(10, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); + +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. // force:true => all nodes are republished, refreshing all nodes - but only with changes - published w/out changes are not repub Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.u+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); + ////Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); + ////Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content3C[0].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content3C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[2].Id}.p+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); + ////Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[3].Id}.u+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content5C[0].Id}.p+p", _events[i++].ToString()); + ////Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content5C[0].Id}.p+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content5C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); // repub content1 +#pragma warning restore SA1003 // Symbols should be spaced correctly } #endregion @@ -847,16 +768,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void SortAll() { // rule: ? - - var content1 = CreateBranch(); - var content1C = Children(content1).ToArray(); + IContent content1 = CreateBranch(); + IContent[] content1C = Children(content1).ToArray(); Assert.AreEqual(4, content1C.Length); - var content1Csorted = new[] { content1C[3], content1C[0], content1C[1], content1C[2] }; + IContent[] content1Csorted = new[] { content1C[3], content1C[0], content1C[1], content1C[2] }; ResetEvents(); ContentService.Sort(content1Csorted); - var content1Cagain = Children(content1).ToArray(); + IContent[] content1Cagain = Children(content1).ToArray(); Assert.AreEqual(4, content1Cagain.Length); Assert.AreEqual(content1C[0].Id, content1Cagain[1].Id); Assert.AreEqual(content1C[1].Id, content1Cagain[2].Id); @@ -865,8 +785,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, _msgCount); Assert.AreEqual(8, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[3].Id}.u=u", _events[i++].ToString()); // content5 is not published Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); // content2 is published Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[1].Id}.u=u", _events[i++].ToString()); // content3 is not published @@ -876,22 +797,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[0].Id}", _events[i++].ToString()); // content2 is published Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[1].Id}", _events[i++].ToString()); // content3 is not published Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[2].Id}", _events[i].ToString()); // content4 is published +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void SortSome() { // rule: ? - - var content1 = CreateBranch(); - var content1C = Children(content1).ToArray(); + IContent content1 = CreateBranch(); + IContent[] content1C = Children(content1).ToArray(); Assert.AreEqual(4, content1C.Length); - var content1Csorted = new[] { content1C[0], content1C[1], content1C[3], content1C[2] }; + IContent[] content1Csorted = new[] { content1C[0], content1C[1], content1C[3], content1C[2] }; ResetEvents(); ContentService.Sort(content1Csorted); - var content1Cagain = Children(content1).ToArray(); + IContent[] content1Cagain = Children(content1).ToArray(); Assert.AreEqual(4, content1Cagain.Length); Assert.AreEqual(content1C[0].Id, content1Cagain[0].Id); Assert.AreEqual(content1C[1].Id, content1Cagain[1].Id); @@ -900,13 +821,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(3, _msgCount); Assert.AreEqual(4, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[3].Id}.u=u", _events[i++].ToString()); // content5 is not published Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1C[2].Id}.p=p", _events[i++].ToString()); // content4 is published + changes m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[3].Id}", _events[i++].ToString()); // content5 is not published Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[2].Id}", _events[i].ToString()); // content4 is published +#pragma warning restore SA1003 // Symbols should be spaced correctly } #endregion @@ -916,11 +839,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // incl. trashing a published, unpublished content, w/changes // incl. trashing a branch, untrashing a single masked content // including emptying the recycle bin - [Test] public void TrashUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ResetEvents(); @@ -928,8 +850,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); @@ -938,7 +860,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void UntrashUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.MoveToRecycleBin(content); @@ -948,8 +870,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); @@ -959,8 +881,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void TrashPublishedContent() { // does 1) unpublish and 2) trash - - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -970,11 +891,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=m", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); + ////Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); } @@ -982,8 +903,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void UntrashPublishedContent() { // same as unpublished as it's been unpublished - - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -994,8 +914,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; + // trashing did /pm- (published, masked) // un-trashing cannot re-publish so /u?- (not-published, unchanged) // but because we *have* to change state to unpublished, it's /ux- and not /uu- @@ -1007,7 +928,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TrashPublishedContentWithChanges() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -1019,32 +940,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=m", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); + ////Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); } [Test] public void TrashContentBranch() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ResetEvents(); ContentService.MoveToRecycleBin(content1); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=m", _events[i++].ToString()); @@ -1061,6 +983,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] @@ -1068,7 +991,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.MoveToRecycleBin(content); @@ -1078,8 +1001,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1090,11 +1013,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.MoveToRecycleBin(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.MoveToRecycleBin(content2); @@ -1103,13 +1026,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(3, _msgCount); Assert.AreEqual(4, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content1.Id}", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content2.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content1.Id}", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content2.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] @@ -1117,26 +1042,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); ContentService.MoveToRecycleBin(content1); ResetEvents(); - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[1].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[0].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content1C[3].Id}", _events[i++].ToString()); @@ -1152,6 +1078,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content1.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content1.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } #endregion @@ -1161,7 +1088,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeleteUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ResetEvents(); @@ -1169,8 +1096,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1179,7 +1106,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeletePublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -1188,8 +1115,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1198,7 +1125,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeletePublishedContentWithChanges() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); content.Properties.First().SetValue("changed"); @@ -1209,8 +1136,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1219,10 +1146,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeleteMaskedPublishedContent() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); @@ -1232,8 +1159,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content2.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content2.Id}", _events[i].ToString()); @@ -1242,23 +1169,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeleteBranch() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); // get them before they are deleted! - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); ResetEvents(); ContentService.Delete(content1); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[1].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[0].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content1C[3].Id}", _events[i++].ToString()); @@ -1274,6 +1202,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content1.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content1.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } #endregion @@ -1283,9 +1212,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveUnpublishedContentUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1293,8 +1222,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1303,10 +1232,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1314,8 +1243,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); @@ -1324,12 +1253,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentWithChangesUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ContentService.Save(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1337,8 +1266,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); @@ -1347,9 +1276,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveUnpublishedContentUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1358,8 +1287,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1368,12 +1297,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveUnpublishedContentUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1383,8 +1312,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1393,10 +1322,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1405,8 +1334,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1415,13 +1344,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1431,8 +1360,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1441,12 +1370,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentWithChangesUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ContentService.Save(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1455,8 +1384,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1465,15 +1394,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentWithChangesUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ContentService.Save(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1483,8 +1412,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1493,14 +1422,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); @@ -1509,8 +1438,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1519,17 +1448,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); - var content4 = CreateContent(content3.Id); + IContent content4 = CreateContent(content3.Id); Assert.IsNotNull(content4); ContentService.SaveAndPublish(content4); ContentService.Unpublish(content3); @@ -1539,8 +1468,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1549,16 +1478,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentWithChangesUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ContentService.Save(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); @@ -1567,8 +1496,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1577,19 +1506,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentWithChangesUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ContentService.Save(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); - var content4 = CreateContent(content3.Id); + IContent content4 = CreateContent(content3.Id); Assert.IsNotNull(content4); ContentService.SaveAndPublish(content4); ContentService.Unpublish(content3); @@ -1599,8 +1528,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1609,14 +1538,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ResetEvents(); @@ -1624,8 +1553,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1634,16 +1563,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentWithChangesUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ContentService.Save(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ResetEvents(); @@ -1651,8 +1580,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1661,10 +1590,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveContentBranchUnderUnpublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1672,13 +1601,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=m", _events[i++].ToString()); @@ -1694,29 +1624,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchUnderPublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1725,13 +1642,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1747,32 +1665,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchUnderMasked() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1782,13 +1687,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=m", _events[i++].ToString()); @@ -1804,29 +1710,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchBackFromPublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1837,13 +1730,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1859,29 +1753,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchBackFromUnpublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.Move(content1, content2.Id); @@ -1891,13 +1772,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1913,32 +1795,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchBackFromMasked() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1950,13 +1819,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1972,20 +1842,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } #endregion @@ -1995,16 +1852,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CopyUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); @@ -2013,17 +1870,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CopyPublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); @@ -2032,20 +1889,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CopyMaskedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.Move(content, content2.Id); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); @@ -2054,23 +1911,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CopyBranch() { - var content = CreateBranch(); + IContent content = CreateBranch(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); - var copyC = Children(copy).ToArray(); - var copy2C = Children(copyC[0]).ToArray(); - var copy3C = Children(copyC[1]).ToArray(); - var copy4C = Children(copyC[2]).ToArray(); - var copy5C = Children(copyC[3]).ToArray(); + IContent[] copyC = Children(copy).ToArray(); + IContent[] copy2C = Children(copyC[0]).ToArray(); + IContent[] copy3C = Children(copyC[1]).ToArray(); + IContent[] copy4C = Children(copyC[2]).ToArray(); + IContent[] copy5C = Children(copyC[3]).ToArray(); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{copyC[0].Id}.u=u", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{copy2C[0].Id}.u=u", _events[i++].ToString()); @@ -2086,6 +1944,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } #endregion @@ -2095,18 +1954,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Rollback() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); - var v1 = content.VersionId; + int v1 = content.VersionId; content.Properties.First().SetValue("changed"); ContentService.SaveAndPublish(content); - var v2 = content.VersionId; + int v2 = content.VersionId; content.Properties.First().SetValue("again"); ContentService.SaveAndPublish(content); - var v3 = content.VersionId; + int v3 = content.VersionId; Console.WriteLine(v1); Console.WriteLine(v2); @@ -2118,10 +1977,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (justification: suppression necessary here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } #endregion @@ -2131,7 +1992,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void ContentRemembers() { - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.Save(content); @@ -2148,23 +2009,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } [Test] - public void HasInitialContent() - { - Assert.AreEqual(4, ContentService.Count()); - } + public void HasInitialContent() => Assert.AreEqual(4, ContentService.Count()); #endregion #region TODO // all content type events - #endregion public class LocalServerMessenger : ServerMessengerBase { - public LocalServerMessenger() : base(false) - { } + public LocalServerMessenger() + : base(false) + { + } public override void SendMessages() { } @@ -2176,3 +2035,5 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } } + +#pragma warning restore SA1124 // Do not use regions diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.cs index 83d669a06e..3a5d90b24f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration.Models; @@ -14,15 +17,19 @@ using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, + [UmbracoTest( + Database = UmbracoTestOptions.Database.NewSchemaPerTest, PublishedRepositoryEvents = true, WithApplication = true, Logger = UmbracoTestOptions.Logger.Console)] public class ContentServiceEventTests : UmbracoIntegrationTest { private IContentTypeService ContentTypeService => GetRequiredService(); + private ContentService ContentService => (ContentService)GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); private GlobalSettings _globalSettings; @@ -33,6 +40,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentRepositoryBase.ThrowOnWarning = true; _globalSettings = new GlobalSettings(); + // TODO: remove this once IPublishedSnapShotService has been implemented with nucache. global::Umbraco.Core.Services.Implement.ContentTypeService.ClearScopeEvents(); CreateTestData(); @@ -40,7 +48,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! _contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); @@ -48,10 +56,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } [TearDown] - public void Teardown() - { - ContentRepositoryBase.ThrowOnWarning = false; - } + public void Teardown() => ContentRepositoryBase.ThrowOnWarning = false; [Test] public void Saving_Culture() @@ -59,8 +64,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(new Language(_globalSettings, "fr-FR")); _contentType.Variations = ContentVariation.Culture; - foreach (var propertyType in _contentType.PropertyTypes) + foreach (IPropertyType propertyType in _contentType.PropertyTypes) + { propertyType.Variations = ContentVariation.Culture; + } + ContentTypeService.Save(_contentType); IContent document = new Content("content", -1, _contentType); @@ -68,7 +76,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services document.SetCultureName("bonjour", "fr-FR"); ContentService.Save(document); - //re-get - dirty properties need resetting + // re-get - dirty properties need resetting document = ContentService.GetById(document.Id); // properties: title, bodyText, keywords, description @@ -76,7 +84,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame(document, saved); @@ -86,7 +94,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaved(IContentService sender, ContentSavedEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame(document, saved); @@ -114,7 +122,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.IsTrue(document.GetValue("title").IsNullOrWhiteSpace()); @@ -123,12 +131,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaved(IContentService sender, ContentSavedEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame("title", document.GetValue("title")); - //we're only dealing with invariant here - var propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); + // we're only dealing with invariant here + IPropertyValue propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); Assert.AreEqual("title", propValue.EditedValue); Assert.IsNull(propValue.PublishedValue); @@ -153,8 +161,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(new Language(_globalSettings, "fr-FR")); _contentType.Variations = ContentVariation.Culture; - foreach (var propertyType in _contentType.PropertyTypes) + foreach (IPropertyType propertyType in _contentType.PropertyTypes) + { propertyType.Variations = ContentVariation.Culture; + } + ContentTypeService.Save(_contentType); IContent document = new Content("content", -1, _contentType); @@ -165,12 +176,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(document.IsCulturePublished("fr-FR")); Assert.IsFalse(document.IsCulturePublished("en-US")); - //re-get - dirty properties need resetting + // re-get - dirty properties need resetting document = ContentService.GetById(document.Id); void OnPublishing(IContentService sender, ContentPublishingEventArgs e) { - var publishing = e.PublishedEntities.First(); + IContent publishing = e.PublishedEntities.First(); Assert.AreSame(document, publishing); @@ -180,7 +191,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnPublished(IContentService sender, ContentPublishedEventArgs e) { - var published = e.PublishedEntities.First(); + IContent published = e.PublishedEntities.First(); Assert.AreSame(document, published); @@ -214,7 +225,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.IsTrue(document.GetValue("title").IsNullOrWhiteSpace()); @@ -223,12 +234,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaved(IContentService sender, ContentSavedEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame("title", document.GetValue("title")); // We're only dealing with invariant here. - var propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); + IPropertyValue propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); Assert.AreEqual("title", propValue.EditedValue); Assert.AreEqual("title", propValue.PublishedValue); @@ -253,13 +264,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Publishing_Set_Mandatory_Value() { - var titleProperty = _contentType.PropertyTypes.First(x => x.Alias == "title"); + IPropertyType titleProperty = _contentType.PropertyTypes.First(x => x.Alias == "title"); titleProperty.Mandatory = true; // make this required! ContentTypeService.Save(_contentType); IContent document = new Content("content", -1, _contentType); - var result = ContentService.SaveAndPublish(document); + PublishResult result = ContentService.SaveAndPublish(document); Assert.IsFalse(result.Success); Assert.AreEqual("title", result.InvalidProperties.First().Alias); @@ -269,7 +280,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.IsTrue(document.GetValue("title").IsNullOrWhiteSpace()); @@ -283,7 +294,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services try { result = ContentService.SaveAndPublish(document); - Assert.IsTrue(result.Success); //will succeed now because we were able to specify the required value in the Saving event + Assert.IsTrue(result.Success); // will succeed now because we were able to specify the required value in the Saving event } finally { @@ -297,8 +308,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(new Language(_globalSettings, "fr-FR")); _contentType.Variations = ContentVariation.Culture; - foreach (var propertyType in _contentType.PropertyTypes) + foreach (IPropertyType propertyType in _contentType.PropertyTypes) + { propertyType.Variations = ContentVariation.Culture; + } + ContentTypeService.Save(_contentType); var contentService = (ContentService)ContentService; @@ -311,12 +325,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(document.IsCulturePublished("fr-FR")); Assert.IsTrue(document.IsCulturePublished("en-US")); - //re-get - dirty properties need resetting + // re-get - dirty properties need resetting document = contentService.GetById(document.Id); void OnPublishing(IContentService sender, ContentPublishingEventArgs e) { - var publishing = e.PublishedEntities.First(); + IContent publishing = e.PublishedEntities.First(); Assert.AreSame(document, publishing); @@ -329,7 +343,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnPublished(IContentService sender, ContentPublishedEventArgs e) { - var published = e.PublishedEntities.First(); + IContent published = e.PublishedEntities.First(); Assert.AreSame(document, published); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.cs index 072fbe04a3..e48f1fe52b 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -10,6 +13,7 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; @@ -23,27 +27,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ContentServicePerformanceTest : UmbracoIntegrationTest { protected DocumentRepository DocumentRepository => (DocumentRepository)GetRequiredService(); + protected IFileService FileService => GetRequiredService(); + protected IContentTypeService ContentTypeService => GetRequiredService(); + protected IContentService ContentService => GetRequiredService(); protected IContentType ContentType { get; set; } [SetUp] - public void SetUpData() - { - CreateTestData(); - } + public void SetUpData() => CreateTestData(); [Test] - public void Profiler() - { - Assert.IsInstanceOf(GetRequiredService()); - } + public void Profiler() => Assert.IsInstanceOf(GetRequiredService()); private static IProfilingLogger GetTestProfilingLogger() { - var profiler = new TestProfiler(); return new ProfilingLogger(new NullLogger(), profiler); } @@ -51,7 +51,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Retrieving_All_Content_In_Site() { - //NOTE: Doing this the old 1 by 1 way and based on the results of the ContentServicePerformanceTest.Retrieving_All_Content_In_Site + // NOTE: Doing this the old 1 by 1 way and based on the results of the ContentServicePerformanceTest.Retrieving_All_Content_In_Site // the old way takes 143795ms, the new above way takes: // 14249ms // @@ -62,13 +62,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // // ... NOPE, made even more nice changes, it is now... // 4452ms !!!!!!! - - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType1 = ContentTypeBuilder.CreateTextPageContentType("test1", "test1", defaultTemplateId: template.Id); - var contentType2 = ContentTypeBuilder.CreateTextPageContentType("test2", "test2", defaultTemplateId: template.Id); - var contentType3 = ContentTypeBuilder.CreateTextPageContentType("test3", "test3", defaultTemplateId: template.Id); + ContentType contentType1 = ContentTypeBuilder.CreateTextPageContentType("test1", "test1", defaultTemplateId: template.Id); + ContentType contentType2 = ContentTypeBuilder.CreateTextPageContentType("test2", "test2", defaultTemplateId: template.Id); + ContentType contentType3 = ContentTypeBuilder.CreateTextPageContentType("test3", "test3", defaultTemplateId: template.Id); ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 }); contentType1.AllowedContentTypes = new[] { @@ -87,13 +86,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }; ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 }); - var roots = ContentBuilder.CreateTextpageContent(contentType1, -1, 10); + IEnumerable roots = ContentBuilder.CreateTextpageContent(contentType1, -1, 10); ContentService.Save(roots); - foreach (var root in roots) + foreach (Content root in roots) { - var item1 = ContentBuilder.CreateTextpageContent(contentType1, root.Id, 10); - var item2 = ContentBuilder.CreateTextpageContent(contentType2, root.Id, 10); - var item3 = ContentBuilder.CreateTextpageContent(contentType3, root.Id, 10); + IEnumerable item1 = ContentBuilder.CreateTextpageContent(contentType1, root.Id, 10); + IEnumerable item2 = ContentBuilder.CreateTextpageContent(contentType2, root.Id, 10); + IEnumerable item3 = ContentBuilder.CreateTextpageContent(contentType3, root.Id, 10); ContentService.Save(item1.Concat(item2).Concat(item3)); } @@ -104,10 +103,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { TestProfiler.Enable(); total.AddRange(ContentService.GetRootContent()); - foreach (var content in total.ToArray()) + foreach (IContent content in total.ToArray()) { - total.AddRange(ContentService.GetPagedDescendants(content.Id, 0, int.MaxValue, out var _)); + total.AddRange(ContentService.GetPagedDescendants(content.Id, 0, int.MaxValue, out long _)); } + TestProfiler.Disable(); StaticApplicationLogging.Logger.LogInformation("Returned {Total} items", total.Count); } @@ -117,14 +117,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Creating_100_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); // Act - Stopwatch watch = Stopwatch.StartNew(); + var watch = Stopwatch.StartNew(); ContentService.Save(pages, 0); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items saved in {0} ms", elapsed); @@ -136,14 +136,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Creating_1000_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); // Act - Stopwatch watch = Stopwatch.StartNew(); + var watch = Stopwatch.StartNew(); ContentService.Save(pages, 0); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items saved in {0} ms", elapsed); @@ -155,20 +155,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Getting_100_Uncached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); ContentService.Save(pages, 0); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - Stopwatch watch = Stopwatch.StartNew(); - var contents = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contents = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items retrieved in {0} ms without caching", elapsed); @@ -176,33 +176,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(contents.Any(x => x.HasIdentity == false), Is.False); Assert.That(contents.Any(x => x == null), Is.False); } - - } [Test] public void Getting_1000_Uncached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); ContentService.Save(pages, 0); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - Stopwatch watch = Stopwatch.StartNew(); - var contents = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contents = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("1000 content items retrieved in {0} ms without caching", elapsed); // Assert - //Assert.That(contents.Any(x => x.HasIdentity == false), Is.False); - //Assert.That(contents.Any(x => x == null), Is.False); + // Assert.That(contents.Any(x => x.HasIdentity == false), Is.False); + // Assert.That(contents.Any(x => x == null), Is.False); } } @@ -210,21 +208,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Getting_100_Cached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); ContentService.Save(pages, 0); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - var contents = repository.GetMany(); + IEnumerable contents = repository.GetMany(); - Stopwatch watch = Stopwatch.StartNew(); - var contentsCached = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contentsCached = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items retrieved in {0} ms with caching", elapsed); @@ -239,38 +237,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Getting_1000_Cached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); ContentService.Save(pages, 0); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - var contents = repository.GetMany(); + IEnumerable contents = repository.GetMany(); - Stopwatch watch = Stopwatch.StartNew(); - var contentsCached = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contentsCached = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("1000 content items retrieved in {0} ms with caching", elapsed); // Assert - //Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False); - //Assert.That(contentsCached.Any(x => x == null), Is.False); - //Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count())); + // Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False); + // Assert.That(contentsCached.Any(x => x == null), Is.False); + // Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count())); } } public void CreateTestData() { - - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Create and Save ContentType "textpage" -> ContentType.Id + // Create and Save ContentType "textpage" -> ContentType.Id ContentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(ContentType); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs index fccd708286..b890f186b5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; @@ -18,14 +21,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ContentServicePublishBranchTests : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); [TestCase(1)] // use overload w/ culture: "*" [TestCase(2)] // use overload w/ cultures: new [] { "*" } public void Can_Publish_Invariant_Branch(int method) { - CreateTypes(out var iContentType, out _); + CreateTypes(out IContentType iContentType, out _); IContent iRoot = new Content("iroot", -1, iContentType); iRoot.SetValue("ip", "iroot"); @@ -43,17 +48,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // !force = publishes those that are actually published, and have changes // here: root (root is always published) - - var r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); + PublishResult[] r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); // not forcing, ii1 and ii2 not published yet: only root got published - AssertPublishResults(r, x => x.Content.Name, - "iroot"); - AssertPublishResults(r, x => x.Result, - PublishResultType.SuccessPublish); + AssertPublishResults(r, x => x.Content.Name, "iroot"); + AssertPublishResults(r, x => x.Result, PublishResultType.SuccessPublish); // prepare - ContentService.SaveAndPublish(iRoot); ContentService.SaveAndPublish(ii1); @@ -83,19 +84,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // !force = publishes those that are actually published, and have changes // here: nothing - r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); // not forcing, ii12 and ii2, ii21, ii22 not published yet: only root, ii1, ii11 got published - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "ii11"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "ii11"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready); // prepare - iRoot.SetValue("ip", "changed"); ContentService.Save(iRoot); ii11.SetValue("ip", "changed"); @@ -114,20 +114,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // not forcing, ii12 and ii2, ii21, ii22 not published yet: only root, ii1, ii11 got published r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "ii11"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "ii11"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublish, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublish); // force = publishes everything that has changes // here: ii12, ii2, ii22 - ii21 was published already but masked - r = SaveAndPublishInvariantBranch(iRoot, true, method).ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "ii11", "ii12", "ii2", "ii21", "ii22"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults( + r, + x => x.Content.Name, + "iroot", + "ii1", + "ii11", + "ii12", + "ii2", + "ii21", + "ii22"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready, @@ -143,9 +153,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Variant_Branch_When_No_Changes_On_Root_All_Cultures() { - CreateTypes(out _, out var vContentType); + CreateTypes(out _, out IContentType vContentType); - //create/publish root + // create/publish root IContent vRoot = new Content("vroot", -1, vContentType, "de"); vRoot.SetCultureName("vroot.de", "de"); vRoot.SetCultureName("vroot.ru", "ru"); @@ -156,7 +166,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services vRoot.SetValue("vp", "vroot.es", "es"); ContentService.SaveAndPublish(vRoot); - //create/publish child + // create/publish child IContent iv1 = new Content("iv1", vRoot, vContentType, "de"); iv1.SetCultureName("iv1.de", "de"); iv1.SetCultureName("iv1.ru", "ru"); @@ -167,11 +177,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services iv1.SetValue("vp", "iv1.es", "es"); ContentService.SaveAndPublish(iv1); - //update the child + // update the child iv1.SetValue("vp", "UPDATED-iv1.de", "de"); ContentService.Save(iv1); - var r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); //no culture specified so "*" is used, so all cultures + PublishResult[] r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); // no culture specified so "*" is used, so all cultures Assert.AreEqual(PublishResultType.SuccessPublishAlready, r[0].Result); Assert.AreEqual(PublishResultType.SuccessPublishCulture, r[1].Result); } @@ -179,9 +189,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Variant_Branch_When_No_Changes_On_Root_Specific_Culture() { - CreateTypes(out _, out var vContentType); + CreateTypes(out _, out IContentType vContentType); - //create/publish root + // create/publish root IContent vRoot = new Content("vroot", -1, vContentType, "de"); vRoot.SetCultureName("vroot.de", "de"); vRoot.SetCultureName("vroot.ru", "ru"); @@ -192,7 +202,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services vRoot.SetValue("vp", "vroot.es", "es"); ContentService.SaveAndPublish(vRoot); - //create/publish child + // create/publish child IContent iv1 = new Content("iv1", vRoot, vContentType, "de"); iv1.SetCultureName("iv1.de", "de"); iv1.SetCultureName("iv1.ru", "ru"); @@ -203,11 +213,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services iv1.SetValue("vp", "iv1.es", "es"); ContentService.SaveAndPublish(iv1); - //update the child + // update the child iv1.SetValue("vp", "UPDATED-iv1.de", "de"); - var saveResult = ContentService.Save(iv1); + OperationResult saveResult = ContentService.Save(iv1); - var r = ContentService.SaveAndPublishBranch(vRoot, false, "de").ToArray(); + PublishResult[] r = ContentService.SaveAndPublishBranch(vRoot, false, "de").ToArray(); Assert.AreEqual(PublishResultType.SuccessPublishAlready, r[0].Result); Assert.AreEqual(PublishResultType.SuccessPublishCulture, r[1].Result); } @@ -215,7 +225,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Variant_Branch() { - CreateTypes(out _, out var vContentType); + CreateTypes(out _, out IContentType vContentType); IContent vRoot = new Content("vroot", -1, vContentType, "de"); vRoot.SetCultureName("vroot.de", "de"); @@ -253,14 +263,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // !force = publishes those that are actually published, and have changes // here: nothing - - var r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); // no culture specified = all cultures + PublishResult[] r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); // no culture specified = all cultures // not forcing, iv1 and iv2 not published yet: only root got published - AssertPublishResults(r, x => x.Content.Name, - "vroot.de"); - AssertPublishResults(r, x => x.Result, - PublishResultType.SuccessPublishCulture); + AssertPublishResults(r, x => x.Content.Name, "vroot.de"); + AssertPublishResults(r, x => x.Result, PublishResultType.SuccessPublishCulture); // prepare vRoot.SetValue("ip", "changed"); @@ -269,7 +276,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services vRoot.SetValue("vp", "changed.es", "es"); ContentService.Save(vRoot); // now root has drafts in all cultures - ContentService.SaveAndPublish(iv1, new []{"de", "ru"}); // now iv1 de and ru are published + ContentService.SaveAndPublish(iv1, new[] { "de", "ru" }); // now iv1 de and ru are published iv1.SetValue("ip", "changed"); iv1.SetValue("vp", "changed.de", "de"); @@ -292,9 +299,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services r = ContentService.SaveAndPublishBranch(vRoot, false, "de").ToArray(); // not forcing, iv2 not published yet: only root and iv1 got published - AssertPublishResults(r, x => x.Content.Name, - "vroot.de", "iv1.de"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults(r, x => x.Content.Name, "vroot.de", "iv1.de"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishCulture, PublishResultType.SuccessPublishCulture); @@ -329,8 +337,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // invariant root -> variant -> invariant // variant root -> variant -> invariant // variant root -> invariant -> variant - - CreateTypes(out var iContentType, out var vContentType); + CreateTypes(out IContentType iContentType, out IContentType vContentType); // invariant root -> invariant -> variant iRoot = new Content("iroot", -1, iContentType); @@ -349,7 +356,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.Save(iv11); iv11.SetCultureName("iv11.ru", "ru"); - var xxx = ContentService.SaveAndPublish(iv11, new []{"de", "ru"}); + PublishResult xxx = ContentService.SaveAndPublish(iv11, new[] { "de", "ru" }); Assert.AreEqual("iv11.de", iv11.GetValue("vp", "de", published: true)); Assert.AreEqual("iv11.ru", iv11.GetValue("vp", "ru", published: true)); @@ -363,12 +370,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Mixed_Branch_1() { - Can_Publish_Mixed_Branch(out var iRoot, out var ii1, out var iv11); + Can_Publish_Mixed_Branch(out IContent iRoot, out IContent ii1, out IContent iv11); - var r = ContentService.SaveAndPublishBranch(iRoot, false, "de").ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "iv11.de"); - AssertPublishResults(r, x => x.Result, + PublishResult[] r = ContentService.SaveAndPublishBranch(iRoot, false, "de").ToArray(); + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "iv11.de"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublish, PublishResultType.SuccessPublishCulture); @@ -379,7 +387,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // the invariant child has been published // the variant child has been published for 'de' only - Assert.AreEqual("changed", ii1.GetValue("ip", published: true)); Assert.AreEqual("changed", iv11.GetValue("ip", published: true)); Assert.AreEqual("changed.de", iv11.GetValue("vp", "de", published: true)); @@ -389,12 +396,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_MixedBranch_2() { - Can_Publish_Mixed_Branch(out var iRoot, out var ii1, out var iv11); + Can_Publish_Mixed_Branch(out IContent iRoot, out IContent ii1, out IContent iv11); - var r = ContentService.SaveAndPublishBranch(iRoot, false, new[] { "de", "ru" }).ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "iv11.de"); - AssertPublishResults(r, x => x.Result, + PublishResult[] r = ContentService.SaveAndPublishBranch(iRoot, false, new[] { "de", "ru" }).ToArray(); + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "iv11.de"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublish, PublishResultType.SuccessPublishCulture); @@ -405,7 +413,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // the invariant child has been published // the variant child has been published for 'de' and 'ru' - Assert.AreEqual("changed", ii1.GetValue("ip", published: true)); Assert.AreEqual("changed", iv11.GetValue("ip", published: true)); Assert.AreEqual("changed.de", iv11.GetValue("vp", "de", published: true)); @@ -415,12 +422,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void AssertPublishResults(PublishResult[] values, Func getter, params T[] expected) { if (expected.Length != values.Length) + { Console.WriteLine(string.Join(", ", values.Select(x => getter(x).ToString()))); + } + Assert.AreEqual(expected.Length, values.Length); - for (var i = 0; i < values.Length; i++) + for (int i = 0; i < values.Length; i++) { - var value = getter(values[i]); + T value = getter(values[i]); Assert.AreEqual(expected[i], value, $"Expected {expected[i]} at {i} but got {value}."); } } @@ -468,10 +478,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services case 1: return ContentService.SaveAndPublishBranch(content, force, culture: "*"); case 2: - return ContentService.SaveAndPublishBranch(content, force, cultures: new [] { "*" }); + return ContentService.SaveAndPublishBranch(content, force, cultures: new[] { "*" }); default: throw new ArgumentOutOfRangeException(nameof(method)); } + // ReSharper restore RedundantArgumentDefaultValue // ReSharper restore ArgumentsStyleOther } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs index 193f343305..b7f3609d89 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs @@ -1,10 +1,15 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; @@ -15,40 +20,42 @@ using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, + [UmbracoTest( + Database = UmbracoTestOptions.Database.NewSchemaPerTest, PublishedRepositoryEvents = true, WithApplication = true, Logger = UmbracoTestOptions.Logger.Console)] public class ContentServiceTagsTests : UmbracoIntegrationTest { private IContentTypeService ContentTypeService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); + private ITagService TagService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IJsonSerializer Serializer => GetRequiredService(); + public PropertyEditorCollection PropertyEditorCollection => GetRequiredService(); [SetUp] - public void Setup() - { - ContentRepositoryBase.ThrowOnWarning = true; - } + public void Setup() => ContentRepositoryBase.ThrowOnWarning = true; [TearDown] - public void Teardown() - { - ContentRepositoryBase.ThrowOnWarning = false; - } + public void Teardown() => ContentRepositoryBase.ThrowOnWarning = false; [Test] public void TagsCanBeInvariant() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); @@ -58,16 +65,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content1 = ContentService.GetById(content1.Id); - var enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, enTags.Length); Assert.Contains("one", enTags); Assert.AreEqual(-1, enTags.IndexOf("plus")); - var tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags()) + IEnumerable> tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags()) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -77,16 +87,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBeVariant() { - var languageService = LocalizationService; - var language = new LanguageBuilder() + ILocalizationService languageService = LocalizationService; + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); @@ -99,26 +109,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content1 = ContentService.GetById(content1.Id); - var frTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR").ToArray(); + string[] frTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR").ToArray(); Assert.AreEqual(5, frTags.Length); Assert.Contains("plus", frTags); Assert.AreEqual(-1, frTags.IndexOf("one")); - var enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US").ToArray(); + string[] enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US").ToArray(); Assert.AreEqual(4, enTags.Length); Assert.Contains("one", enTags); Assert.AreEqual(-1, enTags.IndexOf("plus")); - var tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags()) + IEnumerable> tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags()) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(2, tagGroups.Count()); - var frTagGroup = tagGroups.FirstOrDefault(x => x.Key == 2); + IGrouping frTagGroup = tagGroups.FirstOrDefault(x => x.Key == 2); Assert.IsNotNull(frTagGroup); Assert.AreEqual(5, frTagGroup.Count()); Assert.IsTrue(frTagGroup.Any(x => x.Text == "plus")); Assert.IsFalse(frTagGroup.Any(x => x.Text == "one")); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == 1); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == 1); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -128,13 +141,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeVariant() { - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -147,16 +160,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // no changes content1 = ContentService.GetById(content1.Id); - var tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, tags.Length); Assert.Contains("one", tags); Assert.AreEqual(-1, tags.IndexOf("plus")); - var tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags()) + IEnumerable> tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags()) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -179,8 +195,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // tags have been copied from invariant to en-US tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags("*")) + foreach (ITag tag in TagService.GetAllTags("*")) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); enTagGroup = tagGroups.FirstOrDefault(x => x.Key == enId); @@ -193,17 +212,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariant() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); @@ -224,18 +243,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR")); Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US")); - var tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, tags.Length); Assert.Contains("one", tags); Assert.AreEqual(-1, tags.IndexOf("plus")); // tags have been copied from en-US to invariant, fr-FR tags are gone - var tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags("*")) + IEnumerable> tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags("*")) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -245,18 +267,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariant2() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -274,10 +296,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveAndPublish(content2); //// pretend we already have invariant values - //using (var scope = ScopeProvider.CreateScope()) - //{ + // using (var scope = ScopeProvider.CreateScope()) + // { // scope.Database.Execute("INSERT INTO [cmsTags] ([tag], [group], [languageId]) SELECT DISTINCT [tag], [group], NULL FROM [cmsTags] WHERE [languageId] IS NOT NULL"); - //} + // } // this should work propertyType.Variations = ContentVariation.Nothing; @@ -287,18 +309,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariantByPropertyType() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -318,18 +340,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR")); Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US")); - var tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, tags.Length); Assert.Contains("one", tags); Assert.AreEqual(-1, tags.IndexOf("plus")); // tags have been copied from en-US to invariant, fr-FR tags are gone - var tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags("*")) + IEnumerable> tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags("*")) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -339,16 +364,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariantByPropertyTypeAndBackToVariant() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -371,25 +396,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsAreUpdatedWhenContentIsTrashedAndUnTrashed_One() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "plus" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); // verify - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(5, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(5, allTags.Count()); ContentService.MoveToRecycleBin(content1); @@ -398,25 +423,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsAreUpdatedWhenContentIsTrashedAndUnTrashed_All() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "bam" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); // verify - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(5, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(5, allTags.Count()); ContentService.Unpublish(content1); @@ -427,25 +452,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Ignore("https://github.com/umbraco/Umbraco-CMS/issues/3821 (U4-8442), will need to be fixed.")] public void TagsAreUpdatedWhenContentIsTrashedAndUnTrashed_Tree() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "plus" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1.Id); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1.Id); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); // verify - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(5, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(5, allTags.Count()); ContentService.MoveToRecycleBin(content1); @@ -499,18 +524,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsAreUpdatedWhenContentIsUnpublishedAndRePublished() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "bam" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); @@ -522,24 +547,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Ignore("https://github.com/umbraco/Umbraco-CMS/issues/3821 (U4-8442), will need to be fixed.")] public void TagsAreUpdatedWhenContentIsUnpublishedAndRePublished_Tree() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "bam" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(0, tags.Count()); // FIXME: tag & tree issue @@ -547,7 +572,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // see similar note above tags = TagService.GetTagsForEntity(content2.Id); Assert.AreEqual(0, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(0, allTags.Count()); content1.PublishCulture(CultureImpact.Invariant); @@ -562,32 +587,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Tag_Data_Bulk_Publish_Operation() { - //Arrange - //set configuration - var dataType = DataTypeService.GetDataType(1041); + // Arrange + // set configuration + IDataType dataType = DataTypeService.GetDataType(1041); dataType.Configuration = new TagConfiguration { Group = "test", StorageType = TagsStorageType.Csv }; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); contentType.AllowedContentTypes = new[] { new ContentTypeSort(new Lazy(() => contentType.Id), 0, contentType.Alias) }; - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.Save(content); - var child1 = ContentBuilder.CreateSimpleContent(contentType, "child 1 content", content.Id); + Content child1 = ContentBuilder.CreateSimpleContent(contentType, "child 1 content", content.Id); child1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello1", "world1", "some1" }); ContentService.Save(child1); - var child2 = ContentBuilder.CreateSimpleContent(contentType, "child 2 content", content.Id); + Content child2 = ContentBuilder.CreateSimpleContent(contentType, "child 2 content", content.Id); child2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello2", "world2" }); ContentService.Save(child2); @@ -595,9 +620,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveAndPublishBranch(content, true); // Assert - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(4, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -618,16 +643,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Does_Not_Create_Tag_Data_For_Non_Published_Version() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // create content type with a tag property - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); // create a content with tags and publish - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content); @@ -639,8 +664,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); // but the database still contains the initial two tags - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(4, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -652,16 +677,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Replace_Tag_Data_To_Published_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + // Arrange + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); - + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); // Act content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); @@ -669,8 +693,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.AreEqual(4, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(4, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -683,14 +707,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Append_Tag_Data_To_Published_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + // Arrange + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content); @@ -700,8 +724,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.AreEqual(5, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(5, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -714,14 +738,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Remove_Tag_Data_To_Published_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + // Arrange + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content); @@ -731,8 +755,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.AreEqual(2, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(2, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -744,7 +768,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private PropertyType CreateAndAddTagsPropertyType(ContentType contentType, ContentVariation variations = ContentVariation.Nothing) { - var propertyType = new PropertyTypeBuilder() + PropertyType propertyType = new PropertyTypeBuilder() .WithPropertyEditorAlias("test") .WithAlias("tags") .WithDataTypeId(1041) diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.cs index 10fe206290..f809bd3d7e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Diagnostics; @@ -8,10 +11,12 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; using Umbraco.Core.Models; +using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; @@ -35,6 +40,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // TODO: Add test to verify there is only ONE newest document/content in {Constants.DatabaseSchema.Tables.Document} table after updating. // TODO: Add test to delete specific version (with and without deleting prior versions) and versions by date. + + private IDataTypeService DataTypeService => GetRequiredService(); private ILocalizationService LocalizationService => GetRequiredService(); @@ -70,13 +77,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Blueprint() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); blueprint.SetValue("title", "blueprint 1"); blueprint.SetValue("bodyText", "blueprint 2"); blueprint.SetValue("keywords", "blueprint 3"); @@ -84,24 +91,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveBlueprint(blueprint); - var found = ContentService.GetBlueprintsForContentTypes().ToArray(); + IContent[] found = ContentService.GetBlueprintsForContentTypes().ToArray(); Assert.AreEqual(1, found.Length); - //ensures it's not found by normal content - var contentFound = ContentService.GetById(found[0].Id); + // ensures it's not found by normal content + IContent contentFound = ContentService.GetById(found[0].Id); Assert.IsNull(contentFound); } [Test] public void Delete_Blueprint() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); blueprint.SetValue("title", "blueprint 1"); blueprint.SetValue("bodyText", "blueprint 2"); blueprint.SetValue("keywords", "blueprint 3"); @@ -111,22 +118,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.DeleteBlueprint(blueprint); - var found = ContentService.GetBlueprintsForContentTypes().ToArray(); + IContent[] found = ContentService.GetBlueprintsForContentTypes().ToArray(); Assert.AreEqual(0, found.Length); } [Test] public void Create_Content_From_Blueprint() { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) + using (IScope scope = ScopeProvider.CreateScope(autoComplete: true)) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); blueprint.SetValue("title", "blueprint 1"); blueprint.SetValue("bodyText", "blueprint 2"); blueprint.SetValue("keywords", "blueprint 3"); @@ -134,7 +141,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveBlueprint(blueprint); - var fromBlueprint = ContentService.CreateContentFromBlueprint(blueprint, "hello world"); + IContent fromBlueprint = ContentService.CreateContentFromBlueprint(blueprint, "hello world"); ContentService.Save(fromBlueprint); Assert.IsTrue(fromBlueprint.HasIdentity); @@ -143,29 +150,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("blueprint 3", fromBlueprint.Properties["keywords"].GetValue()); Assert.AreEqual("blueprint 4", fromBlueprint.Properties["description"].GetValue()); } - } [Test] public void Get_All_Blueprints() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var ct1 = ContentTypeBuilder.CreateTextPageContentType("ct1", defaultTemplateId: template.Id); + ContentType ct1 = ContentTypeBuilder.CreateTextPageContentType("ct1", defaultTemplateId: template.Id); FileService.SaveTemplate(ct1.DefaultTemplate); ContentTypeService.Save(ct1); - var ct2 = ContentTypeBuilder.CreateTextPageContentType("ct2", defaultTemplateId: template.Id); + ContentType ct2 = ContentTypeBuilder.CreateTextPageContentType("ct2", defaultTemplateId: template.Id); FileService.SaveTemplate(ct2.DefaultTemplate); ContentTypeService.Save(ct2); for (int i = 0; i < 10; i++) { - var blueprint = ContentBuilder.CreateTextpageContent(i % 2 == 0 ? ct1 : ct2, "hello" + i, Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(i % 2 == 0 ? ct1 : ct2, "hello" + i, Constants.System.Root); ContentService.SaveBlueprint(blueprint); } - var found = ContentService.GetBlueprintsForContentTypes().ToArray(); + IContent[] found = ContentService.GetBlueprintsForContentTypes().ToArray(); Assert.AreEqual(10, found.Length); found = ContentService.GetBlueprintsForContentTypes(ct1.Id).ToArray(); @@ -178,92 +184,103 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Perform_Scheduled_Publishing() { - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langUk); - var ctInvariant = ContentTypeBuilder.CreateBasicContentType("invariantPage"); + ContentType ctInvariant = ContentTypeBuilder.CreateBasicContentType("invariantPage"); ContentTypeService.Save(ctInvariant); - var ctVariant = ContentTypeBuilder.CreateBasicContentType("variantPage"); + ContentType ctVariant = ContentTypeBuilder.CreateBasicContentType("variantPage"); ctVariant.Variations = ContentVariation.Culture; ContentTypeService.Save(ctVariant); - var now = DateTime.Now; + DateTime now = DateTime.Now; - //10x invariant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds + // 10x invariant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds var invariant = new List(); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c = ContentBuilder.CreateBasicContent(ctInvariant); + Content c = ContentBuilder.CreateBasicContent(ctInvariant); c.Name = "name" + i; if (i % 2 == 0) { - c.ContentSchedule.Add(now.AddSeconds(5), null); //release in 5 seconds - var r = ContentService.Save(c); + c.ContentSchedule.Add(now.AddSeconds(5), null); // release in 5 seconds + OperationResult r = ContentService.Save(c); Assert.IsTrue(r.Success, r.Result.ToString()); } else { - c.ContentSchedule.Add(null, now.AddSeconds(5)); //expire in 5 seconds - var r = ContentService.SaveAndPublish(c); + c.ContentSchedule.Add(null, now.AddSeconds(5)); // expire in 5 seconds + PublishResult r = ContentService.SaveAndPublish(c); Assert.IsTrue(r.Success, r.Result.ToString()); } + invariant.Add(c); } - //10x variant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds + // 10x variant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds var variant = new List(); - var alternatingCulture = langFr.IsoCode; - for (var i = 0; i < 10; i++) + string alternatingCulture = langFr.IsoCode; + for (int i = 0; i < 10; i++) { - var c = ContentBuilder.CreateBasicContent(ctVariant); + Content c = ContentBuilder.CreateBasicContent(ctVariant); c.SetCultureName("name-uk" + i, langUk.IsoCode); c.SetCultureName("name-fr" + i, langFr.IsoCode); if (i % 2 == 0) { - c.ContentSchedule.Add(alternatingCulture, now.AddSeconds(5), null); //release in 5 seconds - var r = ContentService.Save(c); + c.ContentSchedule.Add(alternatingCulture, now.AddSeconds(5), null); // release in 5 seconds + OperationResult r = ContentService.Save(c); Assert.IsTrue(r.Success, r.Result.ToString()); alternatingCulture = alternatingCulture == langFr.IsoCode ? langUk.IsoCode : langFr.IsoCode; } else { - c.ContentSchedule.Add(alternatingCulture, null, now.AddSeconds(5)); //expire in 5 seconds - var r = ContentService.SaveAndPublish(c); + c.ContentSchedule.Add(alternatingCulture, null, now.AddSeconds(5)); // expire in 5 seconds + PublishResult r = ContentService.SaveAndPublish(c); Assert.IsTrue(r.Success, r.Result.ToString()); } + variant.Add(c); } - var runSched = ContentService.PerformScheduledPublish( - now.AddMinutes(1)).ToList(); //process anything scheduled before a minute from now + now.AddMinutes(1)).ToList(); // process anything scheduled before a minute from now - //this is 21 because the test data installed before this test runs has a scheduled item! + // this is 21 because the test data installed before this test runs has a scheduled item! Assert.AreEqual(21, runSched.Count); - Assert.AreEqual(20, runSched.Count(x => x.Success), + Assert.AreEqual( + 20, + runSched.Count(x => x.Success), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessPublish), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessPublish), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessUnpublish), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessUnpublish), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessPublishCulture), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessPublishCulture), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessUnpublishCulture), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessUnpublishCulture), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - //re-run the scheduled publishing, there should be no results + // re-run the scheduled publishing, there should be no results runSched = ContentService.PerformScheduledPublish( now.AddMinutes(1)).ToList(); @@ -276,20 +293,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act - var content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); content.ContentSchedule.Add(null, DateTime.Now.AddHours(2)); ContentService.Save(content, Constants.Security.SuperUserId); Assert.AreEqual(1, content.ContentSchedule.FullSchedule.Count); content = ContentService.GetById(content.Id); - var sched = content.ContentSchedule.FullSchedule; + IReadOnlyList sched = content.ContentSchedule.FullSchedule; Assert.AreEqual(1, sched.Count); Assert.AreEqual(1, sched.Count(x => x.Culture == string.Empty)); content.ContentSchedule.Clear(ContentScheduleAction.Expire); ContentService.Save(content, Constants.Security.SuperUserId); - // Assert content = ContentService.GetById(content.Id); sched = content.ContentSchedule.FullSchedule; @@ -302,18 +318,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); - for (var i = 0; i < 20; i++) + IContent content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + for (int i = 0; i < 20; i++) { content.SetValue("bodyText", "hello world " + Guid.NewGuid()); ContentService.SaveAndPublish(content); } // Assert - var allVersions = ContentService.GetVersionIds(content.Id, int.MaxValue); + IEnumerable allVersions = ContentService.GetVersionIds(content.Id, int.MaxValue); Assert.AreEqual(21, allVersions.Count()); - var topVersions = ContentService.GetVersionIds(content.Id, 4); + IEnumerable topVersions = ContentService.GetVersionIds(content.Id, 4); Assert.AreEqual(4, topVersions.Count()); } @@ -323,12 +339,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act var results = new List(); - for (var i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { results.Add(ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", 0)); } - var sortedGet = ContentService.GetByIds(new[] {results[10].Id, results[5].Id, results[12].Id}).ToArray(); + IContent[] sortedGet = ContentService.GetByIds(new[] { results[10].Id, results[5].Id, results[12].Id }).ToArray(); // Assert Assert.AreEqual(sortedGet[0].Id, results[10].Id); @@ -354,14 +370,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Count_By_Content_Type() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); // Act - for (var i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); } @@ -374,12 +390,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Count_Children() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); + IContent parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); // Act for (int i = 0; i < 20; i++) @@ -395,12 +411,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Count_Descendants() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); + IContent parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); // Act IContent current = parent; @@ -419,7 +435,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act var current = new Mock(); - var res = ContentService.GetAncestors(current.Object); + IEnumerable res = ContentService.GetAncestors(current.Object); // Assert Assert.IsEmpty(res); @@ -430,7 +446,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); // Assert Assert.That(content, Is.Not.Null); @@ -442,30 +458,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); // Assert Assert.That(content, Is.Not.Null); Assert.That(content.HasIdentity, Is.False); } - [Test] public void Can_Create_Content_Without_Explicitly_Set_User() { // Arrange // Act - var content = ContentService.Create("Test", Constants.System.Root, "umbTextpage"); + IContent content = ContentService.Create("Test", Constants.System.Root, "umbTextpage"); // Assert Assert.That(content, Is.Not.Null); Assert.That(content.HasIdentity, Is.False); - Assert.That(content.CreatorId, Is.EqualTo(Constants.Security.SuperUserId)); //Default to -1 aka SuperUser (unknown) since we didn't explicitly set this in the Create call + Assert.That(content.CreatorId, Is.EqualTo(Constants.Security.SuperUserId)); // Default to -1 aka SuperUser (unknown) since we didn't explicitly set this in the Create call } [Test] public void Can_Save_New_Content_With_Explicit_User() { - var user = new UserBuilder().Build(); + User user = new UserBuilder().Build(); UserService.Save(user); var content = new Content("Test", Constants.System.Root, ContentTypeService.Get("umbTextpage")); @@ -478,12 +493,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } [Test] - public void Cannot_Create_Content_With_Non_Existing_ContentType_Alias() - { - // Arrange - // Act & Assert + public void Cannot_Create_Content_With_Non_Existing_ContentType_Alias() => Assert.Throws(() => ContentService.Create("Test", Constants.System.Root, "umbAliasDoesntExist")); - } [Test] public void Cannot_Save_Content_With_Empty_Name() @@ -500,7 +511,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Assert Assert.That(content, Is.Not.Null); @@ -512,7 +523,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent content = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); // Assert Assert.That(content, Is.Not.Null); @@ -535,33 +546,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_All_Versions_Of_Content() { - var parent = ContentService.GetById(Textpage.Id); + IContent parent = ContentService.GetById(Textpage.Id); Assert.IsFalse(parent.Published); ContentService.SaveAndPublish(parent); // publishing parent, so Text Page 2 can be updated. - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); Assert.IsFalse(content.Published); var versions = ContentService.GetVersions(Subpage.Id).ToList(); Assert.AreEqual(1, versions.Count); - var version1 = content.VersionId; + int version1 = content.VersionId; Console.WriteLine($"1 e={content.VersionId} p={content.PublishedVersionId}"); content.Name = "Text Page 2 Updated"; content.SetValue("author", "Jane Doe"); ContentService.SaveAndPublish(content); // publishes the current version, creates a version - var version2 = content.VersionId; + int version2 = content.VersionId; Console.WriteLine($"2 e={content.VersionId} p={content.PublishedVersionId}"); content.Name = "Text Page 2 ReUpdated"; content.SetValue("author", "Bob Hope"); ContentService.SaveAndPublish(content); // publishes again, creates a version - var version3 = content.VersionId; + int version3 = content.VersionId; Console.WriteLine($"3 e={content.VersionId} p={content.PublishedVersionId}"); - var content1 = ContentService.GetById(content.Id); + IContent content1 = ContentService.GetById(content.Id); Assert.AreEqual("Bob Hope", content1.GetValue("author")); Assert.AreEqual("Bob Hope", content1.GetValue("author", published: true)); @@ -584,8 +595,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // p is always the same, published version // e is changing, actual version we're loading Console.WriteLine(); - foreach (var version in ((IEnumerable) versions).Reverse()) - Console.WriteLine($"+ e={((Content) version).VersionId} p={((Content) version).PublishedVersionId}"); + foreach (IContent version in ((IEnumerable)versions).Reverse()) + { + Console.WriteLine($"+ e={((Content)version).VersionId} p={((Content)version).PublishedVersionId}"); + } // and proper values // first, the current (edited) version, with edited and published versions @@ -618,9 +631,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Content_For_Expiration() { // Arrange - var root = ContentService.GetById(Textpage.Id); + IContent root = ContentService.GetById(Textpage.Id); ContentService.SaveAndPublish(root); - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); content.ContentSchedule.Add(null, DateTime.Now.AddSeconds(1)); ContentService.SaveAndPublish(content); @@ -653,7 +666,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); // Assert Assert.That(contents, Is.Not.Null); @@ -665,11 +678,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Unpublish_Content() { // Arrange - var content = ContentService.GetById(Textpage.Id); - var published = ContentService.SaveAndPublish(content, userId: 0); + IContent content = ContentService.GetById(Textpage.Id); + PublishResult published = ContentService.SaveAndPublish(content, userId: 0); // Act - var unpublished = ContentService.Unpublish(content, userId: 0); + PublishResult unpublished = ContentService.Unpublish(content, userId: 0); // Assert Assert.That(published.Success, Is.True); @@ -681,49 +694,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Unpublish_Content_Variation() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); content.PublishCulture(CultureImpact.Explicit(langFr.IsoCode, langFr.IsDefault)); content.PublishCulture(CultureImpact.Explicit(langUk.IsoCode, langUk.IsDefault)); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - var published = ContentService.SaveAndPublish(content, new[]{ langFr.IsoCode , langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsTrue(published.Success); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - var unpublished = ContentService.Unpublish(content, langFr.IsoCode); + PublishResult unpublished = ContentService.Unpublish(content, langFr.IsoCode); Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - - } [Test] public void Can_Publish_Culture_After_Last_Culture_Unpublished() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langUk.IsoCode); //first culture + PublishResult unpublished = ContentService.Unpublish(content, langUk.IsoCode); // first culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); @@ -731,7 +742,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content = ContentService.GetById(content.Id); - unpublished = ContentService.Unpublish(content, langFr.IsoCode); //last culture + unpublished = ContentService.Unpublish(content, langFr.IsoCode); // last culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishLastCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); @@ -744,54 +755,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); - content = ContentService.GetById(content.Id); //reget + content = ContentService.GetById(content.Id); // reget Assert.AreEqual(PublishedState.Published, content.PublishedState); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); - } - - [Test] public void Unpublish_All_Cultures_Has_Unpublished_State() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.AreEqual(PublishedState.Published, content.PublishedState); - var unpublished = ContentService.Unpublish(content, langFr.IsoCode); //first culture + PublishResult unpublished = ContentService.Unpublish(content, langFr.IsoCode); // first culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - Assert.AreEqual(PublishedState.Published, content.PublishedState); //still published + Assert.AreEqual(PublishedState.Published, content.PublishedState); // still published - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - unpublished = ContentService.Unpublish(content, langUk.IsoCode); //last culture + unpublished = ContentService.Unpublish(content, langUk.IsoCode); // last culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishLastCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); - Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); //the last culture was unpublished so the document should also reflect this + Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); // the last culture was unpublished so the document should also reflect this - //re-get + // re-get content = ContentService.GetById(content.Id); - Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); //just double checking + Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); // just double checking Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); } @@ -799,19 +807,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Unpublishing_Mandatory_Language_Unpublishes_Document() { - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .WithIsMandatory(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langUk); - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); @@ -819,104 +827,108 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("content-fr", langFr.IsoCode); content.SetCultureName("content-en", langUk.IsoCode); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langUk.IsoCode); //unpublish mandatory lang + PublishResult unpublished = ContentService.Unpublish(content, langUk.IsoCode); // unpublish mandatory lang Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishMandatoryCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); - Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); //remains published + Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); // remains published Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); } [Test] public void Unpublishing_Already_Unpublished_Culture() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langUk.IsoCode); + PublishResult unpublished = ContentService.Unpublish(content, langUk.IsoCode); Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); content = ContentService.GetById(content.Id); - //Change some data since Unpublish should always Save + // Change some data since Unpublish should always Save content.SetCultureName("content-en-updated", langUk.IsoCode); - unpublished = ContentService.Unpublish(content, langUk.IsoCode); //unpublish again + unpublished = ContentService.Unpublish(content, langUk.IsoCode); // unpublish again Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishAlready, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); content = ContentService.GetById(content.Id); - //ensure that even though the culture was already unpublished that the data was still persisted + + // ensure that even though the culture was already unpublished that the data was still persisted Assert.AreEqual("content-en-updated", content.GetCultureName(langUk.IsoCode)); } [Test] public void Publishing_No_Cultures_Still_Saves() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - //Change some data since SaveAndPublish should always Save + // Change some data since SaveAndPublish should always Save content.SetCultureName("content-en-updated", langUk.IsoCode); - var saved = ContentService.SaveAndPublish(content, new string [] { }); //save without cultures + PublishResult saved = ContentService.SaveAndPublish(content, new string[] { }); // save without cultures Assert.AreEqual(PublishResultType.FailedPublishNothingToPublish, saved.Result); - //re-get + // re-get content = ContentService.GetById(content.Id); - //ensure that even though nothing was published that the data was still persisted + + // ensure that even though nothing was published that the data was still persisted Assert.AreEqual("content-en-updated", content.GetCultureName(langUk.IsoCode)); } - [Test] public void Pending_Invariant_Property_Changes_Affect_Default_Language_Edited_State() { // Arrange - var langGb = new LanguageBuilder() + ILanguage langGb = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langGb); - var contentType = ContentTypeBuilder.CreateMetaContentType(); + ContentType contentType = ContentTypeBuilder.CreateMetaContentType(); contentType.Variations = ContentVariation.Culture; - foreach(var prop in contentType.PropertyTypes) + foreach (IPropertyType prop in contentType.PropertyTypes) + { prop.Variations = ContentVariation.Culture; - var keywordsProp = contentType.PropertyTypes.Single(x => x.Alias == "metakeywords"); + } + + IPropertyType keywordsProp = contentType.PropertyTypes.Single(x => x.Alias == "metakeywords"); keywordsProp.Variations = ContentVariation.Nothing; // this one is invariant ContentTypeService.Save(contentType); @@ -925,9 +937,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("content-en", langGb.IsoCode); content.SetCultureName("content-fr", langFr.IsoCode); - Assert.IsTrue(ContentService.SaveAndPublish(content, new []{ langGb.IsoCode , langFr.IsoCode }).Success); + Assert.IsTrue(ContentService.SaveAndPublish(content, new[] { langGb.IsoCode, langFr.IsoCode }).Success); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.AreEqual(PublishedState.Published, content.PublishedState); Assert.IsTrue(content.IsCulturePublished(langGb.IsoCode)); @@ -935,11 +947,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(content.IsCultureEdited(langGb.IsoCode)); Assert.IsFalse(content.IsCultureEdited(langFr.IsoCode)); - //update the invariant property and save a pending version + // update the invariant property and save a pending version content.SetValue("metakeywords", "hello"); ContentService.Save(content); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.AreEqual(PublishedState.Published, content.PublishedState); Assert.IsTrue(content.IsCulturePublished(langGb.IsoCode)); @@ -951,20 +963,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Content_Variation_And_Detect_Changed_Cultures() { - CreateEnglishAndFrenchDocumentType(out var langUk, out var langFr, out var contentType); + CreateEnglishAndFrenchDocumentType(out Language langUk, out Language langFr, out ContentType contentType); IContent content = new Content("content", Constants.System.Root, contentType); content.SetCultureName("content-fr", langFr.IsoCode); - var published = ContentService.SaveAndPublish(content, langFr.IsoCode); - //audit log will only show that french was published - var lastLog = AuditService.GetLogs(content.Id).Last(); + PublishResult published = ContentService.SaveAndPublish(content, langFr.IsoCode); + + // audit log will only show that french was published + IAuditItem lastLog = AuditService.GetLogs(content.Id).Last(); Assert.AreEqual($"Published languages: French (France)", lastLog.Comment); - //re-get + // re-get content = ContentService.GetById(content.Id); content.SetCultureName("content-en", langUk.IsoCode); published = ContentService.SaveAndPublish(content, langUk.IsoCode); - //audit log will only show that english was published + + // audit log will only show that english was published lastLog = AuditService.GetLogs(content.Id).Last(); Assert.AreEqual($"Published languages: English (United Kingdom)", lastLog.Comment); } @@ -973,53 +987,55 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Unpublish_Content_Variation_And_Detect_Changed_Cultures() { // Arrange - var langGb = new LanguageBuilder() + ILanguage langGb = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .WithIsMandatory(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langGb); - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); IContent content = new Content("content", Constants.System.Root, contentType); content.SetCultureName("content-fr", langFr.IsoCode); content.SetCultureName("content-gb", langGb.IsoCode); - var published = ContentService.SaveAndPublish(content, new[] {langGb.IsoCode, langFr.IsoCode}); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langGb.IsoCode, langFr.IsoCode }); Assert.IsTrue(published.Success); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langFr.IsoCode); - //audit log will only show that french was unpublished - var lastLog = AuditService.GetLogs(content.Id).Last(); + PublishResult unpublished = ContentService.Unpublish(content, langFr.IsoCode); + + // audit log will only show that french was unpublished + IAuditItem lastLog = AuditService.GetLogs(content.Id).Last(); Assert.AreEqual($"Unpublished languages: French (France)", lastLog.Comment); - //re-get + // re-get content = ContentService.GetById(content.Id); content.SetCultureName("content-en", langGb.IsoCode); unpublished = ContentService.Unpublish(content, langGb.IsoCode); - //audit log will only show that english was published + + // audit log will only show that english was published var logs = AuditService.GetLogs(content.Id).ToList(); - Assert.AreEqual($"Unpublished languages: English (United Kingdom)", logs[logs.Count - 2].Comment); - Assert.AreEqual($"Unpublished (mandatory language unpublished)", logs[logs.Count - 1].Comment); + Assert.AreEqual($"Unpublished languages: English (United Kingdom)", logs[^2].Comment); + Assert.AreEqual($"Unpublished (mandatory language unpublished)", logs[^1].Comment); } [Test] public void Can_Publish_Content_1() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(published.Success, Is.True); @@ -1030,10 +1046,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Publish_Content_2() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act - var published = ContentService.SaveAndPublish(content, userId: 0); + PublishResult published = ContentService.SaveAndPublish(content, userId: 0); // Assert Assert.That(published.Success, Is.True); @@ -1044,10 +1060,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void IsPublishable() { // Arrange - var parent = ContentService.Create("parent", Constants.System.Root, "umbTextpage"); + IContent parent = ContentService.Create("parent", Constants.System.Root, "umbTextpage"); ContentService.SaveAndPublish(parent); - var content = ContentService.Create("child", parent, "umbTextpage"); + IContent content = ContentService.Create("child", parent, "umbTextpage"); ContentService.Save(content); Assert.IsTrue(ContentService.IsPathPublishable(content)); @@ -1063,19 +1079,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // tests that during 'publishing' event, what we get from the repo is the 'old' content, // because 'publishing' fires before the 'saved' event ie before the content is actually // saved - try { - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); Assert.AreEqual("Home", content.Name); content.Name = "foo"; - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); Assert.That(published.Success, Is.True); Assert.That(content.Published, Is.True); - var e = ContentService.GetById(content.Id); + IContent e = ContentService.GetById(content.Id); Assert.AreEqual("foo", e.Name); } finally @@ -1087,23 +1102,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void ContentServiceOnPublishing(IContentService sender, PublishEventArgs args) { Assert.AreEqual(1, args.PublishedEntities.Count()); - var entity = args.PublishedEntities.First(); + IContent entity = args.PublishedEntities.First(); Assert.AreEqual("foo", entity.Name); - var e = ContentService.GetById(entity.Id); + IContent e = ContentService.GetById(entity.Id); Assert.AreEqual("Home", e.Name); } [Test] public void Can_Not_Publish_Invalid_Cultures() { - var content = new ContentBuilder() + Content content = new ContentBuilder() .AddContentType() .WithContentVariation(ContentVariation.Culture) .Done() .Build(); - Assert.Throws(() => ContentService.SaveAndPublish(content, new[] {"*"})); + Assert.Throws(() => ContentService.SaveAndPublish(content, new[] { "*" })); Assert.Throws(() => ContentService.SaveAndPublish(content, new string[] { null })); Assert.Throws(() => ContentService.SaveAndPublish(content, new[] { "*", null })); Assert.Throws(() => ContentService.SaveAndPublish(content, new[] { "en-US", "*", "es-ES" })); @@ -1112,60 +1127,59 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Only_Valid_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parentId = Textpage.Id; + int parentId = Textpage.Id; - var parent = ContentService.GetById(parentId); + IContent parent = ContentService.GetById(parentId); - var parentPublished = ContentService.SaveAndPublish(parent); + PublishResult parentPublished = ContentService.SaveAndPublish(parent); // parent can publish values // and therefore can be published Assert.IsTrue(parentPublished.Success); Assert.IsTrue(parent.Published); - var content = ContentBuilder.CreateSimpleContent(contentType, "Invalid Content", parentId); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Invalid Content", parentId); content.SetValue("author", string.Empty); Assert.IsFalse(content.HasIdentity); // content cannot publish values because they are invalid var propertyValidationService = new PropertyValidationService(PropertyEditorCollection, DataTypeService, TextService); - var isValid = propertyValidationService.IsPropertyDataValid(content, out var invalidProperties, CultureImpact.Invariant); + bool isValid = propertyValidationService.IsPropertyDataValid(content, out IProperty[] invalidProperties, CultureImpact.Invariant); Assert.IsFalse(isValid); Assert.IsNotEmpty(invalidProperties); // and therefore cannot be published, // because it did not have a published version at all - var contentPublished = ContentService.SaveAndPublish(content); + PublishResult contentPublished = ContentService.SaveAndPublish(content); Assert.IsFalse(contentPublished.Success); Assert.AreEqual(PublishResultType.FailedPublishContentInvalid, contentPublished.Result); Assert.IsFalse(content.Published); - //Ensure it saved though + // Ensure it saved though Assert.Greater(content.Id, 0); Assert.IsTrue(content.HasIdentity); } - [Test] public void Can_Publish_And_Unpublish_Cultures_In_Single_Operation() { - //TODO: This is using an internal API - we aren't exposing this publicly (at least for now) but we'll keep the test around - var langFr = new LanguageBuilder() + // TODO: This is using an internal API - we aren't exposing this publicly (at least for now) but we'll keep the test around + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr") .Build(); - var langDa = new LanguageBuilder() + ILanguage langDa = new LanguageBuilder() .WithCultureInfo("da") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langDa); - var ct = ContentTypeBuilder.CreateBasicContentType(); + ContentType ct = ContentTypeBuilder.CreateBasicContentType(); ct.Variations = ContentVariation.Culture; ContentTypeService.Save(ct); @@ -1174,7 +1188,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("name-da", langDa.IsoCode); content.PublishCulture(CultureImpact.Explicit(langFr.IsoCode, langFr.IsDefault)); - var result = ((ContentService)ContentService).CommitDocumentChanges(content); + PublishResult result = ((ContentService)ContentService).CommitDocumentChanges(content); Assert.IsTrue(result.Success); content = ContentService.GetById(content.Id); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); @@ -1197,18 +1211,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private IEnumerable MapPublishValues(IEnumerable documents, Func map) { var exclude = new HashSet(); - foreach (var document in documents) + foreach (IContent document in documents) { if (exclude.Contains(document.ParentId)) { exclude.Add(document.Id); continue; } + if (!map(document)) { exclude.Add(document.Id); continue; } + yield return document; } } @@ -1216,19 +1232,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Content_Children() { - var parentId = Textpage.Id; + int parentId = Textpage.Id; - var parent = ContentService.GetById(parentId); + IContent parent = ContentService.GetById(parentId); Console.WriteLine(" " + parent.Id); const int pageSize = 500; - var page = 0; - var total = long.MaxValue; - while(page * pageSize < total) + int page = 0; + long total = long.MaxValue; + while (page * pageSize < total) { - var descendants = ContentService.GetPagedDescendants(parent.Id, page++, pageSize, out total); - foreach (var x in descendants) + IEnumerable descendants = ContentService.GetPagedDescendants(parent.Id, page++, pageSize, out total); + foreach (IContent x in descendants) + { Console.WriteLine(" ".Substring(0, x.Level) + x.Id); + } } Console.WriteLine(); @@ -1236,16 +1254,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // publish parent & its branch // only those that are not already published // only invariant/neutral values - var parentPublished = ContentService.SaveAndPublishBranch(parent, true); + IEnumerable parentPublished = ContentService.SaveAndPublishBranch(parent, true); - foreach (var result in parentPublished) + foreach (PublishResult result in parentPublished) + { Console.WriteLine(" ".Substring(0, result.Content.Level) + $"{result.Content.Id}: {result.Result}"); + } // everything should be successful Assert.IsTrue(parentPublished.All(x => x.Success)); Assert.IsTrue(parent.Published); - var children = ContentService.GetPagedChildren(parentId, 0, 500, out var totalChildren); //we only want the first so page size, etc.. is abitrary + IEnumerable children = ContentService.GetPagedChildren(parentId, 0, 500, out long totalChildren); // we only want the first so page size, etc.. is abitrary // children are published including ... that was released 5 mins ago Assert.IsTrue(children.First(x => x.Id == Subpage.Id).Published); @@ -1255,15 +1275,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Expired_Content() { // Arrange - var content = ContentService.GetById(Subpage.Id); //This Content expired 5min ago + IContent content = ContentService.GetById(Subpage.Id); // This Content expired 5min ago content.ContentSchedule.Add(null, DateTime.Now.AddMinutes(-5)); ContentService.Save(content); - var parent = ContentService.GetById(Textpage.Id); - var parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId);//Publish root Home node to enable publishing of 'Subpage.Id' + IContent parent = ContentService.GetById(Textpage.Id); + PublishResult parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId); // Publish root Home node to enable publishing of 'Subpage.Id' // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(parentPublished.Success, Is.True); @@ -1275,16 +1295,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Cannot_Publish_Expired_Culture() { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateBasicContent(contentType); + Content content = ContentBuilder.CreateBasicContent(contentType); content.SetCultureName("Hello", "en-US"); content.ContentSchedule.Add("en-US", null, DateTime.Now.AddMinutes(-5)); ContentService.Save(content); - var published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); Assert.IsFalse(published.Success); Assert.AreEqual(PublishResultType.FailedPublishCultureHasExpired, published.Result); @@ -1295,15 +1315,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Content_Awaiting_Release() { // Arrange - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); content.ContentSchedule.Add(DateTime.Now.AddHours(2), null); ContentService.Save(content, Constants.Security.SuperUserId); - var parent = ContentService.GetById(Textpage.Id); - var parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId);//Publish root Home node to enable publishing of 'Subpage.Id' + IContent parent = ContentService.GetById(Textpage.Id); + PublishResult parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId); // Publish root Home node to enable publishing of 'Subpage.Id' // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(parentPublished.Success, Is.True); @@ -1315,16 +1335,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Cannot_Publish_Culture_Awaiting_Release() { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateBasicContent(contentType); + Content content = ContentBuilder.CreateBasicContent(contentType); content.SetCultureName("Hello", "en-US"); content.ContentSchedule.Add("en-US", DateTime.Now.AddHours(2), null); ContentService.Save(content); - var published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); Assert.IsFalse(published.Success); Assert.AreEqual(PublishResultType.FailedPublishCultureAwaitingRelease, published.Result); @@ -1335,11 +1355,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Content_Where_Parent_Is_Unpublished() { // Arrange - var content = ContentService.Create("Subpage with Unpublished Parent", Textpage.Id, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Subpage with Unpublished Parent", Textpage.Id, "umbTextpage", Constants.Security.SuperUserId); ContentService.Save(content, Constants.Security.SuperUserId); // Act - var published = ContentService.SaveAndPublishBranch(content, true); + IEnumerable published = ContentService.SaveAndPublishBranch(content, true); // Assert Assert.That(published.All(x => x.Success), Is.False); @@ -1350,10 +1370,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Trashed_Content() { // Arrange - var content = ContentService.GetById(Trashed.Id); + IContent content = ContentService.GetById(Trashed.Id); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(published.Success, Is.False); @@ -1365,11 +1385,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_And_Publish_Content() { // Arrange - var content = ContentService.Create("Home US", - 1, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Home US", -1, "umbTextpage", Constants.Security.SuperUserId); content.SetValue("author", "Barack Obama"); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(content.HasIdentity, Is.True); @@ -1388,17 +1408,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_And_Publish_Content_And_Child_Without_Identity() { // Arrange - var content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); content.SetValue("author", "Barack Obama"); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); - var childContent = ContentService.Create("Child", content.Id, "umbTextpage", Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + IContent childContent = ContentService.Create("Child", content.Id, "umbTextpage", Constants.Security.SuperUserId); + // Reset all identity properties childContent.Id = 0; childContent.Path = null; ((Content)childContent).ResetIdentity(); - var childPublished = ContentService.SaveAndPublish(childContent, userId: Constants.Security.SuperUserId); + PublishResult childPublished = ContentService.SaveAndPublish(childContent, userId: Constants.Security.SuperUserId); // Assert Assert.That(content.HasIdentity, Is.True); @@ -1413,13 +1434,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Published_Descendant_Versions() { // Arrange - var root = ContentService.GetById(Textpage.Id); - var rootPublished = ContentService.SaveAndPublish(root); + IContent root = ContentService.GetById(Textpage.Id); + PublishResult rootPublished = ContentService.SaveAndPublish(root); - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); content.Properties["title"].SetValue(content.Properties["title"].GetValue() + " Published"); - var contentPublished = ContentService.SaveAndPublish(content); - var publishedVersion = content.VersionId; + PublishResult contentPublished = ContentService.SaveAndPublish(content); + int publishedVersion = content.VersionId; content.Properties["title"].SetValue(content.Properties["title"].GetValue() + " Saved"); ContentService.Save(content); @@ -1433,20 +1454,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(rootPublished.Success); Assert.IsTrue(contentPublished.Success); - //Console.WriteLine(publishedVersion); - //foreach (var d in publishedDescendants) Console.WriteLine(d.Version); + // Console.WriteLine(publishedVersion); + // foreach (var d in publishedDescendants) Console.WriteLine(d.Version); Assert.IsTrue(publishedDescendants.Any(x => x.VersionId == publishedVersion)); - //Ensure that the published content version has the correct property value and is marked as published - var publishedContentVersion = publishedDescendants.First(x => x.VersionId == publishedVersion); + // Ensure that the published content version has the correct property value and is marked as published + IContent publishedContentVersion = publishedDescendants.First(x => x.VersionId == publishedVersion); Assert.That(publishedContentVersion.Published, Is.True); Assert.That(publishedContentVersion.Properties["title"].GetValue(published: true), Contains.Substring("Published")); // and has the correct draft properties Assert.That(publishedContentVersion.Properties["title"].GetValue(), Contains.Substring("Saved")); - //Ensure that the latest version of the content is ok - var currentContent = ContentService.GetById(Subpage.Id); + // Ensure that the latest version of the content is ok + IContent currentContent = ContentService.GetById(Subpage.Id); Assert.That(currentContent.Published, Is.True); Assert.That(currentContent.Properties["title"].GetValue(published: true), Contains.Substring("Published")); Assert.That(currentContent.Properties["title"].GetValue(), Contains.Substring("Saved")); @@ -1457,7 +1478,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_Content() { // Arrange - var content = ContentService.Create("Home US", - 1, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Home US", -1, "umbTextpage", Constants.Security.SuperUserId); content.SetValue("author", "Barack Obama"); // Act @@ -1470,7 +1491,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Update_Content_Property_Values() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); @@ -1511,7 +1532,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("new author text", content.GetValue("author")); // make sure that the published version remained the same - var publishedContent = ContentService.GetVersion(content.PublishedVersionId); + IContent publishedContent = ContentService.GetVersion(content.PublishedVersionId); Assert.AreEqual("another title of mine", publishedContent.GetValue("title")); Assert.IsNull(publishedContent.GetValue("bodyText")); Assert.AreEqual("new author", publishedContent.GetValue("author")); @@ -1521,10 +1542,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Bulk_Save_Content() { // Arrange - var contentType = ContentTypeService.Get("umbTextpage"); - var subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 1", Textpage.Id); - var subpage2 = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 2", Textpage.Id); - var list = new List {subpage, subpage2}; + IContentType contentType = ContentTypeService.Get("umbTextpage"); + Content subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 1", Textpage.Id); + Content subpage2 = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 2", Textpage.Id); + var list = new List { subpage, subpage2 }; // Act ContentService.Save(list, Constants.Security.SuperUserId); @@ -1544,21 +1565,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); - //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown - Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); + // all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown + Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); } [Test] public void Can_Delete_Content_Of_Specific_ContentType() { // Arrange - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); // Act ContentService.DeleteOfType(contentType.Id); - var rootContent = ContentService.GetRootContent(); - var contents = ContentService.GetPagedOfType(contentType.Id, 0, int.MaxValue, out var _, null); + IEnumerable rootContent = ContentService.GetRootContent(); + IEnumerable contents = ContentService.GetPagedOfType(contentType.Id, 0, int.MaxValue, out long _, null); // Assert Assert.That(rootContent.Any(), Is.False); @@ -1569,11 +1590,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Delete_Content() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act ContentService.Delete(content, Constants.Security.SuperUserId); - var deleted = ContentService.GetById(Textpage.Id); + IContent deleted = ContentService.GetById(Textpage.Id); // Assert Assert.That(deleted, Is.Null); @@ -1583,7 +1604,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Content_To_RecycleBin() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act ContentService.MoveToRecycleBin(content, Constants.Security.SuperUserId); @@ -1596,18 +1617,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Move_Content_Structure_To_RecycleBin_And_Empty_RecycleBin() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var subsubpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 3", Subpage.Id); + Content subsubpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 3", Subpage.Id); ContentService.Save(subsubpage, Constants.Security.SuperUserId); - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); const int pageSize = 500; - var page = 0; - var total = long.MaxValue; + int page = 0; + long total = long.MaxValue; var descendants = new List(); - while(page * pageSize < total) + while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(content.Id, page++, pageSize, out total)); + } Assert.AreNotEqual(-20, content.ParentId); Assert.IsFalse(content.Trashed); @@ -1620,7 +1643,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services descendants.Clear(); page = 0; while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(content.Id, page++, pageSize, out total)); + } Assert.AreEqual(-20, content.ParentId); Assert.IsTrue(content.Trashed); @@ -1629,7 +1654,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.True(descendants.All(x => x.Trashed)); ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var trashed = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var trashed = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); Assert.IsEmpty(trashed); } @@ -1639,7 +1664,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); // Assert Assert.That(contents.Any(), Is.False); @@ -1649,36 +1674,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Ensures_Permissions_Are_Retained_For_Copied_Descendants_With_Explicit_Permissions() { // Arrange - var userGroup = UserGroupBuilder.CreateUserGroup("1"); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup("1"); UserService.Save(userGroup); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentType.AllowedContentTypes = new List { new ContentTypeSort(new Lazy(() => contentType.Id), 0, contentType.Alias) }; ContentTypeService.Save(contentType); - var parentPage = ContentBuilder.CreateSimpleContent(contentType); + Content parentPage = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage); - var childPage = ContentBuilder.CreateSimpleContent(contentType, "child", parentPage); + Content childPage = ContentBuilder.CreateSimpleContent(contentType, "child", parentPage); ContentService.Save(childPage); - //assign explicit permissions to the child + + // assign explicit permissions to the child ContentService.SetPermission(childPage, 'A', new[] { userGroup.Id }); - //Ok, now copy, what should happen is the childPage will retain it's own permissions - var parentPage2 = ContentBuilder.CreateSimpleContent(contentType); + // Ok, now copy, what should happen is the childPage will retain it's own permissions + Content parentPage2 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage2); - var copy = ContentService.Copy(childPage, parentPage2.Id, false, true); + IContent copy = ContentService.Copy(childPage, parentPage2.Id, false, true); - //get the permissions and verify - var permissions = UserService.GetPermissionsForPath(userGroup, copy.Path, fallbackToDefaultPermissions: true); - var allPermissions = permissions.GetAllPermissions().ToArray(); + // get the permissions and verify + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, copy.Path, fallbackToDefaultPermissions: true); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(1, allPermissions.Length); Assert.AreEqual("A", allPermissions[0]); } @@ -1687,65 +1713,71 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Ensures_Permissions_Are_Inherited_For_Copied_Descendants() { // Arrange - var userGroup = UserGroupBuilder.CreateUserGroup("1"); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup("1"); UserService.Save(userGroup); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentType.AllowedContentTypes = new List { new ContentTypeSort(new Lazy(() => contentType.Id), 0, contentType.Alias) }; ContentTypeService.Save(contentType); - var parentPage = ContentBuilder.CreateSimpleContent(contentType); + Content parentPage = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage); ContentService.SetPermission(parentPage, 'A', new[] { userGroup.Id }); - var childPage1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parentPage); + Content childPage1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parentPage); ContentService.Save(childPage1); - var childPage2 = ContentBuilder.CreateSimpleContent(contentType, "child2", childPage1); + Content childPage2 = ContentBuilder.CreateSimpleContent(contentType, "child2", childPage1); ContentService.Save(childPage2); - var childPage3 = ContentBuilder.CreateSimpleContent(contentType, "child3", childPage2); + Content childPage3 = ContentBuilder.CreateSimpleContent(contentType, "child3", childPage2); ContentService.Save(childPage3); - //Verify that the children have the inherited permissions + // Verify that the children have the inherited permissions var descendants = new List(); const int pageSize = 500; - var page = 0; - var total = long.MaxValue; - while(page * pageSize < total) + int page = 0; + long total = long.MaxValue; + while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(parentPage.Id, page++, pageSize, out total)); + } + Assert.AreEqual(3, descendants.Count); - foreach (var descendant in descendants) + foreach (IContent descendant in descendants) { - var permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); - var allPermissions = permissions.GetAllPermissions().ToArray(); + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(1, allPermissions.Length); Assert.AreEqual("A", allPermissions[0]); } - //create a new parent with a new permission structure - var parentPage2 = ContentBuilder.CreateSimpleContent(contentType); + // create a new parent with a new permission structure + Content parentPage2 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage2); ContentService.SetPermission(parentPage2, 'B', new[] { userGroup.Id }); - //Now copy, what should happen is the child pages will now have permissions inherited from the new parent - var copy = ContentService.Copy(childPage1, parentPage2.Id, false, true); + // Now copy, what should happen is the child pages will now have permissions inherited from the new parent + IContent copy = ContentService.Copy(childPage1, parentPage2.Id, false, true); descendants.Clear(); page = 0; while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(parentPage2.Id, page++, pageSize, out total)); + } + Assert.AreEqual(3, descendants.Count); - foreach (var descendant in descendants) + foreach (IContent descendant in descendants) { - var permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); - var allPermissions = permissions.GetAllPermissions().ToArray(); + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(1, allPermissions.Length); Assert.AreEqual("B", allPermissions[0]); } @@ -1755,7 +1787,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Empty_RecycleBin_With_Content_That_Has_All_Related_Data() { // Arrange - //need to: + // need to: // * add relations // * add permissions // * add notifications @@ -1764,8 +1796,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // * domain // * published & preview data // * multiple versions - - var contentType = ContentTypeBuilder.CreateAllTypesContentType("test", "test"); + ContentType contentType = ContentTypeBuilder.CreateAllTypesContentType("test", "test"); ContentTypeService.Save(contentType, Constants.Security.SuperUserId); object obj = @@ -1773,23 +1804,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { tags = "[\"Hello\",\"World\"]" }; - var content1 = ContentBuilder.CreateBasicContent(contentType); + Content content1 = ContentBuilder.CreateBasicContent(contentType); content1.PropertyValues(obj); content1.ResetDirtyProperties(false); ContentService.Save(content1, Constants.Security.SuperUserId); Assert.IsTrue(ContentService.SaveAndPublish(content1, userId: 0).Success); - var content2 = ContentBuilder.CreateBasicContent(contentType); + Content content2 = ContentBuilder.CreateBasicContent(contentType); content2.PropertyValues(obj); content2.ResetDirtyProperties(false); ContentService.Save(content2, Constants.Security.SuperUserId); Assert.IsTrue(ContentService.SaveAndPublish(content2, userId: 0).Success); - var editorGroup = UserService.GetUserGroupByAlias(Constants.Security.EditorGroupAlias); + IUserGroup editorGroup = UserService.GetUserGroupByAlias(Constants.Security.EditorGroupAlias); editorGroup.StartContentId = content1.Id; UserService.Save(editorGroup); - var admin = UserService.GetUserById(Constants.Security.SuperUserId); - admin.StartContentIds = new[] {content1.Id}; + IUser admin = UserService.GetUserById(Constants.Security.SuperUserId); + admin.StartContentIds = new[] { content1.Id }; UserService.Save(admin); RelationService.Save(new RelationType("test", "test", false, Constants.ObjectTypes.Document, Constants.ObjectTypes.Document)); @@ -1805,8 +1836,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services })); Assert.IsTrue(PublicAccessService.AddRule(content1, "test2", "test2").Success); - var user = UserService.GetUserById(Constants.Security.SuperUserId); - var userGroup = UserService.GetUserGroupByAlias(user.Groups.First().Alias); + IUser user = UserService.GetUserById(Constants.Security.SuperUserId); + IUserGroup userGroup = UserService.GetUserGroupByAlias(user.Groups.First().Alias); Assert.IsNotNull(NotificationService.CreateNotification(user, content1, "X")); ContentService.SetPermission(content1, 'A', new[] { userGroup.Id }); @@ -1819,7 +1850,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Act ContentService.MoveToRecycleBin(content1, Constants.Security.SuperUserId); ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); // Assert Assert.That(contents.Any(), Is.False); @@ -1829,7 +1860,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Content() { // Arrange - var content = ContentService.GetById(Trashed.Id); + IContent content = ContentService.GetById(Trashed.Id); // Act - moving out of recycle bin ContentService.Move(content, Textpage.Id); @@ -1844,64 +1875,64 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_Content() { // Arrange - var temp = ContentService.GetById(Subpage.Id); + IContent temp = ContentService.GetById(Subpage.Id); // Act - var copy = ContentService.Copy(temp, temp.ParentId, false, Constants.Security.SuperUserId); - var content = ContentService.GetById(Subpage.Id); + IContent copy = ContentService.Copy(temp, temp.ParentId, false, Constants.Security.SuperUserId); + IContent content = ContentService.GetById(Subpage.Id); // Assert Assert.That(copy, Is.Not.Null); Assert.That(copy.Id, Is.Not.EqualTo(content.Id)); Assert.AreNotSame(content, copy); - foreach (var property in copy.Properties) + foreach (IProperty property in copy.Properties) { Assert.AreEqual(property.GetValue(), content.Properties[property.Alias].GetValue()); } - //Assert.AreNotEqual(content.Name, copy.Name); + + // Assert.AreNotEqual(content.Name, copy.Name); } [Test] public void Can_Copy_And_Modify_Content_With_Events() { // see https://github.com/umbraco/Umbraco-CMS/issues/5513 - - TypedEventHandler> copying = (sender, args) => + static void Copying(IContentService sender, CopyEventArgs args) { args.Copy.SetValue("title", "1"); args.Original.SetValue("title", "2"); - }; + } - TypedEventHandler> copied = (sender, args) => + static void Copied(IContentService sender, CopyEventArgs args) { - var copyVal = args.Copy.GetValue("title"); - var origVal = args.Original.GetValue("title"); + string copyVal = args.Copy.GetValue("title"); + string origVal = args.Original.GetValue("title"); Assert.AreEqual("1", copyVal); Assert.AreEqual("2", origVal); - }; + } try { - ContentService.Copying += copying; - ContentService.Copied += copied; + ContentService.Copying += Copying; + ContentService.Copied += Copied; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); content.SetValue("title", "New Value"); ContentService.Save(content); - var copy = ContentService.Copy(content, content.ParentId, false, Constants.Security.SuperUserId); + IContent copy = ContentService.Copy(content, content.ParentId, false, Constants.Security.SuperUserId); Assert.AreEqual("1", copy.GetValue("title")); } finally { - ContentService.Copying -= copying; - ContentService.Copied -= copied; + ContentService.Copying -= Copying; + ContentService.Copied -= Copied; } } @@ -1909,13 +1940,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_Recursive() { // Arrange - var temp = ContentService.GetById(Textpage.Id); + IContent temp = ContentService.GetById(Textpage.Id); Assert.AreEqual("Home", temp.Name); Assert.AreEqual(2, ContentService.CountChildren(temp.Id)); // Act - var copy = ContentService.Copy(temp, temp.ParentId, false, true, Constants.Security.SuperUserId); - var content = ContentService.GetById(Textpage.Id); + IContent copy = ContentService.Copy(temp, temp.ParentId, false, true, Constants.Security.SuperUserId); + IContent content = ContentService.GetById(Textpage.Id); // Assert Assert.That(copy, Is.Not.Null); @@ -1923,8 +1954,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreNotSame(content, copy); Assert.AreEqual(2, ContentService.CountChildren(copy.Id)); - var child = ContentService.GetById(Subpage.Id); - var childCopy = ContentService.GetPagedChildren(copy.Id, 0, 500, out var total).First(); + IContent child = ContentService.GetById(Subpage.Id); + IContent childCopy = ContentService.GetPagedChildren(copy.Id, 0, 500, out long total).First(); Assert.AreEqual(childCopy.Name, child.Name); Assert.AreNotEqual(childCopy.Id, child.Id); Assert.AreNotEqual(childCopy.Key, child.Key); @@ -1934,13 +1965,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_NonRecursive() { // Arrange - var temp = ContentService.GetById(Textpage.Id); + IContent temp = ContentService.GetById(Textpage.Id); Assert.AreEqual("Home", temp.Name); Assert.AreEqual(2, ContentService.CountChildren(temp.Id)); // Act - var copy = ContentService.Copy(temp, temp.ParentId, false, false, Constants.Security.SuperUserId); - var content = ContentService.GetById(Textpage.Id); + IContent copy = ContentService.Copy(temp, temp.ParentId, false, false, Constants.Security.SuperUserId); + IContent content = ContentService.GetById(Textpage.Id); // Assert Assert.That(copy, Is.Not.Null); @@ -1956,23 +1987,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // create a content type that has a 'tags' property // the property needs to support tags, else nothing works of course! - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleTagsContentType("umbTagsPage", "TagsPage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleTagsContentType("umbTagsPage", "TagsPage", defaultTemplateId: template.Id); contentType.Key = new Guid("78D96D30-1354-4A1E-8450-377764200C58"); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Simple Tags Page", Constants.System.Root); - content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, propAlias, new[] {"hello", "world"}); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Simple Tags Page", Constants.System.Root); + content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, propAlias, new[] { "hello", "world" }); ContentService.Save(content); // value has been set but no tags have been created (not published) Assert.AreEqual("[\"hello\",\"world\"]", content.GetValue(propAlias)); - var contentTags = TagService.GetTagsForEntity(content.Id).ToArray(); + ITag[] contentTags = TagService.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(0, contentTags.Length); // reloading the content yields the same result - content = (Content) ContentService.GetById(content.Id); + content = (Content)ContentService.GetById(content.Id); Assert.AreEqual("[\"hello\",\"world\"]", content.GetValue(propAlias)); contentTags = TagService.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(0, contentTags.Length); @@ -1986,11 +2017,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, contentTags.Length); // copy - var copy = ContentService.Copy(content, content.ParentId, false); + IContent copy = ContentService.Copy(content, content.ParentId, false); // copy is not published, so property has value, but no tags have been created Assert.AreEqual("[\"hello\",\"world\"]", copy.GetValue(propAlias)); - var copiedTags = TagService.GetTagsForEntity(copy.Id).ToArray(); + ITag[] copiedTags = TagService.GetTagsForEntity(copy.Id).ToArray(); Assert.AreEqual(0, copiedTags.Length); // publish @@ -2008,17 +2039,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Rollback_Version_On_Content() { // Arrange - var parent = ContentService.GetById(Textpage.Id); + IContent parent = ContentService.GetById(Textpage.Id); Assert.IsFalse(parent.Published); ContentService.SaveAndPublish(parent); // publishing parent, so Text Page 2 can be updated. - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); Assert.IsFalse(content.Published); var versions = ContentService.GetVersions(Subpage.Id).ToList(); Assert.AreEqual(1, versions.Count); - var version1 = content.VersionId; + int version1 = content.VersionId; content.Name = "Text Page 2 Updated"; content.SetValue("author", "Francis Doe"); @@ -2027,7 +2058,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(content.Edited); ContentService.SaveAndPublish(content); // new version - var version2 = content.VersionId; + int version2 = content.VersionId; Assert.AreNotEqual(version1, version2); Assert.IsTrue(content.Published); @@ -2051,7 +2082,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.Name = "Text Page 2 ReReUpdated"; ContentService.SaveAndPublish(content); // new version - var version3 = content.VersionId; + int version3 = content.VersionId; Assert.AreNotEqual(version2, version3); Assert.IsTrue(content.Published); @@ -2067,8 +2098,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // version3, third and current published version // rollback all values to version1 - var rollback = ContentService.GetById(Subpage.Id); - var rollto = ContentService.GetVersion(version1); + IContent rollback = ContentService.GetById(Subpage.Id); + IContent rollto = ContentService.GetVersion(version1); rollback.CopyFrom(rollto); rollback.Name = rollto.Name; // must do it explicitly ContentService.Save(rollback); @@ -2089,8 +2120,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rollback all values to current version // special because... current has edits... this really is equivalent to rolling back to version2 - var rollback2 = ContentService.GetById(Subpage.Id); - var rollto2 = ContentService.GetVersion(version3); + IContent rollback2 = ContentService.GetById(Subpage.Id); + IContent rollto2 = ContentService.GetVersion(version3); rollback2.CopyFrom(rollto2); rollback2.Name = rollto2.PublishName; // must do it explicitely AND must pick the publish one! ContentService.Save(rollback2); @@ -2123,22 +2154,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Rollback_Version_On_Multilingual() { - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr") .Build(); - var langDa = new LanguageBuilder() + ILanguage langDa = new LanguageBuilder() .WithCultureInfo("da") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langDa); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("multi", "Multi", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("multi", "Multi", defaultTemplateId: template.Id); contentType.Key = new Guid("45FF9A70-9C5F-448D-A476-DCD23566BBF8"); contentType.Variations = ContentVariation.Culture; - var p1 = contentType.PropertyTypes.First(); + IPropertyType p1 = contentType.PropertyTypes.First(); p1.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); @@ -2155,13 +2186,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetCultureName("da1", langDa.IsoCode); Thread.Sleep(1); ContentService.Save(page); - var versionId0 = page.VersionId; + int versionId0 = page.VersionId; page.SetValue(p1.Alias, "v1fr", langFr.IsoCode); page.SetValue(p1.Alias, "v1da", langDa.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page); - var versionId1 = page.VersionId; + int versionId1 = page.VersionId; Thread.Sleep(10); @@ -2169,7 +2200,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetValue(p1.Alias, "v2fr", langFr.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page, langFr.IsoCode); - var versionId2 = page.VersionId; + int versionId2 = page.VersionId; Thread.Sleep(10); @@ -2177,7 +2208,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetValue(p1.Alias, "v2da", langDa.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page, langDa.IsoCode); - var versionId3 = page.VersionId; + int versionId3 = page.VersionId; Thread.Sleep(10); @@ -2187,26 +2218,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetValue(p1.Alias, "v3da", langDa.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page); - var versionId4 = page.VersionId; + int versionId4 = page.VersionId; // now get all versions - - var versions = ContentService.GetVersions(page.Id).ToArray(); + IContent[] versions = ContentService.GetVersions(page.Id).ToArray(); Assert.AreEqual(5, versions.Length); // current version Assert.AreEqual(versionId4, versions[0].VersionId); Assert.AreEqual(versionId3, versions[0].PublishedVersionId); + // published version Assert.AreEqual(versionId3, versions[1].VersionId); Assert.AreEqual(versionId3, versions[1].PublishedVersionId); + // previous version Assert.AreEqual(versionId2, versions[2].VersionId); Assert.AreEqual(versionId3, versions[2].PublishedVersionId); + // previous version Assert.AreEqual(versionId1, versions[3].VersionId); Assert.AreEqual(versionId3, versions[3].PublishedVersionId); + // previous version Assert.AreEqual(versionId0, versions[4].VersionId); Assert.AreEqual(versionId3, versions[4].PublishedVersionId); @@ -2236,24 +2270,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("da3", versions[0].GetCultureName(langDa.IsoCode)); // all versions have the same publish infos - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Assert.AreEqual(versions[0].PublishDate, versions[i].PublishDate); Assert.AreEqual(versions[0].GetPublishDate(langFr.IsoCode), versions[i].GetPublishDate(langFr.IsoCode)); Assert.AreEqual(versions[0].GetPublishDate(langDa.IsoCode), versions[i].GetPublishDate(langDa.IsoCode)); } - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Console.Write("[{0}] ", i); - Console.WriteLine(versions[i].UpdateDate.ToString("O").Substring(11)); - Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O").Substring(11)); - Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O").Substring(11)); + Console.WriteLine(versions[i].UpdateDate.ToString("O")[11..]); + Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O")[11..]); + Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O")[11..]); } + Console.WriteLine("-"); // for all previous versions, UpdateDate is the published date - Assert.AreEqual(versions[4].UpdateDate, versions[4].GetUpdateDate(langFr.IsoCode)); Assert.AreEqual(versions[4].UpdateDate, versions[4].GetUpdateDate(langDa.IsoCode)); @@ -2264,28 +2298,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(versions[2].UpdateDate, versions[2].GetUpdateDate(langDa.IsoCode)); // for the published version, UpdateDate is the published date - Assert.AreEqual(versions[1].UpdateDate, versions[1].GetUpdateDate(langFr.IsoCode)); Assert.AreEqual(versions[1].UpdateDate, versions[1].GetUpdateDate(langDa.IsoCode)); Assert.AreEqual(versions[1].PublishDate, versions[1].UpdateDate); // for the current version, things are different // UpdateDate is the date it was last saved - Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langFr.IsoCode)); Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langDa.IsoCode)); // so if we save again... page.SetCultureName("fr4", langFr.IsoCode); - //page.SetCultureName("da4", langDa.IsoCode); + + // page.SetCultureName("da4", langDa.IsoCode); page.SetValue(p1.Alias, "v4fr", langFr.IsoCode); page.SetValue(p1.Alias, "v4da", langDa.IsoCode); + // This sleep ensures the save is called on later ticks then the SetValue and SetCultureName. Therefore // we showcase the currect lack of handling dirty on variants on save. When this is implemented the sleep // helps showcase the functionality is actually working Thread.Sleep(5); ContentService.Save(page); - var versionId5 = page.VersionId; + int versionId5 = page.VersionId; versions = ContentService.GetVersions(page.Id).ToArray(); @@ -2293,29 +2327,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, versions.Length); Assert.AreEqual(versionId4, versionId5); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Console.Write("[{0}] ", i); - Console.WriteLine(versions[i].UpdateDate.ToString("O").Substring(11)); - Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O").Substring(11)); - Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O").Substring(11)); + Console.WriteLine(versions[i].UpdateDate.ToString("O")[11..]); + Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O")[11..]); + Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O")[11..]); } + Console.WriteLine("-"); - var versionsSlim = ContentService.GetVersionsSlim(page.Id, 0, 50).ToArray(); + IContent[] versionsSlim = ContentService.GetVersionsSlim(page.Id, 0, 50).ToArray(); Assert.AreEqual(5, versionsSlim.Length); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Console.Write("[{0}] ", i); Console.WriteLine(versionsSlim[i].UpdateDate.Ticks); Console.WriteLine(" fr: {0}", versionsSlim[i].GetUpdateDate(langFr.IsoCode)?.Ticks); Console.WriteLine(" da: {0}", versionsSlim[i].GetUpdateDate(langDa.IsoCode)?.Ticks); } + Console.WriteLine("-"); // what we do in the controller to get rollback versions - var versionsSlimFr = versionsSlim.Where(x => x.UpdateDate == x.GetUpdateDate(langFr.IsoCode)).ToArray(); + IContent[] versionsSlimFr = versionsSlim.Where(x => x.UpdateDate == x.GetUpdateDate(langFr.IsoCode)).ToArray(); // TODO this should expect 4, but as the comment below tells we are "*not* properly track 'dirty' for culture" // This should be changed to 4 as soon a this functionality works. Currently it is always 3 due to the sleep @@ -2325,8 +2361,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // alas, at the moment we do *not* properly track 'dirty' for cultures, meaning // that we cannot synchronize dates the way we do with publish dates - and so this // would fail - the version UpdateDate is greater than the cultures'. - //Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langFr.IsoCode)); - //Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langDa.IsoCode)); + // Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langFr.IsoCode)); + // Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langDa.IsoCode)); // now roll french back to its very first version page.CopyFrom(versions[4], langFr.IsoCode); // only the pure FR values @@ -2345,18 +2381,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Save_Lazy_Content() { - var contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentService.GetById(Textpage.Id); + IContentType contentType = ContentTypeService.Get("umbTextpage"); + IContent root = ContentService.GetById(Textpage.Id); var c = new Lazy(() => ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Page", root.Id)); var c2 = new Lazy(() => ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Subpage", c.Value.Id)); - var list = new List> {c, c2}; + var list = new List> { c, c2 }; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + IDocumentRepository repository = DocumentRepository; - foreach (var content in list) + foreach (Lazy content in list) { repository.Save(content.Value); } @@ -2370,22 +2406,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(c.Value.ParentId > 0, Is.True); Assert.That(c2.Value.ParentId > 0, Is.True); } - } [Test] public void Can_Verify_Property_Types_On_Content() { // Arrange - var contentTypeService = ContentTypeService; - var contentType = ContentTypeBuilder.CreateAllTypesContentType("allDataTypes", "All DataTypes"); + IContentTypeService contentTypeService = ContentTypeService; + ContentType contentType = ContentTypeBuilder.CreateAllTypesContentType("allDataTypes", "All DataTypes"); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateAllTypesContent(contentType, "Random Content", Constants.System.Root); + Content content = ContentBuilder.CreateAllTypesContent(contentType, "Random Content", Constants.System.Root); ContentService.Save(content); - var id = content.Id; + int id = content.Id; // Act - var sut = ContentService.GetById(id); + IContent sut = ContentService.GetById(id); // Arrange Assert.That(sut.GetValue("isTrue"), Is.True); @@ -2395,8 +2430,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(sut.GetValue("multilineText"), Is.EqualTo("Multiple lines \n in one box")); Assert.That(sut.GetValue("upload"), Is.EqualTo("/media/1234/koala.jpg")); Assert.That(sut.GetValue("label"), Is.EqualTo("Non-editable label")); - //SD: This is failing because the 'content' call to GetValue always has empty milliseconds - //MCH: I'm guessing this is an issue because of the format the date is actually stored as, right? Cause we don't do any formatting when saving or loading + + // SD: This is failing because the 'content' call to GetValue always has empty milliseconds + // MCH: I'm guessing this is an issue because of the format the date is actually stored as, right? Cause we don't do any formatting when saving or loading Assert.That(sut.GetValue("dateTime").ToString("G"), Is.EqualTo(content.GetValue("dateTime").ToString("G"))); Assert.That(sut.GetValue("colorPicker"), Is.EqualTo("black")); Assert.That(sut.GetValue("ddlMultiple"), Is.EqualTo("1234,1235")); @@ -2415,12 +2451,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Delete_Previous_Versions_Not_Latest() { // Arrange - var content = ContentService.GetById(Trashed.Id); - var version = content.VersionId; + IContent content = ContentService.GetById(Trashed.Id); + int version = content.VersionId; // Act ContentService.DeleteVersion(Trashed.Id, version, true, Constants.Security.SuperUserId); - var sut = ContentService.GetById(Trashed.Id); + IContent sut = ContentService.GetById(Trashed.Id); // Assert Assert.That(sut.VersionId, Is.EqualTo(version)); @@ -2430,21 +2466,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Paged_Children() { // Start by cleaning the "db" - var umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); ContentService.Delete(umbTextPage, Constants.Security.SuperUserId); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType); + Content c1 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(c1); } - var entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out var total).ToArray(); + IContent[] entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = ContentService.GetPagedChildren(Constants.System.Root, 1, 6, out total).ToArray(); @@ -2456,31 +2492,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Paged_Children_Dont_Get_Descendants() { // Start by cleaning the "db" - var umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); ContentService.Delete(umbTextPage, Constants.Security.SuperUserId); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - // only add 9 as we also add a content with children - for (var i = 0; i < 9; i++) + + // Only add 9 as we also add a content with children + for (int i = 0; i < 9; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType); + Content c1 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(c1); } - var willHaveChildren = ContentBuilder.CreateSimpleContent(contentType); + Content willHaveChildren = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(willHaveChildren); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, "Content" + i, willHaveChildren.Id); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, "Content" + i, willHaveChildren.Id); ContentService.Save(c1); } // children in root including the folder - not the descendants in the folder - var entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out var total).ToArray(); + IContent[] entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = ContentService.GetPagedChildren(Constants.System.Root, 1, 6, out total).ToArray(); @@ -2516,7 +2553,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! ContentTypeService.Save(contentType); - var content = ContentService.Create("foo", Constants.System.Root, "foo"); + IContent content = ContentService.Create("foo", Constants.System.Root, "foo"); ContentService.Save(content); Assert.IsFalse(content.Published); @@ -2538,7 +2575,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(content.Published); Assert.IsTrue(content.Edited); - var versions = ContentService.GetVersions(content.Id); + IEnumerable versions = ContentService.GetVersions(content.Id); Assert.AreEqual(1, versions.Count()); // publish content @@ -2570,8 +2607,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("foo", content.GetValue("title", published: true)); Assert.AreEqual("foo", content.GetValue("title")); - var vpk = ((Content) content).VersionId; - var ppk = ((Content) content).PublishedVersionId; + int vpk = ((Content)content).VersionId; + int ppk = ((Content)content).PublishedVersionId; content = ContentService.GetById(content.Id); Assert.IsFalse(content.Published); @@ -2580,13 +2617,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // FIXME: depending on 1 line in ContentBaseFactory.BuildEntity // the published infos can be gone or not // if gone, it's not consistent with above - Assert.AreEqual(vpk, ((Content) content).VersionId); - Assert.AreEqual(ppk, ((Content) content).PublishedVersionId); // still there + Assert.AreEqual(vpk, ((Content)content).VersionId); + Assert.AreEqual(ppk, ((Content)content).PublishedVersionId); // still there // FIXME: depending on 1 line in ContentRepository.MapDtoToContent // the published values can be null or not // if null, it's not consistent with above - //Assert.IsNull(content.GetValue("title", published: true)); + // Assert.IsNull(content.GetValue("title", published: true)); Assert.AreEqual("foo", content.GetValue("title", published: true)); // still there Assert.AreEqual("foo", content.GetValue("title")); @@ -2597,7 +2634,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // and therefore we cannot "just" republish the content - we need to publish some values // so... that's not really an option // - //ContentService.SaveAndPublish(content); + // ContentService.SaveAndPublish(content); // FIXME: what shall we do of all this? /* @@ -2628,22 +2665,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Ensure_Invariant_Name() { - var languageService = LocalizationService; + ILocalizationService languageService = LocalizationService; - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); languageService.Save(langFr); languageService.Save(langUk); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Nvarchar, "prop") { Variations = ContentVariation.Culture }); ContentTypeService.Save(contentType); @@ -2654,35 +2691,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("name-fr", langFr.IsoCode); ContentService.Save(content); - //the name will be set to the default culture variant name + // the name will be set to the default culture variant name Assert.AreEqual("name-us", content.Name); // FIXME: should we always sync the invariant name even on update? see EnsureInvariantNameValues ////updating the default culture variant name should also update the invariant name so they stay in sync - //content.SetName("name-us-2", langUk.IsoCode); - //ContentService.Save(content); - //Assert.AreEqual("name-us-2", content.Name); + // content.SetName("name-us-2", langUk.IsoCode); + // ContentService.Save(content); + // Assert.AreEqual("name-us-2", content.Name); } [Test] public void Ensure_Unique_Culture_Names() { - var languageService = LocalizationService; + ILocalizationService languageService = LocalizationService; - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); languageService.Save(langFr); languageService.Save(langUk); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); @@ -2690,34 +2727,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("root", langUk.IsoCode); ContentService.Save(content); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { var child = new Content(null, content, contentType); child.SetCultureName("child", langUk.IsoCode); ContentService.Save(child); - Assert.AreEqual("child" + (i == 0 ? "" : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); + Assert.AreEqual("child" + (i == 0 ? string.Empty : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); - //Save it again to ensure that the unique check is not performed again against it's own name + // Save it again to ensure that the unique check is not performed again against it's own name ContentService.Save(child); - Assert.AreEqual("child" + (i == 0 ? "" : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); + Assert.AreEqual("child" + (i == 0 ? string.Empty : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); } } [Test] public void Can_Get_Paged_Children_WithFilterAndOrder() { - var languageService = LocalizationService; + ILocalizationService languageService = LocalizationService; - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .WithIsMandatory(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); - var langDa = new LanguageBuilder() + ILanguage langDa = new LanguageBuilder() .WithCultureInfo("da-DK") .Build(); @@ -2725,14 +2762,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services languageService.Save(langUk); languageService.Save(langDa); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var o = new[] { 2, 1, 3, 0, 4 }; // randomly different - for (var i = 0; i < 5; i++) + int[] o = new[] { 2, 1, 3, 0, 4 }; // randomly different + for (int i = 0; i < 5; i++) { var contentA = new Content(null, Constants.System.Root, contentType); contentA.SetCultureName("contentA" + i + "uk", langUk.IsoCode); @@ -2748,7 +2785,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } // get all - var list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out var total).ToList(); + var list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out long total).ToList(); Console.WriteLine("ALL"); WriteList(list); @@ -2757,10 +2794,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(11, total); Assert.AreEqual(11, list.Count); - var sqlContext = GetRequiredService(); + ISqlContext sqlContext = GetRequiredService(); // filter - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentX")), Ordering.By("name", culture: langFr.IsoCode)).ToList(); @@ -2768,7 +2809,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(0, list.Count); // filter - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentX")), Ordering.By("name", culture: langDa.IsoCode)).ToList(); @@ -2779,7 +2824,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(10, list.Count); // filter - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentA")), Ordering.By("name", culture: langFr.IsoCode)).ToList(); @@ -2789,10 +2838,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, total); Assert.AreEqual(5, list.Count); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) + { Assert.AreEqual("contentA" + i + "fr", list[i].GetCultureName(langFr.IsoCode)); + } - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentA")), Ordering.By("name", direction: Direction.Descending, culture: langFr.IsoCode)).ToList(); @@ -2802,32 +2857,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, total); Assert.AreEqual(5, list.Count); - for (var i = 0; i < 5; i++) - Assert.AreEqual("contentA" + (4-i) + "fr", list[i].GetCultureName(langFr.IsoCode)); + for (int i = 0; i < 5; i++) + { + Assert.AreEqual("contentA" + (4 - i) + "fr", list[i].GetCultureName(langFr.IsoCode)); + } } private void WriteList(List list) { - foreach (var content in list) + foreach (IContent content in list) + { Console.WriteLine("[{0}] {1} {2} {3} {4}", content.Id, content.Name, content.GetCultureName("en-GB"), content.GetCultureName("fr-FR"), content.GetCultureName("da-DK")); + } + Console.WriteLine("-"); } [Test] public void Can_SaveRead_Variations() { - var languageService = LocalizationService; - var langPt = new LanguageBuilder() + ILocalizationService languageService = LocalizationService; + ILanguage langPt = new LanguageBuilder() .WithCultureInfo("pt-PT") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); - var langDe = new LanguageBuilder() + ILanguage langDe = new LanguageBuilder() .WithCultureInfo("de-DE") .Build(); @@ -2835,25 +2895,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services languageService.Save(langUk); languageService.Save(langDe); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Nvarchar, "prop") { Variations = ContentVariation.Culture }); + // FIXME: add test w/ an invariant prop ContentTypeService.Save(contentType); - var content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage"); + IContent content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage"); // creating content with a name but no culture - will set the invariant name // but, because that content is variant, as soon as we save, we'll need to // replace the invariant name with whatever we have in cultures - always // // in fact, that would throw, because there is no name - //ContentService.Save(content); - - // act + // ContentService.Save(content); + // Act content.SetValue("author", "Barack Obama"); content.SetValue("prop", "value-fr1", langFr.IsoCode); content.SetValue("prop", "value-uk1", langUk.IsoCode); @@ -2863,8 +2923,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // content has been saved, // it has names, but no publishNames, and no published cultures - - var content2 = ContentService.GetById(content.Id); + IContent content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr", content2.Name); // got the default culture name when saved Assert.AreEqual("name-fr", content2.GetCultureName(langFr.IsoCode)); @@ -2891,14 +2950,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.IsCultureEdited(c), (langFr, true), (langUk, true), (langDe, false)); AssertPerCulture(content2, (x, c) => x.IsCultureEdited(c), (langFr, true), (langUk, true), (langDe, false)); - // act - - ContentService.SaveAndPublish(content, new[]{ langFr.IsoCode, langUk.IsoCode }); + // Act + ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); // both FR and UK have been published, // and content has been published, // it has names, publishNames, and published cultures - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr", content2.Name); // got the default culture name when saved @@ -2935,20 +2992,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // note that content and content2 culture published dates might be slightly different due to roundtrip to database - - // act - + // Act ContentService.SaveAndPublish(content); // now it has publish name for invariant neutral - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr", content2.PublishName); - - // act - content.SetCultureName("Home US2", null); content.SetCultureName("name-fr2", langFr.IsoCode); content.SetCultureName("name-uk2", langUk.IsoCode); @@ -2959,7 +3010,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // content has been saved, // it has updated names, unchanged publishNames, and published cultures - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr2", content2.Name); // got the default culture name when saved @@ -2993,16 +3043,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langFr, false), (langUk, false)); // DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langFr, false), (langUk, false)); // DE would throw - - // act + // Act // cannot just 'save' since we are changing what's published! - ContentService.Unpublish(content, langFr.IsoCode); // content has been published, // the french culture is gone // (only if french is not mandatory, else everything would be gone!) - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr2", content2.Name); // got the default culture name when saved @@ -3036,9 +3083,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act - + // Act ContentService.Unpublish(content); // content has been unpublished, @@ -3050,7 +3095,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // its exact previous state, properties and names etc. retain their published // values even though the content is not published - hence many things being // non-null or true below - always check against content.Published to be sure - content2 = ContentService.GetById(content.Id); Assert.IsFalse(content2.Published); @@ -3083,18 +3127,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act + // Act // that HAS to be SavePublishing, because SaveAndPublish would just republish everything! - //TODO: This is using an internal API - the test can't pass without this but we want to keep the test here + // TODO: This is using an internal API - the test can't pass without this but we want to keep the test here // will need stephane to have a look at this test at some stage since there is a lot of logic here that we // want to keep on testing but don't need the public API to do these more complicated things. ContentService.CommitDocumentChanges(content); // content has been re-published, // everything is back to what it was before being unpublished - content2 = ContentService.GetById(content.Id); Assert.IsTrue(content2.Published); @@ -3127,9 +3169,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act - + // Act ContentService.SaveAndPublish(content, langUk.IsoCode); content2 = ContentService.GetById(content.Id); @@ -3149,9 +3189,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act - + // Act content.SetCultureName("name-uk3", langUk.IsoCode); ContentService.Save(content); @@ -3161,30 +3199,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // but they change, on what's being saved, and when getting it back // changing the name = edited! - Assert.IsTrue(content.IsCultureEdited(langUk.IsoCode)); Assert.IsTrue(content2.IsCultureEdited(langUk.IsoCode)); } private void AssertPerCulture(IContent item, Func getter, params (ILanguage Language, bool Result)[] testCases) { - foreach (var testCase in testCases) + foreach ((ILanguage Language, bool Result) testCase in testCases) { - var value = getter(item, testCase.Language.IsoCode); + T value = getter(item, testCase.Language.IsoCode); Assert.AreEqual(testCase.Result, value, $"Expected {testCase.Result} and got {value} for culture {testCase.Language.IsoCode}."); } } private IEnumerable CreateContentHierarchy() { - var contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentService.GetById(Textpage.Id); + IContentType contentType = ContentTypeService.Get("umbTextpage"); + IContent root = ContentService.GetById(Textpage.Id); var list = new List(); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var content = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Page " + i, root); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Page " + i, root); list.Add(content); list.AddRange(CreateChildrenOf(contentType, content, 4)); @@ -3198,13 +3235,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private IEnumerable CreateChildrenOf(IContentType contentType, IContent content, int depth) { var list = new List(); - for (var i = 0; i < depth; i++) + for (int i = 0; i < depth; i++) { - var c = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Subpage " + i, content); + Content c = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Subpage " + i, content); list.Add(c); Debug.Print("Created: 'Hierarchy Simple Text Subpage {0}' - Depth: {1}", i, depth); } + return list; } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs index e5234205c4..469a806335 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs @@ -1,7 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; @@ -20,27 +22,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ContentTypeServiceTests : UmbracoIntegrationTest { private IFileService FileService => GetRequiredService(); + private ContentService ContentService => (ContentService)GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private ContentTypeService ContentTypeService => (ContentTypeService)GetRequiredService(); [Test] public void CanSaveAndGetIsElement() { - //create content type with a property type that varies by culture + // create content type with a property type that varies by culture IContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Nothing; - var contentCollection = new PropertyTypeCollection(true); - contentCollection.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext) + var contentCollection = new PropertyTypeCollection(true) { - Alias = "title", - Name = "Title", - Description = "", - Mandatory = false, - SortOrder = 1, - DataTypeId = -88, - Variations = ContentVariation.Nothing - }); + new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext) + { + Alias = "title", + Name = "Title", + Description = string.Empty, + Mandatory = false, + SortOrder = 1, + DataTypeId = -88, + Variations = ContentVariation.Nothing + } + }; contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); ContentTypeService.Save(contentType); @@ -57,7 +64,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleting_Content_Type_With_Hierarchy_Of_Content_Items_Moves_Orphaned_Content_To_Recycle_Bin() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -70,17 +77,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType3.DefaultTemplate); ContentTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IContentType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; var ids = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); + IContentType contentType = contentTypes[index]; + Content contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); ContentService.Save(contentItem); ContentService.SaveAndPublish(contentItem); parentId = contentItem.Id; @@ -89,13 +96,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - //delete the first content type, all other content of different content types should be in the recycle bin + // delete the first content type, all other content of different content types should be in the recycle bin ContentTypeService.Delete(contentTypes[0]); - var found = ContentService.GetByIds(ids); + IEnumerable found = ContentService.GetByIds(ids); Assert.AreEqual(4, found.Count()); - foreach (var content in found) + foreach (IContent content in found) { Assert.IsTrue(content.Trashed); } @@ -108,7 +115,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services try { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -121,22 +128,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType3.DefaultTemplate); ContentTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IContentType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); + IContentType contentType = contentTypes[index]; + Content contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); ContentService.Save(contentItem); ContentService.SaveAndPublish(contentItem); parentId = contentItem.Id; } } - foreach (var contentType in contentTypes.Reverse()) + foreach (IContentType contentType in contentTypes.Reverse()) { ContentTypeService.Delete(contentType); } @@ -154,7 +161,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services try { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -167,17 +174,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType3.DefaultTemplate); ContentTypeService.Save(contentType3); - var root = ContentBuilder.CreateSimpleContent(contentType1, "Root", -1); + Content root = ContentBuilder.CreateSimpleContent(contentType1, "Root", -1); ContentService.Save(root); ContentService.SaveAndPublish(root); - var level1 = ContentBuilder.CreateSimpleContent(contentType2, "L1", root.Id); + Content level1 = ContentBuilder.CreateSimpleContent(contentType2, "L1", root.Id); ContentService.Save(level1); ContentService.SaveAndPublish(level1); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - var level3 = ContentBuilder.CreateSimpleContent(contentType3, "L2" + i, level1.Id); + Content level3 = ContentBuilder.CreateSimpleContent(contentType3, "L2" + i, level1.Id); ContentService.Save(level3); ContentService.SaveAndPublish(level3); } @@ -192,19 +199,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void ContentServiceOnTrashed(IContentService sender, MoveEventArgs e) { - foreach (var item in e.MoveInfoCollection) + foreach (MoveEventInfo item in e.MoveInfoCollection) { - //if this item doesn't exist then Fail! - var exists = ContentService.GetById(item.Entity.Id); + // if this item doesn't exist then Fail! + IContent exists = ContentService.GetById(item.Entity.Id); if (exists == null) + { Assert.Fail("The item doesn't exist"); + } } } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateTextPageContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -212,13 +221,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentType1); IContent contentItem = ContentBuilder.CreateTextpageContent(contentType1, "Testing", -1); ContentService.SaveAndPublish(contentItem); - var initProps = contentItem.Properties.Count; + int initProps = contentItem.Properties.Count; - //remove a property + // remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ContentTypeService.Save(contentType1); - //re-load it from the db + // re-load it from the db contentItem = ContentService.GetById(contentItem.Id); Assert.AreEqual(initProps - 1, contentItem.Properties.Count); @@ -228,15 +237,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_Descendants() { // Arrange - var contentTypeService = ContentTypeService; - var hierarchy = CreateContentTypeHierarchy(); - contentTypeService.Save(hierarchy, 0); //ensure they are saved! - var master = hierarchy.First(); + ContentTypeService contentTypeService = ContentTypeService; + IContentType[] hierarchy = CreateContentTypeHierarchy(); + contentTypeService.Save(hierarchy, 0); // ensure they are saved! + IContentType master = hierarchy.First(); - //Act - var descendants = contentTypeService.GetDescendants(master.Id, false); + // Act + IEnumerable descendants = contentTypeService.GetDescendants(master.Id, false); - //Assert + // Assert Assert.AreEqual(10, descendants.Count()); } @@ -244,15 +253,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_Descendants_And_Self() { // Arrange - var contentTypeService = ContentTypeService; - var hierarchy = CreateContentTypeHierarchy(); - contentTypeService.Save(hierarchy, 0); //ensure they are saved! - var master = hierarchy.First(); + ContentTypeService contentTypeService = ContentTypeService; + IContentType[] hierarchy = CreateContentTypeHierarchy(); + contentTypeService.Save(hierarchy, 0); // ensure they are saved! + IContentType master = hierarchy.First(); - //Act - var descendants = contentTypeService.GetDescendants(master.Id, true); + // Act + IEnumerable descendants = contentTypeService.GetDescendants(master.Id, true); - //Assert + // Assert Assert.AreEqual(11, descendants.Count()); } @@ -260,19 +269,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Bulk_Save_New_Hierarchy_Content_Types() { // Arrange - var contentTypeService = ContentTypeService; - var hierarchy = CreateContentTypeHierarchy(); + ContentTypeService contentTypeService = ContentTypeService; + IContentType[] hierarchy = CreateContentTypeHierarchy(); // Act contentTypeService.Save(hierarchy, 0); Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); - //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown + + // all parent ids should be ok, they are lazy and if they equal zero an exception will be thrown Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); - for (var i = 0; i < hierarchy.Count(); i++) + for (int i = 0; i < hierarchy.Count(); i++) { - if (i == 0) continue; + if (i == 0) + { + continue; + } + Assert.AreEqual(hierarchy.ElementAt(i).ParentId, hierarchy.ElementAt(i - 1).Id); } } @@ -281,16 +295,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_ContentType_Structure_And_Create_Content_Based_On_It() { // Arrange - var cs = ContentService; - var cts = ContentTypeService; - var dtdYesNo = DataTypeService.GetDataType(-49); + ContentService cs = ContentService; + ContentTypeService cts = ContentTypeService; + IDataType dtdYesNo = DataTypeService.GetDataType(-49); var ctBase = new ContentType(ShortStringHelper, -1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" }; ctBase.AddPropertyType(new PropertyType(ShortStringHelper, dtdYesNo, Constants.Conventions.Content.NaviHide) { Name = "Hide From Navigation", - } - /*,"Navigation"*/); - cts.Save(ctBase); + }); + /*,"Navigation"*/ cts.Save(ctBase); const string contentTypeAlias = "HomePage"; var ctHomePage = new ContentType(ShortStringHelper, ctBase, contentTypeAlias) @@ -301,12 +314,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Thumbnail = "folder.png", AllowedAsRoot = true }; - ctHomePage.AddPropertyType(new PropertyType(ShortStringHelper, dtdYesNo, "someProperty") { Name = "Some property" } - /*,"Navigation"*/); - cts.Save(ctHomePage); + ctHomePage.AddPropertyType(new PropertyType(ShortStringHelper, dtdYesNo, "someProperty") { Name = "Some property" }); + /*,"Navigation"*/ cts.Save(ctHomePage); // Act - var homeDoc = cs.Create("Home Page", -1, contentTypeAlias); + IContent homeDoc = cs.Create("Home Page", -1, contentTypeAlias); cs.SaveAndPublish(homeDoc); // Assert @@ -331,13 +343,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Trashed = false }; - contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, DataTypeId = -88 }); - contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TinyMce, ValueStorageType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, DataTypeId = -87 }); + contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { Name = "Title", Description = string.Empty, Mandatory = false, DataTypeId = -88 }); + contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TinyMce, ValueStorageType.Ntext, "bodyText") { Name = "Body Text", Description = string.Empty, Mandatory = false, DataTypeId = -87 }); contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { Name = "Author", Description = "Name of the author", Mandatory = false, DataTypeId = -88 }); ContentTypeService.Save(contentType); - var sortOrders = contentType.PropertyTypes.Select(x => x.SortOrder).ToArray(); + int[] sortOrders = contentType.PropertyTypes.Select(x => x.SortOrder).ToArray(); Assert.AreEqual(1, sortOrders.Count(x => x == 0)); Assert.AreEqual(1, sortOrders.Count(x => x == 1)); @@ -352,22 +364,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services * - Components * - Category */ - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var global = ContentTypeBuilder.CreateSimpleContentType("global", "Global", defaultTemplateId: template.Id); + ContentType global = ContentTypeBuilder.CreateSimpleContentType("global", "Global", defaultTemplateId: template.Id); ContentTypeService.Save(global); - var components = ContentTypeBuilder.CreateSimpleContentType("components", "Components", global, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType components = ContentTypeBuilder.CreateSimpleContentType("components", "Components", global, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(components); - var component = ContentTypeBuilder.CreateSimpleContentType("component", "Component", components, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType component = ContentTypeBuilder.CreateSimpleContentType("component", "Component", components, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(component); - var category = ContentTypeBuilder.CreateSimpleContentType("category", "Category", global, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType category = ContentTypeBuilder.CreateSimpleContentType("category", "Category", global, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(category); - var success = category.AddContentType(component); + bool success = category.AddContentType(component); Assert.That(success, Is.False); } @@ -375,15 +387,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Delete_Parent_ContentType_When_Child_Has_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var childContentType = ContentTypeBuilder.CreateSimpleContentType("childPage", "Child Page", contentType, randomizeAliases: true, propertyGroupName: "Child Content", defaultTemplateId: template.Id); + ContentType childContentType = ContentTypeBuilder.CreateSimpleContentType("childPage", "Child Page", contentType, randomizeAliases: true, propertyGroupName: "Child Content", defaultTemplateId: template.Id); ContentTypeService.Save(childContentType); - var content = ContentService.Create("Page 1", -1, childContentType.Alias); + IContent content = ContentService.Create("Page 1", -1, childContentType.Alias); ContentService.Save(content); ContentTypeService.Delete(contentType); @@ -394,9 +406,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreNotEqual(0, childContentType.Id); Assert.IsNotNull(contentType.Id); Assert.AreNotEqual(0, contentType.Id); - var deletedContent = ContentService.GetById(content.Id); - var deletedChildContentType = ContentTypeService.Get(childContentType.Id); - var deletedContentType = ContentTypeService.Get(contentType.Id); + IContent deletedContent = ContentService.GetById(content.Id); + IContentType deletedChildContentType = ContentTypeService.Get(childContentType.Id); + IContentType deletedContentType = ContentTypeService.Get(contentType.Id); Assert.IsNull(deletedChildContentType); Assert.IsNull(deletedContent); @@ -407,15 +419,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Create_Container() { // Arrange - var cts = ContentTypeService; + ContentTypeService cts = ContentTypeService; // Act - var container = new EntityContainer(Constants.ObjectTypes.DocumentType); - container.Name = "container1"; + var container = new EntityContainer(Constants.ObjectTypes.DocumentType) + { + Name = "container1" + }; cts.SaveContainer(container); // Assert - var createdContainer = cts.GetContainer(container.Id); + EntityContainer createdContainer = cts.GetContainer(container.Id); Assert.IsNotNull(createdContainer); } @@ -423,37 +437,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_All_Containers() { // Arrange - var cts = ContentTypeService; + ContentTypeService cts = ContentTypeService; // Act - var container1 = new EntityContainer(Constants.ObjectTypes.DocumentType); - container1.Name = "container1"; + var container1 = new EntityContainer(Constants.ObjectTypes.DocumentType) + { + Name = "container1" + }; cts.SaveContainer(container1); - var container2 = new EntityContainer(Constants.ObjectTypes.DocumentType); - container2.Name = "container2"; + var container2 = new EntityContainer(Constants.ObjectTypes.DocumentType) + { + Name = "container2" + }; cts.SaveContainer(container2); // Assert - var containers = cts.GetContainers(new int[0]); + IEnumerable containers = cts.GetContainers(new int[0]); Assert.AreEqual(2, containers.Count()); } [Test] public void Deleting_ContentType_Sends_Correct_Number_Of_DeletedEntities_In_Events() { - var deletedEntities = 0; + int deletedEntities = 0; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - ContentTypeService.Deleted += (sender, args) => - { - deletedEntities += args.DeletedEntities.Count(); - }; + ContentTypeService.Deleted += (sender, args) => deletedEntities += args.DeletedEntities.Count(); ContentTypeService.Delete(contentType); @@ -463,20 +478,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleting_Multiple_ContentTypes_Sends_Correct_Number_Of_DeletedEntities_In_Events() { - var deletedEntities = 0; + int deletedEntities = 0; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateSimpleContentType("otherPage", "Other page", defaultTemplateId: template.Id); + ContentType contentType2 = ContentTypeBuilder.CreateSimpleContentType("otherPage", "Other page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType2); - ContentTypeService.Deleted += (sender, args) => - { - deletedEntities += args.DeletedEntities.Count(); - }; + ContentTypeService.Deleted += (sender, args) => deletedEntities += args.DeletedEntities.Count(); ContentTypeService.Delete(contentType); ContentTypeService.Delete(contentType2); @@ -487,21 +499,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleting_ContentType_With_Child_Sends_Correct_Number_Of_DeletedEntities_In_Events() { - var deletedEntities = 0; + int deletedEntities = 0; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateSimpleContentType("subPage", "Sub page", defaultTemplateId: template.Id); + ContentType contentType2 = ContentTypeBuilder.CreateSimpleContentType("subPage", "Sub page", defaultTemplateId: template.Id); contentType2.ParentId = contentType.Id; ContentTypeService.Save(contentType2); - ContentTypeService.Deleted += (sender, args) => - { - deletedEntities += args.DeletedEntities.Count(); - }; + ContentTypeService.Deleted += (sender, args) => deletedEntities += args.DeletedEntities.Count(); ContentTypeService.Delete(contentType); @@ -511,37 +520,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Remove_ContentType_Composition_From_ContentType() { - //Test for U4-2234 - var cts = ContentTypeService; - //Arrange - var component = CreateComponent(); + // Test for U4-2234 + ContentTypeService cts = ContentTypeService; + + // Arrange + ContentType component = CreateComponent(); cts.Save(component); - var banner = CreateBannerComponent(component); + ContentType banner = CreateBannerComponent(component); cts.Save(banner); - var site = CreateSite(); + ContentType site = CreateSite(); cts.Save(site); - var homepage = CreateHomepage(site); + ContentType homepage = CreateHomepage(site); cts.Save(homepage); - //Add banner to homepage - var added = homepage.AddContentType(banner); + // Add banner to homepage + bool added = homepage.AddContentType(banner); cts.Save(homepage); - //Assert composition - var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); - var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); + // Assert composition + bool bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); + bool bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(added, Is.True); Assert.That(bannerExists, Is.True); Assert.That(bannerPropertyExists, Is.True); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); - //Remove banner from homepage - var removed = homepage.RemoveContentType(banner.Alias); + // Remove banner from homepage + bool removed = homepage.RemoveContentType(banner.Alias); cts.Save(homepage); - //Assert composition - var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); - var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); + // Assert composition + bool bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); + bool bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(removed, Is.True); Assert.That(bannerStillExists, Is.False); Assert.That(bannerPropertyStillExists, Is.False); @@ -552,25 +562,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_By_Performing_Clone() { // Arrange - var metaContentType = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaContentType = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaContentType); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType, defaultTemplateId: template.Id) as IContentType; ContentTypeService.Save(simpleContentType); - var categoryId = simpleContentType.Id; + int categoryId = simpleContentType.Id; // Act - var sut = simpleContentType.DeepCloneWithResetIdentities("newcategory"); + IContentType sut = simpleContentType.DeepCloneWithResetIdentities("newcategory"); Assert.IsNotNull(sut); ContentTypeService.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); - var contentType = ContentTypeService.Get(sut.Id); - var category = ContentTypeService.Get(categoryId); + IContentType contentType = ContentTypeService.Get(sut.Id); + IContentType category = ContentTypeService.Get(categoryId); Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); Assert.AreEqual(contentType.ParentId, category.ParentId); @@ -588,19 +598,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_To_New_Parent_By_Performing_Clone() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); + ContentType parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType1); - var parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType2); var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", parentContentType1, randomizeAliases: true, defaultTemplateId: template.Id) as IContentType; ContentTypeService.Save(simpleContentType); // Act - var clone = simpleContentType.DeepCloneWithResetIdentities("newcategory"); + IContentType clone = simpleContentType.DeepCloneWithResetIdentities("newcategory"); Assert.IsNotNull(clone); clone.RemoveContentType("parent1"); clone.AddContentType(parentContentType2); @@ -610,8 +620,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.That(clone.HasIdentity, Is.True); - var clonedContentType = ContentTypeService.Get(clone.Id); - var originalContentType = ContentTypeService.Get(simpleContentType.Id); + IContentType clonedContentType = ContentTypeService.Get(clone.Id); + IContentType originalContentType = ContentTypeService.Get(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); @@ -634,26 +644,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_With_Service_To_Root() { // Arrange - var metaContentType = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaContentType = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaContentType); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType, defaultTemplateId: template.Id); + ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType, defaultTemplateId: template.Id); ContentTypeService.Save(simpleContentType); - var categoryId = simpleContentType.Id; + int categoryId = simpleContentType.Id; // Act - var clone = ContentTypeService.Copy(simpleContentType, "newcategory", "new category"); + IContentType clone = ContentTypeService.Copy(simpleContentType, "newcategory", "new category"); // Assert Assert.That(clone.HasIdentity, Is.True); - var cloned = ContentTypeService.Get(clone.Id); - var original = ContentTypeService.Get(categoryId); + IContentType cloned = ContentTypeService.Get(clone.Id); + IContentType original = ContentTypeService.Get(categoryId); - Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); //it's been copied to root + Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); // it's been copied to root Assert.AreEqual(cloned.ParentId, -1); Assert.AreEqual(cloned.Level, 1); Assert.AreEqual(cloned.PropertyTypes.Count(), original.PropertyTypes.Count()); @@ -662,13 +672,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int i = 0; i < cloned.PropertyGroups.Count; i++) { Assert.AreEqual(cloned.PropertyGroups[i].PropertyTypes.Count, original.PropertyGroups[i].PropertyTypes.Count); - foreach (var propertyType in cloned.PropertyGroups[i].PropertyTypes) + foreach (IPropertyType propertyType in cloned.PropertyGroups[i].PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } } - foreach (var propertyType in cloned.PropertyTypes) + foreach (IPropertyType propertyType in cloned.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } @@ -685,25 +695,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_To_New_Parent_With_Service() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); + ContentType parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType1); - var parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType2); - var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", parentContentType1, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", parentContentType1, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(simpleContentType); // Act - var clone = ContentTypeService.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); + IContentType clone = ContentTypeService.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); // Assert Assert.That(clone.HasIdentity, Is.True); - var clonedContentType = ContentTypeService.Get(clone.Id); - var originalContentType = ContentTypeService.Get(simpleContentType.Id); + IContentType clonedContentType = ContentTypeService.Get(clone.Id); + IContentType originalContentType = ContentTypeService.Get(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); @@ -725,29 +735,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_To_Referenced_Composition() { - //Related the second issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 + // Related the second issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var parent = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType parent = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(parent); - var child = ContentTypeBuilder.CreateSimpleContentType("simpleChildPage", "Simple Child Page", parent, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType child = ContentTypeBuilder.CreateSimpleContentType("simpleChildPage", "Simple Child Page", parent, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(child); - var composition = ContentTypeBuilder.CreateMetaContentType(); + ContentType composition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(composition); - //Adding Meta-composition to child doc type + // Adding Meta-composition to child doc type child.AddContentType(composition); ContentTypeService.Save(child); // Act var duplicatePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var added = composition.AddPropertyType(duplicatePropertyType, "Meta"); + bool added = composition.AddPropertyType(duplicatePropertyType, "Meta"); // Assert Assert.That(added, Is.True); @@ -759,35 +769,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Add_Duplicate_PropertyType_Alias_In_Composition_Graph() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); - var seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); + ContentType seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); ContentTypeService.Save(seoComposition); - var metaAdded = contentPage.AddContentType(metaComposition); + bool metaAdded = contentPage.AddContentType(metaComposition); ContentTypeService.Save(contentPage); - var seoAdded = advancedPage.AddContentType(seoComposition); + bool seoAdded = advancedPage.AddContentType(seoComposition); ContentTypeService.Save(advancedPage); // Act var duplicatePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var addedToBasePage = basePage.AddPropertyType(duplicatePropertyType, "Content"); - var addedToAdvancedPage = advancedPage.AddPropertyType(duplicatePropertyType, "Content"); - var addedToMeta = metaComposition.AddPropertyType(duplicatePropertyType, "Meta"); - var addedToSeo = seoComposition.AddPropertyType(duplicatePropertyType, "Seo"); + bool addedToBasePage = basePage.AddPropertyType(duplicatePropertyType, "Content"); + bool addedToAdvancedPage = advancedPage.AddPropertyType(duplicatePropertyType, "Content"); + bool addedToMeta = metaComposition.AddPropertyType(duplicatePropertyType, "Meta"); + bool addedToSeo = seoComposition.AddPropertyType(duplicatePropertyType, "Seo"); // Assert Assert.That(metaAdded, Is.True); @@ -822,40 +832,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); - var compositionAdded = advancedPage.AddContentType(contentMetaComposition); + bool compositionAdded = advancedPage.AddContentType(contentMetaComposition); ContentTypeService.Save(advancedPage); - //NOTE: It should not be possible to Save 'BasePage' with the Title PropertyType added + // NOTE: It should not be possible to Save 'BasePage' with the Title PropertyType added var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); // Assert Assert.That(bodyTextAdded, Is.True); @@ -873,7 +883,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_ContentType_With_Empty_Name() { // Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("contentType", string.Empty); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("contentType", string.Empty); // Act & Assert Assert.Throws(() => ContentTypeService.Save(contentType)); @@ -892,55 +902,55 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); + ContentType moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); ContentTypeService.Save(moreAdvancedPage); - var seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); + ContentType seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); ContentTypeService.Save(seoComposition); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); + bool subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); ContentTypeService.Save(advancedPage); var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); ContentTypeService.Save(seoComposition); - var seoCompositionAdded = advancedPage.AddContentType(seoComposition); - var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); + bool seoCompositionAdded = advancedPage.AddContentType(seoComposition); + bool metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); ContentTypeService.Save(advancedPage); ContentTypeService.Save(moreAdvancedPage); - var keywordsPropertyType = metaComposition.PropertyTypes.First(x => x.Alias.Equals("metakeywords")); + IPropertyType keywordsPropertyType = metaComposition.PropertyTypes.First(x => x.Alias.Equals("metakeywords")); keywordsPropertyType.Alias = "title"; // Assert @@ -971,51 +981,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); + ContentType moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); ContentTypeService.Save(moreAdvancedPage); - var seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); + ContentType seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); ContentTypeService.Save(seoComposition); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); + bool subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); ContentTypeService.Save(advancedPage); var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); ContentTypeService.Save(seoComposition); - var seoCompositionAdded = advancedPage.AddContentType(seoComposition); - var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); + bool seoCompositionAdded = advancedPage.AddContentType(seoComposition); + bool metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); ContentTypeService.Save(advancedPage); ContentTypeService.Save(moreAdvancedPage); @@ -1029,9 +1039,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var testPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "test") { - Name = "Test", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Test", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var testAdded = seoComposition.AddPropertyType(testPropertyType, "Content"); + bool testAdded = seoComposition.AddPropertyType(testPropertyType, "Content"); ContentTypeService.Save(seoComposition); Assert.That(testAdded, Is.True); @@ -1045,37 +1055,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Rename_PropertyGroup_On_Child_Avoiding_Conflict_With_Parent_PropertyGroup() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(page); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Details", defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Details", defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); - //Change the name of the tab on the "root" content type 'page'. - var propertyGroup = contentPage.PropertyGroups["Content_"]; + // Change the name of the tab on the "root" content type 'page'. + PropertyGroup propertyGroup = contentPage.PropertyGroups["Content_"]; Assert.Throws(() => contentPage.PropertyGroups.Add(new PropertyGroup(true) { Id = propertyGroup.Id, @@ -1096,40 +1106,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Rename_PropertyType_Alias_Causing_Conflicts_With_Parents() { // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); // Act var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content"); var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(basePage); ContentTypeService.Save(contentPage); ContentTypeService.Save(advancedPage); - //Rename the PropertyType to something that already exists in the Composition - NOTE this should not be allowed and Saving should throw an exception - var authorPropertyTypeToRename = advancedPage.PropertyTypes.First(x => x.Alias.Equals("author")); + // Rename the PropertyType to something that already exists in the Composition - NOTE this should not be allowed and Saving should throw an exception + IPropertyType authorPropertyTypeToRename = advancedPage.PropertyTypes.First(x => x.Alias.Equals("author")); authorPropertyTypeToRename.Alias = "title"; // Assert @@ -1155,33 +1165,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services * ---- Advanced Page */ // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); - var metaAdded = contentPage.AddContentType(metaComposition); + bool metaAdded = contentPage.AddContentType(metaComposition); ContentTypeService.Save(contentPage); - var metaAddedToComposition = contentMetaComposition.AddContentType(metaComposition); + bool metaAddedToComposition = contentMetaComposition.AddContentType(metaComposition); ContentTypeService.Save(contentMetaComposition); // Act var propertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var addedToContentPage = contentPage.AddPropertyType(propertyType, "Content"); + bool addedToContentPage = contentPage.AddPropertyType(propertyType, "Content"); // Assert Assert.That(metaAdded, Is.True); @@ -1194,13 +1204,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Rename_PropertyGroup_With_Inherited_PropertyGroups() { - //Related the first issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 + // Related the first issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange // create 'page' content type with a 'Content_' group - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", propertyGroupName: "Content_", defaultTemplateId: template.Id); Assert.AreEqual(1, page.PropertyGroups.Count); Assert.AreEqual("Content_", page.PropertyGroups.First().Name); Assert.AreEqual(3, page.PropertyTypes.Count()); @@ -1210,7 +1220,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(page); // create 'contentPage' content type as a child of 'page' - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, defaultTemplateId: template.Id); Assert.AreEqual(1, page.PropertyGroups.Count); Assert.AreEqual("Content_", page.PropertyGroups.First().Name); Assert.AreEqual(3, contentPage.PropertyTypes.Count()); @@ -1220,7 +1230,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentPage); // add 'Content' group to 'meta' content type - var meta = ContentTypeBuilder.CreateMetaContentType(); + ContentType meta = ContentTypeBuilder.CreateMetaContentType(); Assert.AreEqual(1, meta.PropertyGroups.Count); Assert.AreEqual("Meta", meta.PropertyGroups.First().Name); Assert.AreEqual(2, meta.PropertyTypes.Count()); @@ -1237,41 +1247,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // add property 'prop1' to 'contentPage' group 'Content_' var prop1 = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "testTextbox") { - Name = "Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Test Textbox", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var prop1Added = contentPage.AddPropertyType(prop1, "Content_"); + bool prop1Added = contentPage.AddPropertyType(prop1, "Content_"); Assert.IsTrue(prop1Added); // add property 'prop2' to 'contentPage' group 'Content' var prop2 = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "anotherTextbox") { - Name = "Another Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Another Test Textbox", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var prop2Added = contentPage.AddPropertyType(prop2, "Content"); + bool prop2Added = contentPage.AddPropertyType(prop2, "Content"); Assert.IsTrue(prop2Added); // save 'contentPage' content type ContentTypeService.Save(contentPage); - var group = page.PropertyGroups["Content_"]; + PropertyGroup group = page.PropertyGroups["Content_"]; group.Name = "ContentTab"; // rename the group ContentTypeService.Save(page); Assert.AreEqual(3, page.PropertyTypes.Count()); // get 'contentPage' content type again - var contentPageAgain = ContentTypeService.Get("contentPage"); + IContentType contentPageAgain = ContentTypeService.Get("contentPage"); Assert.IsNotNull(contentPageAgain); // assert that 'Content_' group is still there because we don't propagate renames - var findGroup = contentPageAgain.CompositionPropertyGroups.FirstOrDefault(x => x.Name == "Content_"); + PropertyGroup findGroup = contentPageAgain.CompositionPropertyGroups.FirstOrDefault(x => x.Name == "Content_"); Assert.IsNotNull(findGroup); // count all property types (local and composed) - var propertyTypeCount = contentPageAgain.PropertyTypes.Count(); + int propertyTypeCount = contentPageAgain.PropertyTypes.Count(); Assert.That(propertyTypeCount, Is.EqualTo(5)); // count composed property types - var compPropertyTypeCount = contentPageAgain.CompositionPropertyTypes.Count(); + int compPropertyTypeCount = contentPageAgain.CompositionPropertyTypes.Count(); Assert.That(compPropertyTypeCount, Is.EqualTo(10)); } @@ -1279,52 +1289,52 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); ContentTypeService.Save(page); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Contentx", defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Contentx", defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Contenty", defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Contenty", defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content_");//Will be added to the parent tab - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content");//Will be added to the "Content Meta" composition + bool bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content_"); // Will be added to the parent tab + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); // Will be added to the "Content Meta" composition ContentTypeService.Save(contentPage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var descriptionPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "description") { - Name = "Description", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Description", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var keywordsPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "keywords") { - Name = "Keywords", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Keywords", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content_");//Will be added to an ancestor tab - var descriptionAdded = advancedPage.AddPropertyType(descriptionPropertyType, "Contentx");//Will be added to a parent tab - var keywordsAdded = advancedPage.AddPropertyType(keywordsPropertyType, "Content");//Will be added to the "Content Meta" composition + bool authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content_"); // Will be added to an ancestor tab + bool descriptionAdded = advancedPage.AddPropertyType(descriptionPropertyType, "Contentx"); // Will be added to a parent tab + bool keywordsAdded = advancedPage.AddPropertyType(keywordsPropertyType, "Content"); // Will be added to the "Content Meta" composition ContentTypeService.Save(advancedPage); - //Change the name of the tab on the "root" content type 'page'. - var propertyGroup = page.PropertyGroups["Content_"]; + // Change the name of the tab on the "root" content type 'page'. + PropertyGroup propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup(true) { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); ContentTypeService.Save(page); @@ -1339,13 +1349,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.DoesNotThrow(() => ContentTypeService.Get("contentPage")); Assert.DoesNotThrow(() => ContentTypeService.Get("advancedPage")); - var advancedPageReloaded = ContentTypeService.Get("advancedPage"); - var contentUnderscoreTabExists = advancedPageReloaded.CompositionPropertyGroups.Any(x => x.Name.Equals("Content_")); + IContentType advancedPageReloaded = ContentTypeService.Get("advancedPage"); + bool contentUnderscoreTabExists = advancedPageReloaded.CompositionPropertyGroups.Any(x => x.Name.Equals("Content_")); // now is true, because we don't propagate renames anymore Assert.That(contentUnderscoreTabExists, Is.True); - var numberOfContentTabs = advancedPageReloaded.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); + int numberOfContentTabs = advancedPageReloaded.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(4)); } @@ -1353,40 +1363,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups_v2() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); ContentTypeService.Save(page); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content", defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content", defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = page.AddPropertyType(bodyTextPropertyType, "Content_"); - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content_"); + bool bodyTextAdded = page.AddPropertyType(bodyTextPropertyType, "Content_"); + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content_"); ContentTypeService.Save(page); ContentTypeService.Save(contentPage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); - //Change the name of the tab on the "root" content type 'page'. - var propertyGroup = page.PropertyGroups["Content_"]; + // Change the name of the tab on the "root" content type 'page'. + PropertyGroup propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup(true) { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); ContentTypeService.Save(page); @@ -1403,34 +1413,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Remove_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); basePage.RemovePropertyGroup("Content"); @@ -1444,14 +1454,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.DoesNotThrow(() => ContentTypeService.Get("contentPage")); Assert.DoesNotThrow(() => ContentTypeService.Get("advancedPage")); - var contentType = ContentTypeService.Get("contentPage"); - var propertyGroup = contentType.PropertyGroups["Content"]; + IContentType contentType = ContentTypeService.Get("contentPage"); + PropertyGroup propertyGroup = contentType.PropertyGroups["Content"]; } [Test] public void Can_Remove_PropertyGroup_Without_Removing_Property_Types() { - var basePage = (IContentType) ContentTypeBuilder.CreateBasicContentType(); + var basePage = (IContentType)ContentTypeBuilder.CreateBasicContentType(); basePage.AddPropertyGroup("Content"); basePage.AddPropertyGroup("Meta"); ContentTypeService.Save(basePage); @@ -1459,7 +1469,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { Name = "Author", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 @@ -1469,7 +1479,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { Name = "Title", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 @@ -1479,7 +1489,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(basePage); basePage = ContentTypeService.Get(basePage.Id); - var count = basePage.PropertyTypes.Count(); + int count = basePage.PropertyTypes.Count(); Assert.AreEqual(2, count); basePage.RemovePropertyGroup("Content"); @@ -1501,34 +1511,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); // Assert @@ -1539,39 +1549,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.DoesNotThrow(() => ContentTypeService.Get("contentPage")); Assert.DoesNotThrow(() => ContentTypeService.Get("advancedPage")); - var contentType = ContentTypeService.Get("contentPage"); - var propertyGroup = contentType.PropertyGroups["Content"]; + IContentType contentType = ContentTypeService.Get("contentPage"); + PropertyGroup propertyGroup = contentType.PropertyGroups["Content"]; - var numberOfContentTabs = contentType.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); + int numberOfContentTabs = contentType.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(3)); - //Ensure that adding a new PropertyType to the "Content"-tab also adds it to the right group - + // Ensure that adding a new PropertyType to the "Content"-tab also adds it to the right group var descriptionPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { - Alias = "description", Name = "Description", Description = "", Mandatory = false, SortOrder = 1,DataTypeId = -88 + Alias = "description", Name = "Description", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var descriptionAdded = contentType.AddPropertyType(descriptionPropertyType, "Content"); + bool descriptionAdded = contentType.AddPropertyType(descriptionPropertyType, "Content"); ContentTypeService.Save(contentType); Assert.That(descriptionAdded, Is.True); - var contentPageReloaded = ContentTypeService.Get("contentPage"); - var propertyGroupReloaded = contentPageReloaded.PropertyGroups["Content"]; - var hasDescriptionPropertyType = propertyGroupReloaded.PropertyTypes.Contains("description"); + IContentType contentPageReloaded = ContentTypeService.Get("contentPage"); + PropertyGroup propertyGroupReloaded = contentPageReloaded.PropertyGroups["Content"]; + bool hasDescriptionPropertyType = propertyGroupReloaded.PropertyTypes.Contains("description"); Assert.That(hasDescriptionPropertyType, Is.True); - var descriptionPropertyTypeReloaded = propertyGroupReloaded.PropertyTypes["description"]; + IPropertyType descriptionPropertyTypeReloaded = propertyGroupReloaded.PropertyTypes["description"]; Assert.That(descriptionPropertyTypeReloaded.PropertyGroupId.IsValueCreated, Is.False); } [Test] public void Empty_Description_Is_Always_Null_After_Saving_Content_Type() { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Description = null; ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateBasicContentType("basePage2", "Base Page 2"); + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("basePage2", "Base Page 2"); contentType2.Description = string.Empty; ContentTypeService.Save(contentType2); @@ -1582,23 +1591,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Variations_In_Compositions() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var typeA = ContentTypeBuilder.CreateSimpleContentType("a", "A", defaultTemplateId: template.Id); + ContentType typeA = ContentTypeBuilder.CreateSimpleContentType("a", "A", defaultTemplateId: template.Id); typeA.Variations = ContentVariation.Culture; // make it variant typeA.PropertyTypes.First(x => x.Alias.InvariantEquals("title")).Variations = ContentVariation.Culture; // with a variant property ContentTypeService.Save(typeA); - var typeB = ContentTypeBuilder.CreateSimpleContentType("b", "B", typeA, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType typeB = ContentTypeBuilder.CreateSimpleContentType("b", "B", typeA, randomizeAliases: true, defaultTemplateId: template.Id); typeB.Variations = ContentVariation.Nothing; // make it invariant ContentTypeService.Save(typeB); - var typeC = ContentTypeBuilder.CreateSimpleContentType("c", "C", typeA, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType typeC = ContentTypeBuilder.CreateSimpleContentType("c", "C", typeA, randomizeAliases: true, defaultTemplateId: template.Id); typeC.Variations = ContentVariation.Culture; // make it variant ContentTypeService.Save(typeC); // property is variant on A - var test = ContentTypeService.Get(typeA.Id); + IContentType test = ContentTypeService.Get(typeA.Id); Assert.AreEqual(ContentVariation.Culture, test.CompositionPropertyTypes.First(x => x.Alias.InvariantEquals("title")).Variations); Assert.AreEqual(ContentVariation.Culture, test.CompositionPropertyGroups.First().PropertyTypes.First(x => x.Alias.InvariantEquals("title")).Variations); @@ -1627,8 +1636,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Trashed = false }; - var contentCollection = new PropertyTypeCollection(true); - contentCollection.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "componentGroup") { Name = "Component Group", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + var contentCollection = new PropertyTypeCollection(true) + { + new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "componentGroup") { Name = "Component Group", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 } + }; component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); return component; @@ -1652,7 +1663,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var propertyType = new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "bannerName") { Name = "Banner Name", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 2, DataTypeId = -88 @@ -1675,8 +1686,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Trashed = false }; - var contentCollection = new PropertyTypeCollection(true); - contentCollection.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "hostname") { Name = "Hostname", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + var contentCollection = new PropertyTypeCollection(true) + { + new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "hostname") { Name = "Hostname", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 } + }; site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); return site; @@ -1684,28 +1697,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private ContentType CreateHomepage(ContentType parent) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); return ContentTypeBuilder.CreateSimpleContentType("homepage", "Homepage", parent, defaultTemplateId: template.Id); } private IContentType[] CreateContentTypeHierarchy() { - //create the master type - var template = TemplateBuilder.CreateTextPageTemplate(); + // create the master type + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var masterContentType = ContentTypeBuilder.CreateSimpleContentType("masterContentType", "MasterContentType", defaultTemplateId: template.Id); + ContentType masterContentType = ContentTypeBuilder.CreateSimpleContentType("masterContentType", "MasterContentType", defaultTemplateId: template.Id); masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); ContentTypeService.Save(masterContentType); - //add the one we just created + // add the one we just created var list = new List { masterContentType }; - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var contentType = ContentTypeBuilder.CreateSimpleContentType("childType" + i, "ChildType" + i, - //make the last entry in the list, this one's parent - list.Last(), randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType( + "childType" + i, + "ChildType" + i, + list.Last(), // make the last entry in the list, this one's parent + randomizeAliases: true, + defaultTemplateId: template.Id); list.Add(contentType); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs index b52609ce89..3671287da7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs @@ -1,24 +1,24 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using NPoco; using NUnit.Framework; -using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Models; using Umbraco.Core.DependencyInjection; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; -using Umbraco.Core.Sync; using Umbraco.Infrastructure.PublishedCache.DependencyInjection; -using Umbraco.Net; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; -using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.NuCache; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services @@ -49,20 +49,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void AssertJsonStartsWith(int id, string expected) { - var json = GetJson(id).Replace('"', '\''); - var pos = json.IndexOf("'cd':", StringComparison.InvariantCultureIgnoreCase); + string json = GetJson(id).Replace('"', '\''); + int pos = json.IndexOf("'cd':", StringComparison.InvariantCultureIgnoreCase); json = json.Substring(0, pos + "'cd':".Length); Assert.AreEqual(expected, json); } private string GetJson(int id) { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) + using (IScope scope = ScopeProvider.CreateScope(autoComplete: true)) { - var selectJson = SqlContext.Sql().Select().From().Where(x => x.NodeId == id && !x.Published); - var dto = scope.Database.Fetch(selectJson).FirstOrDefault(); + Sql selectJson = SqlContext.Sql().Select().From().Where(x => x.NodeId == id && !x.Published); + ContentNuDto dto = scope.Database.Fetch(selectJson).FirstOrDefault(); Assert.IsNotNull(dto); - var json = dto.Data; + string json = dto.Data; return json; } } @@ -85,16 +85,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment, false)] public void Change_Content_Type_Variation_Clears_Redirects(ContentVariation startingContentTypeVariation, ContentVariation changedContentTypeVariation, bool shouldUrlRedirectsBeCleared) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = startingContentTypeVariation; ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); ContentTypeService.Save(contentType2); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.Name = "Hello1"; - if(startingContentTypeVariation.HasFlag(ContentVariation.Culture)) + if (startingContentTypeVariation.HasFlag(ContentVariation.Culture)) { doc.SetCultureName(doc.Name, "en-US"); } @@ -111,10 +111,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(1, RedirectUrlService.GetContentRedirectUrls(doc.Key).Count()); Assert.AreEqual(1, RedirectUrlService.GetContentRedirectUrls(doc2.Key).Count()); - //change variation + // change variation contentType.Variations = changedContentTypeVariation; ContentTypeService.Save(contentType); - var expectedRedirectUrlCount = shouldUrlRedirectsBeCleared ? 0 : 1; + int expectedRedirectUrlCount = shouldUrlRedirectsBeCleared ? 0 : 1; Assert.AreEqual(expectedRedirectUrlCount, RedirectUrlService.GetContentRedirectUrls(doc.Key).Count()); Assert.AreEqual(1, RedirectUrlService.GetContentRedirectUrls(doc2.Key).Count()); } @@ -125,43 +125,43 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.Segment, ContentVariation.CultureAndSegment)] public void Change_Content_Type_From_No_Culture_To_Culture(ContentVariation from, ContentVariation to) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = from; - var properties = CreatePropertyCollection(("title", from)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", from)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.Name = "Hello1"; doc.SetValue("title", "hello world"); ContentService.Save(doc); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello1", doc.Name); Assert.AreEqual("hello world", doc.GetValue("title")); Assert.IsTrue(doc.Edited); Assert.IsFalse(doc.IsCultureEdited("en-US")); - //change the content type to be variant, we will also update the name here to detect the copy changes + // change the content type to be variant, we will also update the name here to detect the copy changes doc.Name = "Hello2"; ContentService.Save(doc); contentType.Variations = to; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello2", doc.GetCultureName("en-US")); - Assert.AreEqual("hello world", doc.GetValue("title")); //We are not checking against en-US here because properties will remain invariant + Assert.AreEqual("hello world", doc.GetValue("title")); // We are not checking against en-US here because properties will remain invariant Assert.IsTrue(doc.Edited); Assert.IsTrue(doc.IsCultureEdited("en-US")); - //change back property type to be invariant, we will also update the name here to detect the copy changes + // change back property type to be invariant, we will also update the name here to detect the copy changes doc.SetCultureName("Hello3", "en-US"); ContentService.Save(doc); contentType.Variations = from; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello3", doc.Name); Assert.AreEqual("hello world", doc.GetValue("title")); @@ -175,55 +175,55 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Content_Type_From_Culture_To_No_Culture(ContentVariation startingContentTypeVariation, ContentVariation changeContentTypeVariationTo) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = startingContentTypeVariation; - var properties = CreatePropertyCollection(("title", startingContentTypeVariation)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", startingContentTypeVariation)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Hello1", "en-US"); doc.SetValue("title", "hello world", "en-US"); ContentService.Save(doc); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello1", doc.GetCultureName("en-US")); Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); Assert.IsTrue(doc.Edited); Assert.IsTrue(doc.IsCultureEdited("en-US")); - //change the content type to be invariant, we will also update the name here to detect the copy changes + // change the content type to be invariant, we will also update the name here to detect the copy changes doc.SetCultureName("Hello2", "en-US"); ContentService.Save(doc); contentType.Variations = changeContentTypeVariationTo; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello2", doc.Name); Assert.AreEqual("hello world", doc.GetValue("title")); Assert.IsTrue(doc.Edited); Assert.IsFalse(doc.IsCultureEdited("en-US")); - //change back property type to be variant, we will also update the name here to detect the copy changes + // change back property type to be variant, we will also update the name here to detect the copy changes doc.Name = "Hello3"; ContentService.Save(doc); contentType.Variations = startingContentTypeVariation; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get - //at this stage all property types were switched to invariant so even though the variant value - //exists it will not be returned because the property type is invariant, - //so this check proves that null will be returned + // at this stage all property types were switched to invariant so even though the variant value + // exists it will not be returned because the property type is invariant, + // so this check proves that null will be returned Assert.AreEqual("Hello3", doc.Name); Assert.IsNull(doc.GetValue("title", "en-US")); Assert.IsTrue(doc.Edited); Assert.IsTrue(doc.IsCultureEdited("en-US")); // this is true because the name change is copied to the default language - //we can now switch the property type to be variant and the value can be returned again + // we can now switch the property type to be variant and the value can be returned again contentType.PropertyTypes.First().Variations = startingContentTypeVariation; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello3", doc.GetCultureName("en-US")); Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); @@ -249,23 +249,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment)] public void Preserve_Content_Name_After_Content_Type_Variation_Change(ContentVariation contentTypeVariationFrom, ContentVariation contentTypeVariationTo) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = contentTypeVariationFrom; ContentTypeService.Save(contentType); - var invariantContentName = "Content Invariant"; + string invariantContentName = "Content Invariant"; - var defaultCultureContentName = "Content en-US"; - var defaultCulture = "en-US"; + string defaultCultureContentName = "Content en-US"; + string defaultCulture = "en-US"; - var nlContentName = "Content nl-NL"; - var nlCulture = "nl-NL"; + string nlContentName = "Content nl-NL"; + string nlCulture = "nl-NL"; var globalSettings = new GlobalSettings(); LocalizationService.Save(new Language(globalSettings, nlCulture)); - var includeCultureNames = contentType.Variations.HasFlag(ContentVariation.Culture); + bool includeCultureNames = contentType.Variations.HasFlag(ContentVariation.Culture); // Create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); @@ -275,7 +275,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { Assert.DoesNotThrow(() => doc.SetCultureName(defaultCultureContentName, defaultCulture)); Assert.DoesNotThrow(() => doc.SetCultureName(nlContentName, nlCulture)); - } else + } + else { Assert.Throws(() => doc.SetCultureName(defaultCultureContentName, defaultCulture)); Assert.Throws(() => doc.SetCultureName(nlContentName, nlCulture)); @@ -329,14 +330,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment)] public void Verify_If_Property_Type_Variation_Is_Correctly_Corrected_When_Content_Type_Is_Updated(ContentVariation contentTypeVariation, ContentVariation propertyTypeVariation) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); // We test an updated content type so it has to be saved first. ContentTypeService.Save(contentType); // Update it contentType.Variations = contentTypeVariation; - var properties = CreatePropertyCollection(("title", propertyTypeVariation)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", propertyTypeVariation)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); @@ -350,40 +351,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.Segment, ContentVariation.CultureAndSegment)] public void Change_Property_Type_From_Invariant_Variant(ContentVariation invariant, ContentVariation variant) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); + // content type supports all variations contentType.Variations = ContentVariation.Culture | ContentVariation.Segment; - var properties = CreatePropertyCollection(("title", invariant)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", invariant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world"); ContentService.Save(doc); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); - Assert.IsTrue(doc.IsCultureEdited("en-US")); //invariant prop changes show up on default lang + Assert.IsTrue(doc.IsCultureEdited("en-US")); // invariant prop changes show up on default lang Assert.IsTrue(doc.Edited); - //change the property type to be variant + // change the property type to be variant contentType.PropertyTypes.First().Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); Assert.IsTrue(doc.IsCultureEdited("en-US")); Assert.IsTrue(doc.Edited); - //change back property type to be invariant + // change back property type to be invariant contentType.PropertyTypes.First().Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); - Assert.IsTrue(doc.IsCultureEdited("en-US")); //invariant prop changes show up on default lang + Assert.IsTrue(doc.IsCultureEdited("en-US")); // invariant prop changes show up on default lang Assert.IsTrue(doc.Edited); } @@ -393,15 +395,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Property_Type_From_Variant_Invariant(ContentVariation variant, ContentVariation invariant) { - //create content type with a property type that varies by culture - var contentType = ContentTypeBuilder.CreateBasicContentType(); + // create content type with a property type that varies by culture + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); + // content type supports all variations contentType.Variations = ContentVariation.Culture | ContentVariation.Segment; - var properties = CreatePropertyCollection(("title", variant)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", variant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world", "en-US"); @@ -409,17 +412,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); - //change the property type to be invariant + // change the property type to be invariant contentType.PropertyTypes.First().Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); - //change back property type to be variant + // change back property type to be variant contentType.PropertyTypes.First().Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); } @@ -430,21 +433,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Property_Type_From_Variant_Invariant_On_A_Composition(ContentVariation variant, ContentVariation invariant) { - //create content type with a property type that varies by culture - var contentType = ContentTypeBuilder.CreateBasicContentType(); + // create content type with a property type that varies by culture + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); + // content type supports all variations contentType.Variations = ContentVariation.Culture | ContentVariation.Segment; - var properties = CreatePropertyCollection(("title", variant)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", variant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //compose this from the other one - var contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); + // compose this from the other one + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); contentType2.Variations = contentType.Variations; contentType2.AddContentType(contentType); ContentTypeService.Save(contentType2); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world", "en-US"); @@ -455,20 +459,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services doc2.SetValue("title", "hello world", "en-US"); ContentService.Save(doc2); - //change the property type to be invariant + // change the property type to be invariant contentType.PropertyTypes.First().Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); Assert.AreEqual("hello world", doc2.GetValue("title")); - //change back property type to be variant + // change back property type to be variant contentType.PropertyTypes.First().Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); Assert.AreEqual("hello world", doc2.GetValue("title", "en-US")); @@ -480,20 +484,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Content_Type_From_Variant_Invariant_On_A_Composition(ContentVariation variant, ContentVariation invariant) { - //create content type with a property type that varies by culture - var contentType = ContentTypeBuilder.CreateBasicContentType(); + // create content type with a property type that varies by culture + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = variant; - var properties = CreatePropertyCollection(("title", ContentVariation.Culture)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", ContentVariation.Culture)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //compose this from the other one - var contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); + // compose this from the other one + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); contentType2.Variations = contentType.Variations; contentType2.AddContentType(contentType); ContentTypeService.Save(contentType2); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world", "en-US"); @@ -504,22 +508,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services doc2.SetValue("title", "hello world", "en-US"); ContentService.Save(doc2); - //change the content type to be invariant + // change the content type to be invariant contentType.Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); Assert.AreEqual("hello world", doc2.GetValue("title")); - //change back content type to be variant + // change back content type to be variant contentType.Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get - //this will be null because the doc type was changed back to variant but it's property types don't get changed back + // this will be null because the doc type was changed back to variant but it's property types don't get changed back Assert.IsNull(doc.GetValue("title", "en-US")); Assert.IsNull(doc2.GetValue("title", "en-US")); } @@ -531,9 +535,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change it to invariant and back CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture); + IContentType contentType = CreateContentType(ContentVariation.Culture); - var properties = CreatePropertyCollection( + PropertyTypeCollection properties = CreatePropertyCollection( ("value1", ContentVariation.Culture), ("value2", ContentVariation.Nothing)); @@ -557,7 +561,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'en','v':'v1en'},{'c':'fr','v':'v1fr'}],'value2':[{'v':'v2'}]},'cd':"); // switch content type to Nothing @@ -574,7 +579,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch content back to Culture @@ -591,7 +597,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch property back to Culture @@ -607,7 +614,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'fr','v':'v1fr'},{'c':'en','v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); } @@ -624,16 +632,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var languageFr = new Language(globalSettings, "fr"); LocalizationService.Save(languageFr); - var contentType = CreateContentType(ContentVariation.Nothing); + IContentType contentType = CreateContentType(ContentVariation.Nothing); - var properties = CreatePropertyCollection( + PropertyTypeCollection properties = CreatePropertyCollection( ("value1", ContentVariation.Nothing), ("value2", ContentVariation.Nothing)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - var document = (IContent) new Content("document", -1, contentType); + var document = (IContent)new Content("document", -1, contentType); document.Name = "doc1"; document.SetValue("value1", "v1"); document.SetValue("value2", "v2"); @@ -649,7 +657,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); // switch content type to Culture @@ -665,7 +674,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); // switch property to Culture @@ -680,7 +690,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'en','v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); // switch content back to Nothing @@ -697,7 +708,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); } @@ -708,9 +720,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change an invariant property to variant and back CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture); + IContentType contentType = CreateContentType(ContentVariation.Culture); - var properties = CreatePropertyCollection( + PropertyTypeCollection properties = CreatePropertyCollection( ("value1", ContentVariation.Culture), ("value2", ContentVariation.Nothing)); @@ -734,7 +746,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'en','v':'v1en'},{'c':'fr','v':'v1fr'}],'value2':[{'v':'v2'}]},'cd':"); // switch property type to Nothing @@ -751,7 +764,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch property back to Culture @@ -767,7 +781,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'fr','v':'v1fr'},{'c':'en','v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch other property to Culture @@ -785,7 +800,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsNull(document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'fr','v':'v1fr'},{'c':'en','v':'v1en'}],'value2':[{'c':'en','v':'v2'}]},'cd':"); } @@ -797,12 +813,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // one simple content type, variant, with both variant and invariant properties // can change an invariant property to variant and back - CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); + IContentType contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); - var properties = CreatePropertyCollection(("value1", variant)); + PropertyTypeCollection properties = CreatePropertyCollection(("value1", variant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); @@ -812,15 +827,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services document.SetCultureName("doc1fr", "fr"); document.SetValue("value1", "v1en-init", "en"); document.SetValue("value1", "v1fr-init", "fr"); - ContentService.SaveAndPublish(document); //all values are published which means the document is not 'edited' + ContentService.SaveAndPublish(document); // all values are published which means the document is not 'edited' document = ContentService.GetById(document.Id); Assert.IsFalse(document.IsCultureEdited("en")); Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsFalse(document.Edited); - document.SetValue("value1", "v1en", "en"); //change the property culture value, so now this culture will be edited - document.SetValue("value1", "v1fr", "fr"); //change the property culture value, so now this culture will be edited + document.SetValue("value1", "v1en", "en"); // change the property culture value, so now this culture will be edited + document.SetValue("value1", "v1fr", "fr"); // change the property culture value, so now this culture will be edited ContentService.Save(document); document = ContentService.GetById(document.Id); @@ -831,20 +846,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v1en-init", document.GetValue("value1", "en", published: true)); Assert.AreEqual("v1fr", document.GetValue("value1", "fr")); Assert.AreEqual("v1fr-init", document.GetValue("value1", "fr", published: true)); - Assert.IsTrue(document.IsCultureEdited("en")); //This will be true because the edited value isn't the same as the published value - Assert.IsTrue(document.IsCultureEdited("fr")); //This will be true because the edited value isn't the same as the published value + Assert.IsTrue(document.IsCultureEdited("en")); // This will be true because the edited value isn't the same as the published value + Assert.IsTrue(document.IsCultureEdited("fr")); // This will be true because the edited value isn't the same as the published value Assert.IsTrue(document.Edited); // switch property type to Invariant contentType.PropertyTypes.First(x => x.Alias == "value1").Variations = invariant; - ContentTypeService.Save(contentType); //This is going to have to re-normalize the "Edited" flag + ContentTypeService.Save(contentType); // This is going to have to re-normalize the "Edited" flag document = ContentService.GetById(document.Id); - Assert.IsTrue(document.IsCultureEdited("en")); //This will remain true because there is now a pending change for the invariant property data which is flagged under the default lang - Assert.IsFalse(document.IsCultureEdited("fr")); //This will be false because nothing has changed for this culture and the property no longer reflects variant changes + Assert.IsTrue(document.IsCultureEdited("en")); // This will remain true because there is now a pending change for the invariant property data which is flagged under the default lang + Assert.IsFalse(document.IsCultureEdited("fr")); // This will be false because nothing has changed for this culture and the property no longer reflects variant changes Assert.IsTrue(document.Edited); - //update the invariant value and publish + // update the invariant value and publish document.SetValue("value1", "v1inv"); ContentService.SaveAndPublish(document); @@ -852,14 +867,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1en", document.Name); Assert.AreEqual("doc1en", document.GetCultureName("en")); Assert.AreEqual("doc1fr", document.GetCultureName("fr")); - Assert.IsNull(document.GetValue("value1", "en")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "fr")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "en", published: true)); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "fr", published: true)); //The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "en")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "fr")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "en", published: true)); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "fr", published: true)); // The values are there but the business logic returns null Assert.AreEqual("v1inv", document.GetValue("value1")); Assert.AreEqual("v1inv", document.GetValue("value1", published: true)); - Assert.IsFalse(document.IsCultureEdited("en")); //This returns false, everything is published - Assert.IsFalse(document.IsCultureEdited("fr")); //This will be false because nothing has changed for this culture and the property no longer reflects variant changes + Assert.IsFalse(document.IsCultureEdited("en")); // This returns false, everything is published + Assert.IsFalse(document.IsCultureEdited("fr")); // This will be false because nothing has changed for this culture and the property no longer reflects variant changes Assert.IsFalse(document.Edited); // switch property back to Culture @@ -867,17 +882,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentType); document = ContentService.GetById(document.Id); - Assert.AreEqual("v1inv", document.GetValue("value1", "en")); //The invariant property value gets copied over to the default language + Assert.AreEqual("v1inv", document.GetValue("value1", "en")); // The invariant property value gets copied over to the default language Assert.AreEqual("v1inv", document.GetValue("value1", "en", published: true)); - Assert.AreEqual("v1fr", document.GetValue("value1", "fr")); //values are still retained - Assert.AreEqual("v1fr-init", document.GetValue("value1", "fr", published: true)); //values are still retained - Assert.IsFalse(document.IsCultureEdited("en")); //The invariant published AND edited values are copied over to the default language - Assert.IsTrue(document.IsCultureEdited("fr")); //The previously existing french values are there and there is no published value - Assert.IsTrue(document.Edited); //Will be flagged edited again because the french culture had pending changes + Assert.AreEqual("v1fr", document.GetValue("value1", "fr")); // values are still retained + Assert.AreEqual("v1fr-init", document.GetValue("value1", "fr", published: true)); // values are still retained + Assert.IsFalse(document.IsCultureEdited("en")); // The invariant published AND edited values are copied over to the default language + Assert.IsTrue(document.IsCultureEdited("fr")); // The previously existing french values are there and there is no published value + Assert.IsTrue(document.Edited); // Will be flagged edited again because the french culture had pending changes // publish again - document.SetValue("value1", "v1en2", "en"); //update the value now that it's variant again - document.SetValue("value1", "v1fr2", "fr"); //update the value now that it's variant again + document.SetValue("value1", "v1en2", "en"); // update the value now that it's variant again + document.SetValue("value1", "v1fr2", "fr"); // update the value now that it's variant again ContentService.SaveAndPublish(document); document = ContentService.GetById(document.Id); @@ -886,9 +901,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1fr", document.GetCultureName("fr")); Assert.AreEqual("v1en2", document.GetValue("value1", "en")); Assert.AreEqual("v1fr2", document.GetValue("value1", "fr")); - Assert.IsNull(document.GetValue("value1")); //The value is there but the business logic returns null - Assert.IsFalse(document.IsCultureEdited("en")); //This returns false, the variant property value has been published - Assert.IsFalse(document.IsCultureEdited("fr")); //This returns false, the variant property value has been published + Assert.IsNull(document.GetValue("value1")); // The value is there but the business logic returns null + Assert.IsFalse(document.IsCultureEdited("en")); // This returns false, the variant property value has been published + Assert.IsFalse(document.IsCultureEdited("fr")); // This returns false, the variant property value has been published Assert.IsFalse(document.Edited); } @@ -902,9 +917,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change an invariant property to variant and back CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); + IContentType contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); - var properties = CreatePropertyCollection(("value1", invariant)); + PropertyTypeCollection properties = CreatePropertyCollection(("value1", invariant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); @@ -913,14 +928,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services document.SetCultureName("doc1en", "en"); document.SetCultureName("doc1fr", "fr"); document.SetValue("value1", "v1en-init"); - ContentService.SaveAndPublish(document); //all values are published which means the document is not 'edited' + ContentService.SaveAndPublish(document); // all values are published which means the document is not 'edited' document = ContentService.GetById(document.Id); Assert.IsFalse(document.IsCultureEdited("en")); Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsFalse(document.Edited); - document.SetValue("value1", "v1en"); //change the property value, so now the invariant (default) culture will be edited + document.SetValue("value1", "v1en"); // change the property value, so now the invariant (default) culture will be edited ContentService.Save(document); document = ContentService.GetById(document.Id); @@ -929,20 +944,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1fr", document.GetCultureName("fr")); Assert.AreEqual("v1en", document.GetValue("value1")); Assert.AreEqual("v1en-init", document.GetValue("value1", published: true)); - Assert.IsTrue(document.IsCultureEdited("en")); //This is true because the invariant property reflects changes on the default lang + Assert.IsTrue(document.IsCultureEdited("en")); // This is true because the invariant property reflects changes on the default lang Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsTrue(document.Edited); // switch property type to Culture contentType.PropertyTypes.First(x => x.Alias == "value1").Variations = variant; - ContentTypeService.Save(contentType); //This is going to have to re-normalize the "Edited" flag + ContentTypeService.Save(contentType); // This is going to have to re-normalize the "Edited" flag document = ContentService.GetById(document.Id); - Assert.IsTrue(document.IsCultureEdited("en")); //Remains true - Assert.IsFalse(document.IsCultureEdited("fr")); //False because no french property has ever been edited + Assert.IsTrue(document.IsCultureEdited("en")); // Remains true + Assert.IsFalse(document.IsCultureEdited("fr")); // False because no french property has ever been edited Assert.IsTrue(document.Edited); - //update the culture value and publish + // update the culture value and publish document.SetValue("value1", "v1en2", "en"); ContentService.SaveAndPublish(document); @@ -950,12 +965,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1en", document.Name); Assert.AreEqual("doc1en", document.GetCultureName("en")); Assert.AreEqual("doc1fr", document.GetCultureName("fr")); - Assert.IsNull(document.GetValue("value1")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", published: true)); //The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", published: true)); // The values are there but the business logic returns null Assert.AreEqual("v1en2", document.GetValue("value1", "en")); Assert.AreEqual("v1en2", document.GetValue("value1", "en", published: true)); - Assert.IsFalse(document.IsCultureEdited("en")); //This returns false, everything is published - Assert.IsFalse(document.IsCultureEdited("fr")); //False because no french property has ever been edited + Assert.IsFalse(document.IsCultureEdited("en")); // This returns false, everything is published + Assert.IsFalse(document.IsCultureEdited("fr")); // False because no french property has ever been edited Assert.IsFalse(document.Edited); // switch property back to Invariant @@ -963,14 +978,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentType); document = ContentService.GetById(document.Id); - Assert.AreEqual("v1en2", document.GetValue("value1")); //The variant property value gets copied over to the invariant + Assert.AreEqual("v1en2", document.GetValue("value1")); // The variant property value gets copied over to the invariant Assert.AreEqual("v1en2", document.GetValue("value1", published: true)); - Assert.IsNull(document.GetValue("value1", "fr")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "fr", published: true)); //The values are there but the business logic returns null - Assert.IsFalse(document.IsCultureEdited("en")); //The variant published AND edited values are copied over to the invariant + Assert.IsNull(document.GetValue("value1", "fr")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "fr", published: true)); // The values are there but the business logic returns null + Assert.IsFalse(document.IsCultureEdited("en")); // The variant published AND edited values are copied over to the invariant Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsFalse(document.Edited); - } [Test] @@ -982,18 +996,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change the composed content type to invariant and back CreateFrenchAndEnglishLangs(); - var composing = CreateContentType(ContentVariation.Culture, "composing"); + IContentType composing = CreateContentType(ContentVariation.Culture, "composing"); - var properties1 = CreatePropertyCollection( + PropertyTypeCollection properties1 = CreatePropertyCollection( ("value11", ContentVariation.Culture), ("value12", ContentVariation.Nothing)); composing.PropertyGroups.Add(new PropertyGroup(properties1) { Name = "Content" }); ContentTypeService.Save(composing); - var composed = CreateContentType(ContentVariation.Culture, "composed"); + IContentType composed = CreateContentType(ContentVariation.Culture, "composed"); - var properties2 = CreatePropertyCollection( + PropertyTypeCollection properties2 = CreatePropertyCollection( ("value21", ContentVariation.Culture), ("value22", ContentVariation.Nothing)); @@ -1001,7 +1015,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services composed.AddContentType(composing); ContentTypeService.Save(composed); - var document = (IContent) new Content("document", -1, composed); + var document = (IContent)new Content("document", -1, composed); document.SetCultureName("doc1en", "en"); document.SetCultureName("doc1fr", "fr"); document.SetValue("value11", "v11en", "en"); @@ -1014,7 +1028,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are variant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'en','v':'v21en'},{'c':'fr','v':'v21fr'}],'value22':[{'v':'v22'}]},'cd':"); composed.Variations = ContentVariation.Nothing; @@ -1022,7 +1037,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composed.Variations = ContentVariation.Culture; @@ -1030,23 +1046,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is variant again, but value21 is still invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, - "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); + AssertJsonStartsWith( + document.Id, + "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composed.PropertyTypes.First(x => x.Alias == "value21").Variations = ContentVariation.Culture; ContentTypeService.Save(composed); // we can make it variant again Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, - "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); + AssertJsonStartsWith( + document.Id, + "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composing.Variations = ContentVariation.Nothing; ContentTypeService.Save(composing); // value11 is invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composing.Variations = ContentVariation.Culture; @@ -1054,7 +1073,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is still invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composing.PropertyTypes.First(x => x.Alias == "value11").Variations = ContentVariation.Culture; @@ -1062,7 +1082,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // we can make it variant again Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); } @@ -1076,18 +1097,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change the variant composed content type to invariant and back CreateFrenchAndEnglishLangs(); - var composing = CreateContentType(ContentVariation.Culture, "composing"); + IContentType composing = CreateContentType(ContentVariation.Culture, "composing"); - var properties1 = CreatePropertyCollection( + PropertyTypeCollection properties1 = CreatePropertyCollection( ("value11", ContentVariation.Culture), ("value12", ContentVariation.Nothing)); composing.PropertyGroups.Add(new PropertyGroup(properties1) { Name = "Content" }); ContentTypeService.Save(composing); - var composed1 = CreateContentType(ContentVariation.Culture, "composed1"); + IContentType composed1 = CreateContentType(ContentVariation.Culture, "composed1"); - var properties2 = CreatePropertyCollection( + PropertyTypeCollection properties2 = CreatePropertyCollection( ("value21", ContentVariation.Culture), ("value22", ContentVariation.Nothing)); @@ -1095,9 +1116,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services composed1.AddContentType(composing); ContentTypeService.Save(composed1); - var composed2 = CreateContentType(ContentVariation.Nothing, "composed2"); + IContentType composed2 = CreateContentType(ContentVariation.Nothing, "composed2"); - var properties3 = CreatePropertyCollection( + PropertyTypeCollection properties3 = CreatePropertyCollection( ("value31", ContentVariation.Nothing), ("value32", ContentVariation.Nothing)); @@ -1105,7 +1126,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services composed2.AddContentType(composing); ContentTypeService.Save(composed2); - var document1 = (IContent) new Content ("document1", -1, composed1); + var document1 = (IContent)new Content("document1", -1, composed1); document1.SetCultureName("doc1en", "en"); document1.SetCultureName("doc1fr", "fr"); document1.SetValue("value11", "v11en", "en"); @@ -1126,11 +1147,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are variant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'en','v':'v21en'},{'c':'fr','v':'v21fr'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composed1.Variations = ContentVariation.Nothing; @@ -1138,11 +1161,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composed1.Variations = ContentVariation.Culture; @@ -1150,11 +1175,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is variant again, but value21 is still invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, - "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); + AssertJsonStartsWith( + document1.Id, + "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composed1.PropertyTypes.First(x => x.Alias == "value21").Variations = ContentVariation.Culture; @@ -1162,11 +1189,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // we can make it variant again Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, - "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); + AssertJsonStartsWith( + document1.Id, + "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composing.Variations = ContentVariation.Nothing; @@ -1174,11 +1203,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composing.Variations = ContentVariation.Culture; @@ -1186,11 +1217,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is still invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composing.PropertyTypes.First(x => x.Alias == "value11").Variations = ContentVariation.Culture; @@ -1198,11 +1231,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // we can make it variant again Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); } @@ -1226,13 +1261,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { var propertyCollection = new PropertyTypeCollection(true); - foreach (var (alias, variance) in props) + foreach ((string alias, ContentVariation variance) in props) + { propertyCollection.Add(new PropertyType(ShortStringHelper, alias, ValueStorageType.Ntext) { Alias = alias, DataTypeId = -88, Variations = variance }); + } return propertyCollection; } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.cs index 2de7fb6b2a..9c284fb4b7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; @@ -21,11 +25,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class DataTypeServiceTests : UmbracoIntegrationTest { private IDataTypeService DataTypeService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private ILocalizedTextService LocalizedTextService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); [Test] @@ -47,26 +57,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void DataTypeService_Can_Delete_Textfield_DataType_And_Clear_Usages() { // Arrange - var textfieldId = "Umbraco.Textbox"; - var dataTypeDefinitions = DataTypeService.GetByEditorAlias(textfieldId); - var template = TemplateBuilder.CreateTextPageTemplate(); + string textfieldId = "Umbraco.Textbox"; + IEnumerable dataTypeDefinitions = DataTypeService.GetByEditorAlias(textfieldId); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var doctype = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); + ContentType doctype = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); ContentTypeService.Save(doctype); - // Act - var definition = dataTypeDefinitions.First(); - var definitionId = definition.Id; + IDataType definition = dataTypeDefinitions.First(); + int definitionId = definition.Id; DataTypeService.Delete(definition); - var deletedDefinition = DataTypeService.GetDataType(definitionId); + IDataType deletedDefinition = DataTypeService.GetDataType(definitionId); // Assert Assert.That(deletedDefinition, Is.Null); - //Further assertions against the ContentType that contains PropertyTypes based on the TextField - var contentType = ContentTypeService.Get(doctype.Id); + // Further assertions against the ContentType that contains PropertyTypes based on the TextField + IContentType contentType = ContentTypeService.Get(doctype.Id); Assert.That(contentType.Alias, Is.EqualTo("umbTextpage")); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(1)); } @@ -75,7 +84,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_DataType_With_Empty_Name() { // Act - var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService,LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = string.Empty, DatabaseType = ValueStorageType.Ntext }; + var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = string.Empty, DatabaseType = ValueStorageType.Ntext }; // Act & Assert Assert.Throws(() => DataTypeService.Save(dataTypeDefinition)); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs index 6d5cf19b50..a221575f7c 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; @@ -18,7 +21,6 @@ using Umbraco.Web.PublishedCache.NuCache; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { - /// /// Tests covering the EntityService /// @@ -31,12 +33,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private Language _langEs; private ILocalizationService LocalizationService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); + private IEntityService EntityService => GetRequiredService(); + private ISqlContext SqlContext => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); [SetUp] @@ -57,24 +66,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Descendants_Ordering_Path() { + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var contentType = ContentTypeService.Get("umbTextpage"); - - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); - var rootId = root.Id; + int rootId = root.Id; var ids = new List(); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); ids.Add(c1.Id); root = c1; // make a hierarchy } - long total; - - var entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[0], entities[0].Id); @@ -84,15 +90,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[6], entities[0].Id); - //Test ordering direction - - entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out total, + // Test ordering direction + entities = EntityService.GetPagedDescendants( + rootId, + UmbracoObjectTypes.Document, + 0, + 6, + out total, ordering: Ordering.By("Path", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); - Assert.AreEqual(ids[ids.Count - 1], entities[0].Id); + Assert.AreEqual(ids[^1], entities[0].Id); - entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 1, 6, out total, + entities = EntityService.GetPagedDescendants( + rootId, + UmbracoObjectTypes.Document, + 1, + 6, + out total, ordering: Ordering.By("Path", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); @@ -102,22 +117,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Children() { + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var contentType = ContentTypeService.Get("umbTextpage"); - - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); var ids = new List(); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); ids.Add(c1.Id); } - long total; - - var entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[0], entities[0].Id); @@ -127,15 +139,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[6], entities[0].Id); - //Test ordering direction - - entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out total, + // Test ordering direction + entities = EntityService.GetPagedChildren( + root.Id, + UmbracoObjectTypes.Document, + 0, + 6, + out total, ordering: Ordering.By("SortOrder", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); - Assert.AreEqual(ids[ids.Count - 1], entities[0].Id); + Assert.AreEqual(ids[^1], entities[0].Id); - entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 1, 6, out total, + entities = EntityService.GetPagedChildren( + root.Id, + UmbracoObjectTypes.Document, + 1, + 6, + out total, ordering: Ordering.By("SortOrder", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); @@ -145,27 +166,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); - var count = 0; + int count = 0; for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); count++; for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ContentService.Save(c2); count++; } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 31, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 31, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(31)); Assert.That(total, Is.EqualTo(60)); entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 1, 31, out total).ToArray(); @@ -176,14 +196,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants_Including_Recycled() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); if (i % 2 == 0) @@ -193,23 +213,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ContentService.Save(c2); } } - foreach (var content in toDelete) + foreach (IContent content in toDelete) { ContentService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Document, 0, 1000, out total) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Document, 0, 1000, out long total) .Select(x => x.Id) .ToArray(); - foreach (var c in toDelete) + foreach (IContent c in toDelete) { Assert.True(entities.Contains(c.Id)); } @@ -218,14 +237,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants_Without_Recycled() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); if (i % 2 == 0) @@ -235,23 +254,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ContentService.Save(c2); } } - foreach (var content in toDelete) + foreach (IContent content in toDelete) { ContentService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Document, 0, 1000, out total, includeTrashed: false) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Document, 0, 1000, out long total, includeTrashed: false) .Select(x => x.Id) .ToArray(); - foreach (var c in toDelete) + foreach (IContent c in toDelete) { Assert.IsFalse(entities.Contains(c.Id)); } @@ -260,29 +278,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants_With_Search() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, "ssss" + Guid.NewGuid(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, "ssss" + Guid.NewGuid(), root); ContentService.Save(c1); for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, "tttt" + Guid.NewGuid(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, "tttt" + Guid.NewGuid(), c1); ContentService.Save(c2); } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 10, out total, + IEntitySlim[] entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Document, + 0, + 10, + out long total, filter: SqlContext.Query().Where(x => x.Name.Contains("ssss"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(10)); Assert.That(total, Is.EqualTo(10)); - entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 50, out total, + entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Document, + 0, + 50, + out total, filter: SqlContext.Query().Where(x => x.Name.Contains("tttt"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(50)); Assert.That(total, Is.EqualTo(50)); @@ -291,19 +318,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Children() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); } - long total; - var entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 0, 6, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 1, 6, out total).ToArray(); @@ -314,28 +340,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); - var count = 0; + int count = 0; for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); count++; for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); MediaService.Save(c2); count++; } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 31, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 31, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(31)); Assert.That(total, Is.EqualTo(60)); entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 1, 31, out total).ToArray(); @@ -346,15 +371,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants_Including_Recycled() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); if (i % 2 == 0) @@ -364,23 +389,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); MediaService.Save(c2); } } - foreach (var content in toDelete) + foreach (IMedia content in toDelete) { MediaService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Media, 0, 1000, out total) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Media, 0, 1000, out long total) .Select(x => x.Id) .ToArray(); - foreach (var media in toDelete) + foreach (IMedia media in toDelete) { Assert.IsTrue(entities.Contains(media.Id)); } @@ -389,15 +413,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants_Without_Recycled() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); if (i % 2 == 0) @@ -407,23 +431,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); MediaService.Save(c2); } } - foreach (var content in toDelete) + foreach (IMedia content in toDelete) { MediaService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Media, 0, 1000, out total, includeTrashed: false) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Media, 0, 1000, out long total, includeTrashed: false) .Select(x => x.Id) .ToArray(); - foreach (var media in toDelete) + foreach (IMedia media in toDelete) { Assert.IsFalse(entities.Contains(media.Id)); } @@ -432,32 +455,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants_With_Search() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); c1.Name = "ssss" + Guid.NewGuid(); MediaService.Save(c1); for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); c2.Name = "tttt" + Guid.NewGuid(); MediaService.Save(c2); } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 10, out total, + IEntitySlim[] entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Media, + 0, + 10, + out long total, filter: SqlContext.Query().Where(x => x.Name.Contains("ssss"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(10)); Assert.That(total, Is.EqualTo(10)); - entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 50, out total, + entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Media, + 0, + 50, + out total, filter: SqlContext.Query().Where(x => x.Name.Contains("tttt"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(50)); Assert.That(total, Is.EqualTo(50)); @@ -466,7 +498,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Content_By_UmbracoObjectTypes() { - var entities = EntityService.GetAll(UmbracoObjectTypes.Document).ToArray(); + IEntitySlim[] entities = EntityService.GetAll(UmbracoObjectTypes.Document).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); @@ -476,8 +508,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Content_By_UmbracoObjectType_Id() { - var objectTypeId = Constants.ObjectTypes.Document; - var entities = EntityService.GetAll(objectTypeId).ToArray(); + Guid objectTypeId = Constants.ObjectTypes.Document; + IEntitySlim[] entities = EntityService.GetAll(objectTypeId).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); @@ -487,7 +519,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Content_By_Type() { - var entities = EntityService.GetAll().ToArray(); + IEntitySlim[] entities = EntityService.GetAll().ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); @@ -497,7 +529,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Child_Content_By_ParentId_And_UmbracoObjectType() { - var entities = EntityService.GetChildren(-1, UmbracoObjectTypes.Document).ToArray(); + IEntitySlim[] entities = EntityService.GetChildren(-1, UmbracoObjectTypes.Document).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(1)); @@ -507,23 +539,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Content_By_UmbracoObjectType_With_Variant_Names() { - var alias = "test" + Guid.NewGuid(); - var template = TemplateBuilder.CreateTextPageTemplate(alias); + string alias = "test" + Guid.NewGuid(); + Template template = TemplateBuilder.CreateTextPageTemplate(alias); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test2", "Test2", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test2", "Test2", defaultTemplateId: template.Id); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var c1 = ContentBuilder.CreateSimpleContent(contentType, "Test", -1); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, "Test", -1); c1.SetCultureName("Test - FR", _langFr.IsoCode); c1.SetCultureName("Test - ES", _langEs.IsoCode); ContentService.Save(c1); - var result = EntityService.Get(c1.Id, UmbracoObjectTypes.Document); + IEntitySlim result = EntityService.Get(c1.Id, UmbracoObjectTypes.Document); Assert.AreEqual("Test - FR", result.Name); // got name from default culture Assert.IsNotNull(result as IDocumentEntitySlim); var doc = (IDocumentEntitySlim)result; - var cultureNames = doc.CultureNames; + IReadOnlyDictionary cultureNames = doc.CultureNames; Assert.AreEqual("Test - FR", cultureNames[_langFr.IsoCode]); Assert.AreEqual("Test - ES", cultureNames[_langEs.IsoCode]); } @@ -531,19 +563,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Child_Content_By_ParentId_And_UmbracoObjectType_With_Variant_Names() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); root.SetCultureName("Root", _langFr.IsoCode); // else cannot save ContentService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); if (i % 2 == 0) { c1.SetCultureName("Test " + i + " - FR", _langFr.IsoCode); @@ -553,10 +585,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { c1.SetCultureName("Test", _langFr.IsoCode); // else cannot save } + ContentService.Save(c1); } - var entities = EntityService.GetChildren(root.Id, UmbracoObjectTypes.Document).ToArray(); + IEntitySlim[] entities = EntityService.GetChildren(root.Id, UmbracoObjectTypes.Document).ToArray(); Assert.AreEqual(10, entities.Length); @@ -584,7 +617,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Children_By_ParentId() { - var entities = EntityService.GetChildren(folderId); + IEnumerable entities = EntityService.GetChildren(_folderId); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(3)); @@ -594,7 +627,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Descendants_By_ParentId() { - var entities = EntityService.GetDescendants(folderId); + IEnumerable entities = EntityService.GetDescendants(_folderId); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(4)); @@ -604,7 +637,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Throws_When_Getting_All_With_Invalid_Type() { - var objectTypeId = Constants.ObjectTypes.ContentItem; + Guid objectTypeId = Constants.ObjectTypes.ContentItem; Assert.Throws(() => EntityService.GetAll()); Assert.Throws(() => EntityService.GetAll(objectTypeId)); @@ -613,7 +646,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_ContentTypes_By_UmbracoObjectTypes() { - var entities = EntityService.GetAll(UmbracoObjectTypes.DocumentType).ToArray(); + IEntitySlim[] entities = EntityService.GetAll(UmbracoObjectTypes.DocumentType).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); @@ -622,8 +655,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_ContentTypes_By_UmbracoObjectType_Id() { - var objectTypeId = Constants.ObjectTypes.DocumentType; - var entities = EntityService.GetAll(objectTypeId).ToArray(); + Guid objectTypeId = Constants.ObjectTypes.DocumentType; + IEntitySlim[] entities = EntityService.GetAll(objectTypeId).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); @@ -632,7 +665,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_ContentTypes_By_Type() { - var entities = EntityService.GetAll().ToArray(); + IEntitySlim[] entities = EntityService.GetAll().ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); @@ -641,12 +674,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Media_By_UmbracoObjectTypes() { - var entities = EntityService.GetAll(UmbracoObjectTypes.Media).ToArray(); + IEntitySlim[] entities = EntityService.GetAll(UmbracoObjectTypes.Media).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(5)); - foreach (var entity in entities) + foreach (IEntitySlim entity in entities) { Assert.IsTrue(entity.GetType().Implements()); Console.WriteLine(((IMediaEntitySlim)entity).MediaPath); @@ -656,8 +689,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_ObjectType() - { ; - var mediaObjectType = EntityService.GetObjectType(1031); + { + UmbracoObjectTypes mediaObjectType = EntityService.GetObjectType(1031); Assert.NotNull(mediaObjectType); Assert.AreEqual(mediaObjectType, UmbracoObjectTypes.MediaType); @@ -666,7 +699,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Key_For_Id_With_Unknown_Type() { - var result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.Unknown); + Attempt result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.Unknown); Assert.IsTrue(result.Success); Assert.AreEqual(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), result.Result); @@ -675,7 +708,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Key_For_Id() { - var result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); + Attempt result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); Assert.IsTrue(result.Success); Assert.AreEqual(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), result.Result); @@ -684,8 +717,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Cannot_Get_Key_For_Id_With_Incorrect_Object_Type() { - var result1 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); - var result2 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.MediaType); + Attempt result1 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); + Attempt result2 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.MediaType); Assert.IsTrue(result1.Success); Assert.IsFalse(result2.Success); @@ -694,7 +727,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Id_For_Key_With_Unknown_Type() { - var result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.Unknown); + Attempt result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.Unknown); Assert.IsTrue(result.Success); Assert.AreEqual(_contentType.Id, result.Result); @@ -703,7 +736,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Id_For_Key() { - var result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); + Attempt result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); Assert.IsTrue(result.Success); Assert.AreEqual(_contentType.Id, result.Result); @@ -712,8 +745,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Cannot_Get_Id_For_Key_With_Incorrect_Object_Type() { - var result1 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); - var result2 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.MediaType); + Attempt result1 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); + Attempt result2 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.MediaType); Assert.IsTrue(result1.Success); Assert.IsFalse(result2.Success); @@ -725,11 +758,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var guid = Guid.NewGuid(); // can reserve - var reservedId = EntityService.ReserveId(guid); + int reservedId = EntityService.ReserveId(guid); Assert.IsTrue(reservedId > 0); // can get it back - var id = EntityService.GetId(guid, UmbracoObjectTypes.DocumentType); + Attempt id = EntityService.GetId(guid, UmbracoObjectTypes.DocumentType); Assert.IsTrue(id.Success); Assert.AreEqual(reservedId, id.Result); @@ -742,9 +775,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(EntityService.GetId(Guid.NewGuid(), UmbracoObjectTypes.DocumentType).Success); } - private static bool _isSetup = false; + private static bool s_isSetup = false; - private int folderId; + private int _folderId; private ContentType _contentType; private Content _textpage; private Content _subpage; @@ -759,56 +792,57 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void CreateTestData() { - if (_isSetup == false) + if (s_isSetup == false) { - _isSetup = true; + s_isSetup = true; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! - //Create and Save ContentType "umbTextpage" -> _contentType.Id + // Create and Save ContentType "umbTextpage" -> _contentType.Id _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); _contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"); ContentTypeService.Save(_contentType); - //Create and Save Content "Homepage" based on "umbTextpage" -> 1053 + // Create and Save Content "Homepage" based on "umbTextpage" -> 1053 _textpage = ContentBuilder.CreateSimpleContent(_contentType); _textpage.Key = new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0"); ContentService.Save(_textpage, 0); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> 1054 + // Create and Save Content "Text Page 1" based on "umbTextpage" -> 1054 _subpage = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 1", _textpage.Id); _subpage.ContentSchedule.Add(DateTime.Now.AddMinutes(-5), null); ContentService.Save(_subpage, 0); - //Create and Save Content "Text Page 2" based on "umbTextpage" -> 1055 + // Create and Save Content "Text Page 2" based on "umbTextpage" -> 1055 _subpage2 = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 2", _textpage.Id); ContentService.Save(_subpage2, 0); - //Create and Save Content "Text Page Deleted" based on "umbTextpage" -> 1056 + // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> 1056 _trashed = ContentBuilder.CreateSimpleContent(_contentType, "Text Page Deleted", -20); _trashed.Trashed = true; ContentService.Save(_trashed, 0); - //Create and Save folder-Media -> 1057 + // Create and Save folder-Media -> 1057 _folderMediaType = MediaTypeService.Get(1031); _folder = MediaBuilder.CreateMediaFolder(_folderMediaType, -1); MediaService.Save(_folder, 0); - folderId = _folder.Id; + _folderId = _folder.Id; - //Create and Save image-Media -> 1058 + // Create and Save image-Media -> 1058 _imageMediaType = MediaTypeService.Get(1032); _image = MediaBuilder.CreateMediaImage(_imageMediaType, _folder.Id); MediaService.Save(_image, 0); - //Create and Save file-Media -> 1059 - var fileMediaType = MediaTypeService.Get(1033); - var file = MediaBuilder.CreateMediaFile(fileMediaType, _folder.Id); + // Create and Save file-Media -> 1059 + IMediaType fileMediaType = MediaTypeService.Get(1033); + Media file = MediaBuilder.CreateMediaFile(fileMediaType, _folder.Id); MediaService.Save(file, 0); // Create and save sub folder -> 1060 _subfolder = MediaBuilder.CreateMediaFolder(_folderMediaType, _folder.Id); MediaService.Save(_subfolder, 0); + // Create and save sub folder -> 1061 _subfolder2 = MediaBuilder.CreateMediaFolder(_folderMediaType, _subfolder.Id); MediaService.Save(_subfolder2, 0); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs index 8a04caeac7..d9c523bc58 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml.Linq; @@ -23,15 +26,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Export_Macro() { // Arrange - var macroService = GetRequiredService(); - var macro = new MacroBuilder() + IMacroService macroService = GetRequiredService(); + Macro macro = new MacroBuilder() .WithAlias("test1") .WithName("Test") .Build(); macroService.Save(macro); // Act - var element = Serializer.Serialize(macro); + XElement element = Serializer.Serialize(macro); // Assert Assert.That(element, Is.Not.Null); @@ -45,14 +48,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange CreateDictionaryData(); - var localizationService = GetRequiredService(); - var dictionaryItem = localizationService.GetDictionaryItemByKey("Parent"); + ILocalizationService localizationService = GetRequiredService(); + IDictionaryItem dictionaryItem = localizationService.GetDictionaryItemByKey("Parent"); var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); // Act - var xml = Serializer.Serialize(new[] { dictionaryItem }); + XElement xml = Serializer.Serialize(new[] { dictionaryItem }); // Assert Assert.That(xml.ToString(), Is.EqualTo(dictionaryItemsElement.ToString())); @@ -62,24 +65,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Export_Languages() { // Arrange - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - var languageNbNo = new LanguageBuilder() + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .WithCultureName("Norwegian") .Build(); localizationService.Save(languageNbNo); - var languageEnGb = new LanguageBuilder() + ILanguage languageEnGb = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); localizationService.Save(languageEnGb); var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var languageItemsElement = newPackageXml.Elements("Languages").First(); + XElement languageItemsElement = newPackageXml.Elements("Languages").First(); // Act - var xml = Serializer.Serialize(new[] { languageNbNo, languageEnGb }); + XElement xml = Serializer.Serialize(new[] { languageNbNo, languageEnGb }); // Assert Assert.That(xml.ToString(), Is.EqualTo(languageItemsElement.ToString())); @@ -87,15 +90,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void CreateDictionaryData() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - var languageNbNo = new LanguageBuilder() + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .WithCultureName("Norwegian") .Build(); localizationService.Save(languageNbNo); - var languageEnGb = new LanguageBuilder() + ILanguage languageEnGb = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); localizationService.Save(languageEnGb); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs index 192971f405..b47c8fb51e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs @@ -1,4 +1,8 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; +using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; @@ -18,6 +22,7 @@ namespace Umbraco.Tests.Services public class ExternalLoginServiceTests : UmbracoIntegrationTest { private IUserService UserService => GetRequiredService(); + private IExternalLoginService ExternalLoginService => GetRequiredService(); [Test] @@ -26,11 +31,11 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey = Guid.NewGuid().ToString("N"); - var latest = DateTime.Now.AddDays(-1); - var oldest = DateTime.Now.AddDays(-10); + string providerKey = Guid.NewGuid().ToString("N"); + DateTime latest = DateTime.Now.AddDays(-1); + DateTime oldest = DateTime.Now.AddDays(-10); - using (var scope = ScopeProvider.CreateScope()) + using (Core.Scoping.IScope scope = ScopeProvider.CreateScope()) { // insert duplicates manuall scope.Database.Insert(new ExternalLoginDto @@ -50,7 +55,7 @@ namespace Umbraco.Tests.Services } // try to save 2 other duplicates - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test2", providerKey), new ExternalLogin("test2", providerKey), @@ -64,7 +69,7 @@ namespace Umbraco.Tests.Services // duplicates will be removed, keeping the latest entries Assert.AreEqual(2, logins.Count); - var test1 = logins.Single(x => x.LoginProvider == "test1"); + IIdentityUserLogin test1 = logins.Single(x => x.LoginProvider == "test1"); Assert.Greater(test1.CreateDate, latest); } @@ -74,8 +79,8 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey = Guid.NewGuid().ToString("N"); - var externalLogins = new[] + string providerKey = Guid.NewGuid().ToString("N"); + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", providerKey), new ExternalLogin("test1", providerKey) @@ -99,7 +104,7 @@ namespace Umbraco.Tests.Services }; ExternalLoginService.Save(extLogin); - var found = ExternalLoginService.GetAll(user.Id); + IEnumerable found = ExternalLoginService.GetAll(user.Id); Assert.AreEqual(1, found.Count()); Assert.IsTrue(extLogin.HasIdentity); @@ -132,9 +137,9 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey1 = Guid.NewGuid().ToString("N"); - var providerKey2 = Guid.NewGuid().ToString("N"); - var extLogins = new[] + string providerKey1 = Guid.NewGuid().ToString("N"); + string providerKey2 = Guid.NewGuid().ToString("N"); + ExternalLogin[] extLogins = new[] { new ExternalLogin("test1", providerKey1, "hello"), new ExternalLogin("test2", providerKey2, "world") @@ -160,9 +165,9 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey1 = Guid.NewGuid().ToString("N"); - var providerKey2 = Guid.NewGuid().ToString("N"); - var extLogins = new[] + string providerKey1 = Guid.NewGuid().ToString("N"); + string providerKey2 = Guid.NewGuid().ToString("N"); + ExternalLogin[] extLogins = new[] { new ExternalLogin("test1", providerKey1, "hello"), new ExternalLogin("test2", providerKey2, "world") @@ -173,7 +178,6 @@ namespace Umbraco.Tests.Services Assert.AreEqual(1, found.Count); var asExtended = found.ToList(); Assert.AreEqual(1, found.Count); - } [Test] @@ -182,7 +186,7 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", Guid.NewGuid().ToString("N")), new ExternalLogin("test2", Guid.NewGuid().ToString("N")) @@ -205,7 +209,7 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", Guid.NewGuid().ToString("N")), new ExternalLogin("test2", Guid.NewGuid().ToString("N")), @@ -237,7 +241,7 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", Guid.NewGuid().ToString("N"), "hello world") }; @@ -247,7 +251,6 @@ namespace Umbraco.Tests.Services var logins = ExternalLoginService.GetAll(user.Id).ToList(); Assert.AreEqual("hello world", logins[0].UserData); - } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs index 1820573cc2..9ca4b79a6e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using System.Threading; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -18,8 +22,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Template_Then_Assign_Child() { - var child = FileService.CreateTemplateWithIdentity("Child", "child", "test"); - var parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); + ITemplate child = FileService.CreateTemplateWithIdentity("Child", "child", "test"); + ITemplate parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); child.SetMasterTemplate(parent); FileService.SaveTemplate(child); @@ -27,14 +31,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services child = FileService.GetTemplate(child.Id); Assert.AreEqual(parent.Alias, child.MasterTemplateAlias); - } [Test] public void Create_Template_With_Child_Then_Unassign() { - var parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); - var child = FileService.CreateTemplateWithIdentity("Child", "child", "test", parent); + ITemplate parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); + ITemplate child = FileService.CreateTemplateWithIdentity("Child", "child", "test", parent); child.SetMasterTemplate(null); FileService.SaveTemplate(child); @@ -47,11 +50,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Query_Template_Children() { - var parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); - var child1 = FileService.CreateTemplateWithIdentity("Child1", "child1", "test", parent); - var child2 = FileService.CreateTemplateWithIdentity("Child2", "child2", "test", parent); + ITemplate parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); + ITemplate child1 = FileService.CreateTemplateWithIdentity("Child1", "child1", "test", parent); + ITemplate child2 = FileService.CreateTemplateWithIdentity("Child2", "child2", "test", parent); - var children = FileService.GetTemplates(parent.Id).Select(x => x.Id).ToArray(); + int[] children = FileService.GetTemplates(parent.Id).Select(x => x.Id).ToArray(); Assert.IsTrue(children.Contains(child1.Id)); Assert.IsTrue(children.Contains(child2.Id)); @@ -60,7 +63,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Template_With_Custom_Alias() { - var template = FileService.CreateTemplateWithIdentity("Test template", "customTemplateAlias", "test"); + ITemplate template = FileService.CreateTemplateWithIdentity("Test template", "customTemplateAlias", "test"); FileService.SaveTemplate(template); @@ -69,6 +72,5 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("Test template", template.Name); Assert.AreEqual("customTemplateAlias", template.Alias); } - } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs index 8248e89dc2..5ffbe871a7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs @@ -1,4 +1,7 @@ -using System.Threading; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Threading; using NUnit.Framework; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; @@ -20,7 +23,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void GetValue_ForMissingKey_ReturnsNull() { // Act - var value = KeyValueService.GetValue("foo"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.IsNull(value); @@ -32,7 +35,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services KeyValueService.SetValue("foo", "bar"); // Act - var value = KeyValueService.GetValue("foo"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.AreEqual("bar", value); @@ -45,7 +48,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Act KeyValueService.SetValue("foo", "buzz"); - var value = KeyValueService.GetValue("foo"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.AreEqual("buzz", value); @@ -57,8 +60,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services KeyValueService.SetValue("foo", "bar"); // Act - var result = KeyValueService.TrySetValue("foo", "bar", "buzz"); - var value = KeyValueService.GetValue("foo"); + bool result = KeyValueService.TrySetValue("foo", "bar", "buzz"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.IsTrue(result); @@ -71,8 +74,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services KeyValueService.SetValue("foo", "bar"); // Act - var result = KeyValueService.TrySetValue("foo", "bang", "buzz"); - var value = KeyValueService.GetValue("foo"); + bool result = KeyValueService.TrySetValue("foo", "bang", "buzz"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.IsFalse(result); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs index 5076a3bbf7..a920682f4f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -6,6 +9,7 @@ using System.Threading; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Persistence; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -34,15 +38,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private ILocalizationService LocalizationService => GetRequiredService(); [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); [Test] public void Can_Get_Root_Dictionary_Items() { - var rootItems = LocalizationService.GetRootDictionaryItems(); + IEnumerable rootItems = LocalizationService.GetRootDictionaryItems(); Assert.NotNull(rootItems); Assert.IsTrue(rootItems.Any()); @@ -51,14 +52,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Determint_If_DictionaryItem_Exists() { - var exists = LocalizationService.DictionaryItemExists("Parent"); + bool exists = LocalizationService.DictionaryItemExists("Parent"); Assert.IsTrue(exists); } [Test] public void Can_Get_All_Languages() { - var languages = LocalizationService.GetAllLanguages(); + IEnumerable languages = LocalizationService.GetAllLanguages(); Assert.NotNull(languages); Assert.IsTrue(languages.Any()); Assert.That(languages.Count(), Is.EqualTo(3)); @@ -67,41 +68,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Dictionary_Item_By_Int_Id() { - var parentItem = LocalizationService.GetDictionaryItemById(_parentItemIntId); + IDictionaryItem parentItem = LocalizationService.GetDictionaryItemById(_parentItemIntId); Assert.NotNull(parentItem); - var childItem = LocalizationService.GetDictionaryItemById(_childItemIntId); + IDictionaryItem childItem = LocalizationService.GetDictionaryItemById(_childItemIntId); Assert.NotNull(childItem); } [Test] public void Can_Get_Dictionary_Item_By_Guid_Id() { - var parentItem = LocalizationService.GetDictionaryItemById(_parentItemGuidId); + IDictionaryItem parentItem = LocalizationService.GetDictionaryItemById(_parentItemGuidId); Assert.NotNull(parentItem); - var childItem = LocalizationService.GetDictionaryItemById(_childItemGuidId); + IDictionaryItem childItem = LocalizationService.GetDictionaryItemById(_childItemGuidId); Assert.NotNull(childItem); } [Test] public void Can_Get_Dictionary_Item_By_Key() { - var parentItem = LocalizationService.GetDictionaryItemByKey("Parent"); + IDictionaryItem parentItem = LocalizationService.GetDictionaryItemByKey("Parent"); Assert.NotNull(parentItem); - var childItem = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem childItem = LocalizationService.GetDictionaryItemByKey("Child"); Assert.NotNull(childItem); } [Test] public void Can_Get_Dictionary_Item_Children() { - var item = LocalizationService.GetDictionaryItemChildren(_parentItemGuidId); + IEnumerable item = LocalizationService.GetDictionaryItemChildren(_parentItemGuidId); Assert.NotNull(item); Assert.That(item.Count(), Is.EqualTo(1)); - foreach (var dictionaryItem in item) + foreach (IDictionaryItem dictionaryItem in item) { Assert.AreEqual(_parentItemGuidId, dictionaryItem.ParentId); Assert.IsFalse(string.IsNullOrEmpty(dictionaryItem.ItemKey)); @@ -111,15 +112,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Dictionary_Item_Descendants() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var en = LocalizationService.GetLanguageById(_englishLangId); - var dk = LocalizationService.GetLanguageById(_danishLangId); + ILanguage en = LocalizationService.GetLanguageById(_englishLangId); + ILanguage dk = LocalizationService.GetLanguageById(_danishLangId); - var currParentId = _childItemGuidId; - for (var i = 0; i < 25; i++) + Guid currParentId = _childItemGuidId; + for (int i = 0; i < 25; i++) { - //Create 2 per level + // Create 2 per level var desc1 = new DictionaryItem(currParentId, "D1" + i) { Translations = new List @@ -145,12 +146,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var items = LocalizationService.GetDictionaryItemDescendants(_parentItemGuidId).ToArray(); + IDictionaryItem[] items = LocalizationService.GetDictionaryItemDescendants(_parentItemGuidId).ToArray(); Debug.WriteLine("SQL CALLS: " + scope.Database.AsUmbracoDatabase().SqlCount); Assert.AreEqual(51, items.Length); - //there's a call or two to get languages, so apart from that there should only be one call per level + + // There's a call or two to get languages, so apart from that there should only be one call per level. Assert.Less(scope.Database.AsUmbracoDatabase().SqlCount, 30); } } @@ -158,8 +160,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_GetLanguageById() { - var danish = LocalizationService.GetLanguageById(_danishLangId); - var english = LocalizationService.GetLanguageById(_englishLangId); + ILanguage danish = LocalizationService.GetLanguageById(_danishLangId); + ILanguage english = LocalizationService.GetLanguageById(_englishLangId); Assert.NotNull(danish); Assert.NotNull(english); } @@ -167,8 +169,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_GetLanguageByIsoCode() { - var danish = LocalizationService.GetLanguageByIsoCode("da-DK"); - var english = LocalizationService.GetLanguageByIsoCode("en-GB"); + ILanguage danish = LocalizationService.GetLanguageByIsoCode("da-DK"); + ILanguage english = LocalizationService.GetLanguageByIsoCode("en-GB"); Assert.NotNull(danish); Assert.NotNull(english); } @@ -176,54 +178,54 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Does_Not_Fail_When_Language_Doesnt_Exist() { - var language = LocalizationService.GetLanguageByIsoCode("sv-SE"); + ILanguage language = LocalizationService.GetLanguageByIsoCode("sv-SE"); Assert.Null(language); } [Test] public void Does_Not_Fail_When_DictionaryItem_Doesnt_Exist() { - var item = LocalizationService.GetDictionaryItemByKey("RandomKey"); + IDictionaryItem item = LocalizationService.GetDictionaryItemByKey("RandomKey"); Assert.Null(item); } [Test] public void Can_Delete_Language() { - var languageNbNo = new LanguageBuilder() + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .Build(); LocalizationService.Save(languageNbNo, 0); Assert.That(languageNbNo.HasIdentity, Is.True); - var languageId = languageNbNo.Id; + int languageId = languageNbNo.Id; LocalizationService.Delete(languageNbNo); - var language = LocalizationService.GetLanguageById(languageId); + ILanguage language = LocalizationService.GetLanguageById(languageId); Assert.Null(language); } [Test] public void Can_Delete_Language_Used_As_Fallback() { - var languageDaDk = LocalizationService.GetLanguageByIsoCode("da-DK"); - var languageNbNo = new LanguageBuilder() + ILanguage languageDaDk = LocalizationService.GetLanguageByIsoCode("da-DK"); + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .WithFallbackLanguageId(languageDaDk.Id) .Build(); LocalizationService.Save(languageNbNo, 0); - var languageId = languageDaDk.Id; + int languageId = languageDaDk.Id; LocalizationService.Delete(languageDaDk); - var language = LocalizationService.GetLanguageById(languageId); + ILanguage language = LocalizationService.GetLanguageById(languageId); Assert.Null(language); } [Test] public void Can_Create_DictionaryItem_At_Root() { - var english = LocalizationService.GetLanguageByIsoCode("en-US"); + ILanguage english = LocalizationService.GetLanguageByIsoCode("en-US"); var item = (IDictionaryItem)new DictionaryItem("Testing123") { @@ -234,7 +236,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }; LocalizationService.Save(item); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); Assert.Greater(item.Id, 0); @@ -247,10 +249,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Create_DictionaryItem_At_Root_With_Identity() { - var item = LocalizationService.CreateDictionaryItemWithIdentity( + IDictionaryItem item = LocalizationService.CreateDictionaryItemWithIdentity( "Testing12345", null, "Hellooooo"); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); Assert.IsNotNull(item); @@ -258,9 +260,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(item.HasIdentity); Assert.IsFalse(item.ParentId.HasValue); Assert.AreEqual("Testing12345", item.ItemKey); - var allLangs = LocalizationService.GetAllLanguages(); + IEnumerable allLangs = LocalizationService.GetAllLanguages(); Assert.Greater(allLangs.Count(), 0); - foreach (var language in allLangs) + foreach (ILanguage language in allLangs) { Assert.AreEqual("Hellooooo", item.Translations.Single(x => x.Language.CultureName == language.CultureName).Value); } @@ -269,12 +271,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Add_Translation_To_Existing_Dictionary_Item() { - var english = LocalizationService.GetLanguageByIsoCode("en-US"); + ILanguage english = LocalizationService.GetLanguageByIsoCode("en-US"); - var item = (IDictionaryItem) new DictionaryItem("Testing123"); + var item = (IDictionaryItem)new DictionaryItem("Testing123"); LocalizationService.Save(item); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); item.Translations = new List @@ -285,7 +287,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(item); Assert.AreEqual(1, item.Translations.Count()); - foreach (var translation in item.Translations) + foreach (IDictionaryTranslation translation in item.Translations) { Assert.AreEqual("Hello world", translation.Value); } @@ -299,7 +301,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(item); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); Assert.AreEqual(2, item.Translations.Count()); @@ -310,30 +312,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Delete_DictionaryItem() { - var item = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem item = LocalizationService.GetDictionaryItemByKey("Child"); Assert.NotNull(item); LocalizationService.Delete(item); - var deletedItem = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem deletedItem = LocalizationService.GetDictionaryItemByKey("Child"); Assert.Null(deletedItem); } [Test] public void Can_Update_Existing_DictionaryItem() { - var item = LocalizationService.GetDictionaryItemByKey("Child"); - foreach (var translation in item.Translations) + IDictionaryItem item = LocalizationService.GetDictionaryItemByKey("Child"); + foreach (IDictionaryTranslation translation in item.Translations) { - translation.Value = translation.Value + "UPDATED"; + translation.Value += "UPDATED"; } LocalizationService.Save(item); - var updatedItem = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem updatedItem = LocalizationService.GetDictionaryItemByKey("Child"); Assert.NotNull(updatedItem); - foreach (var translation in updatedItem.Translations) + foreach (IDictionaryTranslation translation in updatedItem.Translations) { Assert.That(translation.Value.EndsWith("UPDATED"), Is.True); } @@ -343,7 +345,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Find_BaseData_Language() { // Act - var languages = LocalizationService.GetAllLanguages(); + IEnumerable languages = LocalizationService.GetAllLanguages(); // Assert Assert.That(3, Is.EqualTo(languages.Count())); @@ -353,14 +355,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Save_Language_And_GetLanguageByIsoCode() { // Arrange - var isoCode = "en-AU"; - var languageEnAu = new LanguageBuilder() + string isoCode = "en-AU"; + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo(isoCode) .Build(); // Act LocalizationService.Save(languageEnAu); - var result = LocalizationService.GetLanguageByIsoCode(isoCode); + ILanguage result = LocalizationService.GetLanguageByIsoCode(isoCode); // Assert Assert.NotNull(result); @@ -370,13 +372,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Save_Language_And_GetLanguageById() { // Arrange - var languageEnAu = new LanguageBuilder() + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo("en-AU") .Build(); // Act LocalizationService.Save(languageEnAu); - var result = LocalizationService.GetLanguageById(languageEnAu.Id); + ILanguage result = LocalizationService.GetLanguageById(languageEnAu.Id); // Assert Assert.NotNull(result); @@ -385,23 +387,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Set_Default_Language() { - var languageEnAu = new LanguageBuilder() + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo("en-AU") .WithIsDefault(true) .Build(); LocalizationService.Save(languageEnAu); - var result = LocalizationService.GetLanguageById(languageEnAu.Id); + ILanguage result = LocalizationService.GetLanguageById(languageEnAu.Id); Assert.IsTrue(result.IsDefault); - var languageEnNz = new LanguageBuilder() + ILanguage languageEnNz = new LanguageBuilder() .WithCultureInfo("en-NZ") .WithIsDefault(true) .Build(); LocalizationService.Save(languageEnNz); - var result2 = LocalizationService.GetLanguageById(languageEnNz.Id); + ILanguage result2 = LocalizationService.GetLanguageById(languageEnNz.Id); - //re-get + // re-get result = LocalizationService.GetLanguageById(languageEnAu.Id); Assert.IsTrue(result2.IsDefault); @@ -411,15 +413,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleted_Language_Should_Not_Exist() { - var isoCode = "en-AU"; - var languageEnAu = new LanguageBuilder() + string isoCode = "en-AU"; + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo(isoCode) .Build(); LocalizationService.Save(languageEnAu); // Act LocalizationService.Delete(languageEnAu); - var result = LocalizationService.GetLanguageByIsoCode(isoCode); + ILanguage result = LocalizationService.GetLanguageByIsoCode(isoCode); // Assert Assert.Null(result); @@ -427,10 +429,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void CreateTestData() { - var languageDaDk = new LanguageBuilder() + ILanguage languageDaDk = new LanguageBuilder() .WithCultureInfo("da-DK") .Build(); - var languageEnGb = new LanguageBuilder() + ILanguage languageEnGb = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs index d2c1e3b7fc..df89e32f96 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.Extensions.Logging; @@ -26,10 +30,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [SetUp] public void SetupTest() { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + IScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) scopeProvider, AppCaches.Disabled, Mock.Of>(), ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)scopeProvider, AppCaches.Disabled, Mock.Of>(), ShortStringHelper); repository.Save(new Macro(ShortStringHelper, "test1", "Test1", "~/views/macropartials/test1.cshtml")); repository.Save(new Macro(ShortStringHelper, "test2", "Test2", "~/views/macropartials/test2.cshtml")); @@ -42,7 +46,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_By_Alias() { // Act - var macro = MacroService.GetByAlias("test1"); + IMacro macro = MacroService.GetByAlias("test1"); // Assert Assert.IsNotNull(macro); @@ -53,7 +57,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_All() { // Act - var result = MacroService.GetAll(); + IEnumerable result = MacroService.GetAll(); // Assert Assert.AreEqual(3, result.Count()); @@ -63,14 +67,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Create() { // Act - var macro = CreateMacro(); + IMacro macro = CreateMacro(); MacroService.Save(macro); // Assert Assert.IsTrue(macro.HasIdentity); Assert.Greater(macro.Id, 0); Assert.AreNotEqual(Guid.Empty, macro.Key); - var result = MacroService.GetById(macro.Id); + IMacro result = MacroService.GetById(macro.Id); Assert.AreEqual("test", result.Alias); Assert.AreEqual("Test", result.Name); Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.MacroSource); @@ -94,7 +98,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MacroService.Delete(macro); // Assert - var result = MacroService.GetById(macro.Id); + IMacro result = MacroService.GetById(macro.Id); Assert.IsNull(result); result = MacroService.GetById(macro.Key); @@ -105,11 +109,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Update() { // Arrange - var macro = CreateMacro(); + IMacro macro = CreateMacro(); MacroService.Save(macro); // Act - var currKey = macro.Key; + Guid currKey = macro.Key; macro.Name = "New name"; macro.Alias = "NewAlias"; MacroService.Save(macro); @@ -120,21 +124,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("New name", macro.Name); Assert.AreEqual("NewAlias", macro.Alias); Assert.AreEqual(currKey, macro.Key); - } [Test] public void Can_Update_Property() { // Arrange - var macro = CreateMacro(); + IMacro macro = CreateMacro(); macro.Properties.Add(new MacroProperty("blah", "Blah", 0, "blah")); MacroService.Save(macro); Assert.AreNotEqual(Guid.Empty, macro.Properties[0].Key); // Act - var currPropKey = macro.Properties[0].Key; + Guid currPropKey = macro.Properties[0].Key; macro.Properties[0].Alias = "new Alias"; macro.Properties[0].Name = "new Name"; macro.Properties[0].SortOrder = 1; @@ -157,14 +160,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Update_Remove_Property() { // Arrange - var macro = CreateMacro(); + IMacro macro = CreateMacro(); macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); macro.Properties.Add(new MacroProperty("blah2", "Blah2", 1, "blah2")); macro.Properties.Add(new MacroProperty("blah3", "Blah3", 2, "blah3")); MacroService.Save(macro); - var lastKey = macro.Properties[0].Key; - for (var i = 1; i < macro.Properties.Count; i++) + Guid lastKey = macro.Properties[0].Key; + for (int i = 1; i < macro.Properties.Count; i++) { Assert.AreNotEqual(Guid.Empty, macro.Properties[i].Key); Assert.AreNotEqual(lastKey, macro.Properties[i].Key); @@ -199,7 +202,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Add_And_Remove_Properties() { - var macro = CreateMacro(); + IMacro macro = CreateMacro(); // Adds some properties macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); @@ -208,11 +211,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services macro.Properties.Add(new MacroProperty("blah4", "Blah4", 0, "blah4")); MacroService.Save(macro); - var result1 = MacroService.GetById(macro.Id); + IMacro result1 = MacroService.GetById(macro.Id); Assert.AreEqual(4, result1.Properties.Values.Count()); // Simulate clearing the sections - foreach (var s in result1.Properties.Values.ToArray()) + foreach (IMacroProperty s in result1.Properties.Values.ToArray()) { result1.Properties.Remove(s.Alias); } @@ -225,27 +228,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert result1 = MacroService.GetById(result1.Id); Assert.AreEqual(2, result1.Properties.Values.Count()); - } [Test] public void Cannot_Save_Macro_With_Empty_Name() { // Arrange - var macro = CreateMacro(name: string.Empty); + IMacro macro = CreateMacro(name: string.Empty); // Act & Assert Assert.Throws(() => MacroService.Save(macro)); } - private static IMacro CreateMacro(string name = "Test") - { - return new MacroBuilder() + private static IMacro CreateMacro(string name = "Test") => + new MacroBuilder() .WithAlias("test") .WithName(name) .WithSource("~/Views/MacroPartials/Test.cshtml") .WithCacheDuration(1234) .Build(); - } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.cs index ca3605217e..3abbc0c38c 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; @@ -6,6 +10,7 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; using Umbraco.Core.Models; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; using Umbraco.Tests.Common.Builders; @@ -21,8 +26,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MediaServiceTests : UmbracoIntegrationTest { private IMediaService MediaService => GetRequiredService(); - private IMediaTypeService MediaTypeService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); [Test] public void Can_Update_Media_Property_Values() @@ -51,22 +56,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services /// /// Used to list out all ambiguous events that will require dispatching with a name /// - [Test, Explicit] + [Test] + [Explicit] public void List_Ambiguous_Events() { - var events = MediaService.GetType().GetEvents(BindingFlags.Static | BindingFlags.Public); - var typedEventHandler = typeof(TypedEventHandler<,>); - foreach (var e in events) + EventInfo[] events = MediaService.GetType().GetEvents(BindingFlags.Static | BindingFlags.Public); + Type typedEventHandler = typeof(TypedEventHandler<,>); + foreach (EventInfo e in events) { - //only continue if this is a TypedEventHandler - if (!e.EventHandlerType.IsGenericType) continue; - var typeDef = e.EventHandlerType.GetGenericTypeDefinition(); - if (typedEventHandler != typeDef) continue; + // only continue if this is a TypedEventHandler + if (!e.EventHandlerType.IsGenericType) + { + continue; + } - //get the event arg type - var eventArgType = e.EventHandlerType.GenericTypeArguments[1]; + Type typeDef = e.EventHandlerType.GetGenericTypeDefinition(); + if (typedEventHandler != typeDef) + { + continue; + } - var found = EventNameExtractor.FindEvent(typeof(MediaService), eventArgType, EventNameExtractor.MatchIngNames); + // get the event arg type + Type eventArgType = e.EventHandlerType.GenericTypeArguments[1]; + + Attempt found = EventNameExtractor.FindEvent(typeof(MediaService), eventArgType, EventNameExtractor.MatchIngNames); if (!found.Success && found.Result.Error == EventNameExtractorError.Ambiguous) { Console.WriteLine($"Ambiguous event, source: {typeof(MediaService)}, args: {eventArgType}"); @@ -77,31 +90,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_Paged_Children_With_Media_Type_Filter() { - var mediaType1 = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType1 = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType1); - var mediaType2 = MediaTypeBuilder.CreateImageMediaType("Image3"); + MediaType mediaType2 = MediaTypeBuilder.CreateImageMediaType("Image3"); MediaTypeService.Save(mediaType2); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var m1 = MediaBuilder.CreateMediaImage(mediaType1, -1); + Media m1 = MediaBuilder.CreateMediaImage(mediaType1, -1); MediaService.Save(m1); - var m2 = MediaBuilder.CreateMediaImage(mediaType2, -1); + Media m2 = MediaBuilder.CreateMediaImage(mediaType2, -1); MediaService.Save(m2); } - long total; - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var result = MediaService.GetPagedChildren(-1, 0, 11, out total, + IEnumerable result = MediaService.GetPagedChildren( + -1, + 0, + 11, + out long total, provider.SqlContext.Query() .Where(x => new[] { mediaType1.Id, mediaType2.Id }.Contains(x.ContentTypeId)), Ordering.By("SortOrder", Direction.Ascending)); Assert.AreEqual(11, result.Count()); Assert.AreEqual(20, total); - result = MediaService.GetPagedChildren(-1, 1, 11, out total, + result = MediaService.GetPagedChildren( + -1, + 1, + 11, + out total, provider.SqlContext.Query() .Where(x => new[] { mediaType1.Id, mediaType2.Id }.Contains(x.ContentTypeId)), Ordering.By("SortOrder", Direction.Ascending)); @@ -114,8 +134,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Media() { // Arrange - var mediaItems = CreateTrashedTestMedia(); - var media = MediaService.GetById(mediaItems.Item3.Id); + Tuple mediaItems = CreateTrashedTestMedia(); + IMedia media = MediaService.GetById(mediaItems.Item3.Id); // Act MediaService.Move(media, mediaItems.Item2.Id); @@ -129,8 +149,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Media_To_RecycleBin() { // Arrange - var mediaItems = CreateTrashedTestMedia(); - var media = MediaService.GetById(mediaItems.Item1.Id); + Tuple mediaItems = CreateTrashedTestMedia(); + IMedia media = MediaService.GetById(mediaItems.Item1.Id); // Act MediaService.MoveToRecycleBin(media); @@ -144,12 +164,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Media_From_RecycleBin() { // Arrange - var mediaItems = CreateTrashedTestMedia(); - var media = MediaService.GetById(mediaItems.Item4.Id); + Tuple mediaItems = CreateTrashedTestMedia(); + IMedia media = MediaService.GetById(mediaItems.Item4.Id); // Act - moving out of recycle bin MediaService.Move(media, mediaItems.Item1.Id); - var mediaChild = MediaService.GetById(mediaItems.Item5.Id); + IMedia mediaChild = MediaService.GetById(mediaItems.Item5.Id); // Assert Assert.That(media.ParentId, Is.EqualTo(mediaItems.Item1.Id)); @@ -162,13 +182,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_Media_With_Empty_Name() { // Arrange - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); MediaTypeService.Save(mediaType); - var media = MediaService.CreateMedia(string.Empty, -1, "video"); + IMedia media = MediaService.CreateMedia(string.Empty, -1, "video"); // Act & Assert Assert.Throws(() => MediaService.Save(media)); } + /* [Test] public void Ensure_Content_Xml_Created() @@ -188,14 +209,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Media_By_Path() { - var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType); - var media = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media = MediaBuilder.CreateMediaImage(mediaType, -1); MediaService.Save(media); - var mediaPath = "/media/test-image.png"; - var resolvedMedia = MediaService.GetMediaByPath(mediaPath); + string mediaPath = "/media/test-image.png"; + IMedia resolvedMedia = MediaService.GetMediaByPath(mediaPath); Assert.IsNotNull(resolvedMedia); Assert.That(resolvedMedia.GetValue(Constants.Conventions.Media.File).ToString() == mediaPath); @@ -204,14 +225,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Media_With_Crop_By_Path() { - var mediaType = MediaTypeBuilder.CreateImageMediaTypeWithCrop("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaTypeWithCrop("Image2"); MediaTypeService.Save(mediaType); - var media = MediaBuilder.CreateMediaImageWithCrop(mediaType, -1); + Media media = MediaBuilder.CreateMediaImageWithCrop(mediaType, -1); MediaService.Save(media); - var mediaPath = "/media/test-image.png"; - var resolvedMedia = MediaService.GetMediaByPath(mediaPath); + string mediaPath = "/media/test-image.png"; + IMedia resolvedMedia = MediaService.GetMediaByPath(mediaPath); Assert.IsNotNull(resolvedMedia); Assert.That(resolvedMedia.GetValue(Constants.Conventions.Media.File).ToString().Contains(mediaPath)); @@ -220,18 +241,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Paged_Children() { - var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media c1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaService.Save(c1); } - var service = MediaService; + IMediaService service = MediaService; - long total; - var entities = service.GetPagedChildren(-1, 0, 6, out total).ToArray(); + IMedia[] entities = service.GetPagedChildren(-1, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = service.GetPagedChildren(-1, 1, 6, out total).ToArray(); @@ -242,37 +262,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Paged_Children_Dont_Get_Descendants() { - var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType); - // only add 9 as we also add a folder with children - for (var i = 0; i < 9; i++) + + // Only add 9 as we also add a folder with children. + for (int i = 0; i < 9; i++) { - var m1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media m1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaService.Save(m1); } - var mediaTypeForFolder = MediaTypeBuilder.CreateImageMediaType("Folder2"); + MediaType mediaTypeForFolder = MediaTypeBuilder.CreateImageMediaType("Folder2"); MediaTypeService.Save(mediaTypeForFolder); - var mediaFolder = MediaBuilder.CreateMediaFolder(mediaTypeForFolder, -1); + Media mediaFolder = MediaBuilder.CreateMediaFolder(mediaTypeForFolder, -1); MediaService.Save(mediaFolder); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var m1 = MediaBuilder.CreateMediaImage(mediaType, mediaFolder.Id); + Media m1 = MediaBuilder.CreateMediaImage(mediaType, mediaFolder.Id); MediaService.Save(m1); } - var service = MediaService; + IMediaService service = MediaService; - long total; - // children in root including the folder - not the descendants in the folder - var entities = service.GetPagedChildren(-1, 0, 6, out total).ToArray(); + // Children in root including the folder - not the descendants in the folder. + IMedia[] entities = service.GetPagedChildren(-1, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = service.GetPagedChildren(-1, 1, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); - // children in folder + // Children in folder. entities = service.GetPagedChildren(mediaFolder.Id, 0, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); @@ -283,27 +303,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private Tuple CreateTrashedTestMedia() { - //Create and Save folder-Media -> 1050 - var folderMediaType = MediaTypeService.Get(1031); - var folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + // Create and Save folder-Media -> 1050 + IMediaType folderMediaType = MediaTypeService.Get(1031); + Media folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); MediaService.Save(folder); - //Create and Save folder-Media -> 1051 - var folder2 = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + // Create and Save folder-Media -> 1051 + Media folder2 = MediaBuilder.CreateMediaFolder(folderMediaType, -1); MediaService.Save(folder2); - //Create and Save image-Media -> 1052 - var imageMediaType = MediaTypeService.Get(1032); - var image = MediaBuilder.CreateMediaImage(imageMediaType, 1050); + // Create and Save image-Media -> 1052 + IMediaType imageMediaType = MediaTypeService.Get(1032); + Media image = MediaBuilder.CreateMediaImage(imageMediaType, 1050); MediaService.Save(image); - //Create and Save folder-Media that is trashed -> 1053 - var folderTrashed = MediaBuilder.CreateMediaFolder(folderMediaType, -21); + // Create and Save folder-Media that is trashed -> 1053 + Media folderTrashed = MediaBuilder.CreateMediaFolder(folderMediaType, -21); folderTrashed.Trashed = true; MediaService.Save(folderTrashed); - //Create and Save image-Media child of folderTrashed -> 1054 - var imageTrashed = MediaBuilder.CreateMediaImage(imageMediaType, folderTrashed.Id); + // Create and Save image-Media child of folderTrashed -> 1054 + Media imageTrashed = MediaBuilder.CreateMediaImage(imageMediaType, folderTrashed.Id); imageTrashed.Trashed = true; MediaService.Save(imageTrashed); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs index 8a38bdc6eb..2a1b5c3101 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -19,27 +22,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MediaTypeServiceTests : UmbracoIntegrationTest { private MediaService MediaService => (MediaService)GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); [Test] public void Get_With_Missing_Guid() { // Arrange - //Act - var result = MediaTypeService.Get(Guid.NewGuid()); + // Act + IMediaType result = MediaTypeService.Get(Guid.NewGuid()); - //Assert + // Assert Assert.IsNull(result); } [Test] public void Empty_Description_Is_Always_Null_After_Saving_Media_Type() { - var mediaType = MediaTypeBuilder.CreateSimpleMediaType("mediaType", "Media Type"); + MediaType mediaType = MediaTypeBuilder.CreateSimpleMediaType("mediaType", "Media Type"); mediaType.Description = null; MediaTypeService.Save(mediaType); - var mediaType2 = MediaTypeBuilder.CreateSimpleMediaType("mediaType2", "Media Type 2"); + MediaType mediaType2 = MediaTypeBuilder.CreateSimpleMediaType("mediaType2", "Media Type 2"); mediaType2.Description = string.Empty; MediaTypeService.Save(mediaType2); @@ -57,17 +61,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMediaType contentType3 = MediaTypeBuilder.CreateSimpleMediaType("test3", "Test3"); MediaTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IMediaType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; var ids = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); + IMediaType contentType = contentTypes[index]; + Media contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); MediaService.Save(contentItem); parentId = contentItem.Id; @@ -75,13 +79,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - //delete the first content type, all other content of different content types should be in the recycle bin + // delete the first content type, all other content of different content types should be in the recycle bin MediaTypeService.Delete(contentTypes[0]); - var found = MediaService.GetByIds(ids); + IEnumerable found = MediaService.GetByIds(ids); Assert.AreEqual(4, found.Count()); - foreach (var content in found) + foreach (IMedia content in found) { Assert.IsTrue(content.Trashed); } @@ -101,17 +105,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMediaType contentType3 = MediaTypeBuilder.CreateSimpleMediaType("test3", "Test3"); MediaTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IMediaType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; var ids = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); + IMediaType contentType = contentTypes[index]; + Media contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); MediaService.Save(contentItem); parentId = contentItem.Id; @@ -119,7 +123,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - foreach (var contentType in contentTypes.Reverse()) + foreach (IMediaType contentType in contentTypes.Reverse()) { MediaTypeService.Delete(contentType); } @@ -132,12 +136,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void MediaServiceOnTrashed(IMediaService sender, MoveEventArgs e) { - foreach (var item in e.MoveInfoCollection) + foreach (MoveEventInfo item in e.MoveInfoCollection) { - //if this item doesn't exist then Fail! - var exists = MediaService.GetById(item.Entity.Id); + // if this item doesn't exist then Fail! + IMedia exists = MediaService.GetById(item.Entity.Id); if (exists == null) + { Assert.Fail("The item doesn't exist"); + } } } @@ -149,7 +155,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MediaTypeService.Save(mediaType); // Act - var sut = mediaType.DeepCloneWithResetIdentities("Image2_2"); + IMediaType sut = mediaType.DeepCloneWithResetIdentities("Image2_2"); Assert.IsNotNull(sut); MediaTypeService.Save(sut); @@ -170,15 +176,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_MediaType_To_New_Parent_By_Performing_Clone() { // Arrange - var parentMediaType1 = MediaTypeBuilder.CreateSimpleMediaType("parent1", "Parent1"); + MediaType parentMediaType1 = MediaTypeBuilder.CreateSimpleMediaType("parent1", "Parent1"); MediaTypeService.Save(parentMediaType1); - var parentMediaType2 = MediaTypeBuilder.CreateSimpleMediaType("parent2", "Parent2", null, true); + MediaType parentMediaType2 = MediaTypeBuilder.CreateSimpleMediaType("parent2", "Parent2", null, true); MediaTypeService.Save(parentMediaType2); var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2") as IMediaType; MediaTypeService.Save(mediaType); // Act - var clone = mediaType.DeepCloneWithResetIdentities("newcategory"); + IMediaType clone = mediaType.DeepCloneWithResetIdentities("newcategory"); Assert.IsNotNull(clone); clone.RemoveContentType("parent1"); clone.AddContentType(parentMediaType2); @@ -188,8 +194,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.That(clone.HasIdentity, Is.True); - var clonedMediaType = MediaTypeService.Get(clone.Id); - var originalMediaType = MediaTypeService.Get(mediaType.Id); + IMediaType clonedMediaType = MediaTypeService.Get(clone.Id); + IMediaType originalMediaType = MediaTypeService.Get(mediaType.Id); Assert.That(clonedMediaType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedMediaType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs index e0119bccb4..5abd76aaf8 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Threading; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -19,10 +23,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services /// /// Used to list out all ambiguous events that will require dispatching with a name /// - [Test, Explicit] + [Test] + [Explicit] public void List_Ambiguous_Events() { - var memberGroup = new MemberGroupBuilder() + MemberGroup memberGroup = new MemberGroupBuilder() .WithName(string.Empty) .Build(); Assert.Throws(() => MemberGroupService.Save(memberGroup)); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs index a22810ff22..5e195aa077 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Threading; +using NPoco; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; @@ -12,6 +16,7 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common; using Umbraco.Tests.Common.Builders; @@ -28,14 +33,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MemberServiceTests : UmbracoIntegrationTest { private IMemberTypeService MemberTypeService => GetRequiredService(); + private IMemberService MemberService => GetRequiredService(); [SetUp] - public void SetupTest() - { + public void SetupTest() => + // TODO: remove this once IPublishedSnapShotService has been implemented with nucache. global::Umbraco.Core.Services.Implement.MemberTypeService.ClearScopeEvents(); - } [Test] public void Can_Update_Member_Property_Values() @@ -64,11 +69,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_By_Username() { - var memberType = MemberTypeService.Get("member"); + IMemberType memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true); MemberService.Save(member); - var member2 = MemberService.GetByUsername(member.Username); + IMember member2 = MemberService.GetByUsername(member.Username); Assert.IsNotNull(member2); Assert.AreEqual(member.Email, member2.Email); @@ -77,8 +82,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Set_Last_Login_Date() { - var now = DateTime.Now; - var memberType = MemberTypeService.Get("member"); + DateTime now = DateTime.Now; + IMemberType memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true) { LastLoginDate = now, @@ -86,10 +91,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }; MemberService.Save(member); - var newDate = now.AddDays(10); + DateTime newDate = now.AddDays(10); MemberService.SetLastLogin(member.Username, newDate); - //re-get + // re-get member = MemberService.GetById(member.Id); Assert.That(member.LastLoginDate, Is.EqualTo(newDate).Within(1).Seconds); @@ -99,7 +104,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Create_Member_With_Properties() { - var memberType = MemberTypeService.Get("member"); + IMemberType memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true); MemberService.Save(member); @@ -111,14 +116,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var publishedSnapshotAccessor = new TestPublishedSnapshotAccessor(); var variationContextAccessor = new TestVariationContextAccessor(); - var pmember = PublishedMember.Create(member, pmemberType, false, publishedSnapshotAccessor, variationContextAccessor, GetRequiredService()); + IPublishedContent pmember = PublishedMember.Create(member, pmemberType, false, publishedSnapshotAccessor, variationContextAccessor, GetRequiredService()); // contains the umbracoMember... properties created when installing, on the member type // contains the other properties, that PublishedContentType adds (BuiltinMemberProperties) // // TODO: see TODO in PublishedContentType, this list contains duplicates - - var aliases = new[] + string[] aliases = new[] { Constants.Conventions.Member.Comments, Constants.Conventions.Member.FailedPasswordAttempts, @@ -142,7 +146,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(properties.Select(x => x.Alias).ContainsAll(aliases)); - var email = properties[aliases.IndexOf(nameof(IMember.Email))]; + IPublishedProperty email = properties[aliases.IndexOf(nameof(IMember.Email))]; Assert.AreEqual("xemail", email.GetSourceValue()); } @@ -155,7 +159,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.Save(member); Assert.AreNotEqual(0, member.Id); - var foundMember = MemberService.GetById(member.Id); + IMember foundMember = MemberService.GetById(member.Id); Assert.IsNotNull(foundMember); Assert.AreEqual("test@test.com", foundMember.Email); } @@ -169,7 +173,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.Save(member); Assert.AreNotEqual(0, member.Id); - var foundMember = MemberService.GetById(member.Id); + IMember foundMember = MemberService.GetById(member.Id); Assert.IsNotNull(foundMember); Assert.AreEqual("test@test.marketing", foundMember.Email); } @@ -179,7 +183,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { MemberService.AddRole("MyTestRole"); - var found = MemberService.GetAllRoles(); + IEnumerable found = MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); @@ -191,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole"); MemberService.AddRole("MyTestRole"); - var found = MemberService.GetAllRoles(); + IEnumerable found = MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); @@ -204,10 +208,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole2"); MemberService.AddRole("MyTestRole3"); - var found = MemberService.GetAllRoles(); + IEnumerable found = MemberService.GetAllRoles(); Assert.AreEqual(3, found.Count()); } + [Test] public void Can_Get_All_Roles_IDs() { @@ -215,10 +220,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole2"); MemberService.AddRole("MyTestRole3"); - var found = MemberService.GetAllRolesIds(); + IEnumerable found = MemberService.GetAllRolesIds(); Assert.AreEqual(3, found.Count()); } + [Test] public void Can_Get_All_Roles_By_Member_Id() { @@ -232,11 +238,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole3"); MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - var memberRoles = MemberService.GetAllRoles(member.Id); + IEnumerable memberRoles = MemberService.GetAllRoles(member.Id); Assert.AreEqual(2, memberRoles.Count()); - } + [Test] public void Can_Get_All_Roles_Ids_By_Member_Id() { @@ -250,11 +256,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole3"); MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - var memberRoles = MemberService.GetAllRolesIds(member.Id); + IEnumerable memberRoles = MemberService.GetAllRolesIds(member.Id); Assert.AreEqual(2, memberRoles.Count()); - } + [Test] public void Can_Get_All_Roles_By_Member_Username() { @@ -262,7 +268,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberTypeService.Save(memberType); IMember member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); MemberService.Save(member); - //need to test with '@' symbol in the lookup + + // need to test with '@' symbol in the lookup IMember member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); MemberService.Save(member2); @@ -271,10 +278,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole3"); MemberService.AssignRoles(new[] { member.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - var memberRoles = MemberService.GetAllRoles("test"); + IEnumerable memberRoles = MemberService.GetAllRoles("test"); Assert.AreEqual(2, memberRoles.Count()); - var memberRoles2 = MemberService.GetAllRoles("test2@test.com"); + IEnumerable memberRoles2 = MemberService.GetAllRoles("test2@test.com"); Assert.AreEqual(2, memberRoles2.Count()); } @@ -285,7 +292,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.DeleteRole("MyTestRole1", false); - var memberRoles = MemberService.GetAllRoles(); + IEnumerable memberRoles = MemberService.GetAllRoles(); Assert.AreEqual(0, memberRoles.Count()); } @@ -309,7 +316,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { MemberService.AddRole("MyTestRole1"); int roleId; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { roleId = scope.Database.ExecuteScalar("SELECT id from umbracoNode where [text] = 'MyTestRole1'"); scope.Complete(); @@ -317,19 +324,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.Insert(new Member2MemberGroupDto { MemberGroup = roleId, Member = member1.Id }); scope.Database.Insert(new Member2MemberGroupDto { MemberGroup = roleId, Member = member2.Id }); scope.Complete(); } - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -342,7 +349,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Act & Assert Assert.Throws(() => MemberService.Save(member)); - } [TestCase("MyTestRole1", "test1", StringPropertyMatchType.StartsWith, 1)] @@ -355,16 +361,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); - var member3 = MemberBuilder.CreateSimpleMember(memberType, "test3", "test3@test.com", "pass", "test3"); + Member member3 = MemberBuilder.CreateSimpleMember(memberType, "test3", "test3@test.com", "pass", "test3"); MemberService.Save(member3); MemberService.AssignRoles(new[] { member1.Id, member2.Id, member3.Id }, new[] { roleName1 }); - var result = MemberService.FindMembersInRole(roleName1, usernameToMatch, matchType); + IEnumerable result = MemberService.FindMembersInRole(roleName1, usernameToMatch, matchType); Assert.AreEqual(resultCount, result.Count()); } @@ -375,9 +381,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); // temp make sure they exist @@ -386,7 +392,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -398,9 +404,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); // temp make sure they exist @@ -409,7 +415,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "mytestrole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -421,14 +427,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -440,14 +446,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1@test.com"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1@test.com"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -457,15 +463,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); - //implicitly create the role + // implicitly create the role MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -475,17 +481,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - MemberService.DissociateRoles(new[] {member1.Id }, new[] {"MyTestRole1"}); + MemberService.DissociateRoles(new[] { member1.Id }, new[] { "MyTestRole1" }); MemberService.DissociateRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole2" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); @@ -496,9 +502,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1", "MyTestRole2" }); @@ -506,7 +512,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.DissociateRoles(new[] { member1.Username }, new[] { "MyTestRole1" }); MemberService.DissociateRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole2" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); @@ -521,7 +527,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.Save(member); MemberService.Delete(member); - var deleted = MemberService.GetById(member.Id); + IMember deleted = MemberService.GetById(member.Id); // Assert Assert.That(deleted, Is.Null); @@ -562,17 +568,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMember member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); MemberService.Save(member); - var resolved = MemberService.GetByEmail(member.Email); + IMember resolved = MemberService.GetByEmail(member.Email); - //NOTE: This will not trigger a property isDirty because this is not based on a 'Property', it is + // NOTE: This will not trigger a property isDirty because this is not based on a 'Property', it is // just a c# property of the Member object resolved.Email = "changed@test.com"; - //NOTE: this WILL trigger a property isDirty because setting this c# property actually sets a value of + // NOTE: this WILL trigger a property isDirty because setting this c# property actually sets a value of // the underlying 'Property' resolved.FailedPasswordAttempts = 1234; - var dirtyMember = (ICanBeDirty) resolved; + var dirtyMember = (ICanBeDirty)resolved; var dirtyProperties = resolved.Properties.Where(x => x.IsDirty()).ToList(); Assert.IsTrue(dirtyMember.IsDirty()); Assert.AreEqual(1, dirtyProperties.Count); @@ -598,7 +604,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMember member = MemberBuilder.CreateSimpleMember(memberType, "Test Real Name", "test@test.com", "pass", "testUsername"); MemberService.Save(member); - Assert.AreEqual("Test Real Name", member.Name); } @@ -631,11 +636,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - long totalRecs; - var found = MemberService.GetAll(0, 2, out totalRecs); + IEnumerable found = MemberService.GetAll(0, 2, out long totalRecs); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); @@ -648,11 +652,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - long totalRecs; - var found = MemberService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, true, null, "Member No-"); + IEnumerable found = MemberService.GetAll(0, 2, out long totalRecs, "username", Direction.Ascending, true, null, "Member No-"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); @@ -671,14 +674,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "Bob", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "Bob", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindMembersByDisplayName("B", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); + IEnumerable found = MemberService.FindMembersByDisplayName("B", 0, 100, out long totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(1, found.Count()); } @@ -688,14 +690,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //don't find this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello","hello"); + + // don't find this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); + IEnumerable found = MemberService.FindByEmail("tes", 0, 100, out long totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } @@ -705,14 +707,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("test.com", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); + IEnumerable found = MemberService.FindByEmail("test.com", 0, 100, out long totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(11, found.Count()); } @@ -722,14 +724,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); + IEnumerable found = MemberService.FindByEmail("test", 0, 100, out long totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } @@ -739,14 +741,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("hello@test.com", 0, 100, out totalRecs, StringPropertyMatchType.Exact); + IEnumerable found = MemberService.FindByEmail("hello@test.com", 0, 100, out long totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } @@ -756,14 +758,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //don't find this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // don't find this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); + IEnumerable found = MemberService.FindByUsername("tes", 0, 100, out long totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } @@ -773,14 +775,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("llo", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); + IEnumerable found = MemberService.FindByUsername("llo", 0, 100, out long totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); } @@ -790,14 +792,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hellotest"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hellotest"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); + IEnumerable found = MemberService.FindByUsername("test", 0, 100, out long totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } @@ -807,14 +809,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("hello", 0, 100, out totalRecs, StringPropertyMatchType.Exact); + IEnumerable found = MemberService.FindByUsername("hello", 0, 100, out long totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } @@ -824,12 +826,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", "hello member", StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); @@ -840,12 +842,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", " member", StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); @@ -856,12 +858,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", "Member No", StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); @@ -872,13 +874,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("title", "title of mine"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", "mine", StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); @@ -888,21 +890,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Exact() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 2); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 2, ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); @@ -912,21 +918,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Greater_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); @@ -936,21 +946,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Greater_Than_Equal_To() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); @@ -960,21 +974,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Less_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.DateTime, ValueStorageType.Date, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.DateTime, + ValueStorageType.Date, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); @@ -984,21 +1002,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Less_Than_Or_Equal() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); @@ -1008,21 +1030,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Exact() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 2, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 2, 0), ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); @@ -1032,21 +1058,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Greater_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); @@ -1056,21 +1086,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Greater_Than_Equal_To() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); @@ -1080,21 +1114,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Less_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); @@ -1104,21 +1142,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Less_Than_Or_Equal() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); @@ -1129,12 +1171,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetCount(MemberCountType.All); + int found = MemberService.GetCount(MemberCountType.All); Assert.AreEqual(11, found); } @@ -1144,14 +1186,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsLockedOut = i % 2 == 0); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsLockedOut = i % 2 == 0); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsLockedOut, true); MemberService.Save(customMember); - var found = MemberService.GetCount(MemberCountType.LockedOut); + int found = MemberService.GetCount(MemberCountType.LockedOut); Assert.AreEqual(6, found); } @@ -1161,14 +1203,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsApproved = i % 2 == 0); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsApproved = i % 2 == 0); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsApproved, false); MemberService.Save(customMember); - var found = MemberService.GetCount(MemberCountType.Approved); + int found = MemberService.GetCount(MemberCountType.Approved); Assert.AreEqual(5, found); } @@ -1182,12 +1224,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberTypeService.Save(memberType); Assert.IsFalse(memberType.PropertyTypes.Any(x => x.Alias == Constants.Conventions.Member.Comments)); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); - //this should not throw an exception + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // this should not throw an exception customMember.Comments = "hello world"; MemberService.Save(customMember); - var found = MemberService.GetById(customMember.Id); + IMember found = MemberService.GetById(customMember.Id); Assert.IsTrue(found.Comments.IsNullOrWhiteSpace()); } @@ -1201,19 +1244,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "test", "test"); - var date = DateTime.Now; + Member member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "test", "test"); + DateTime date = DateTime.Now; member.LastLoginDate = DateTime.Now; MemberService.Save(member); - var result = MemberService.GetById(member.Id); + IMember result = MemberService.GetById(member.Id); Assert.AreEqual( date.TruncateTo(DateTimeExtensions.DateTruncate.Second), result.LastLoginDate.TruncateTo(DateTimeExtensions.DateTruncate.Second)); - //now ensure the col is correct - var sqlContext = GetRequiredService(); - var sql = sqlContext.Sql().Select() + // now ensure the col is correct + ISqlContext sqlContext = GetRequiredService(); + Sql sql = sqlContext.Sql().Select() .From() .InnerJoin().On(dto => dto.PropertyTypeId, dto => dto.Id) .InnerJoin().On((left, right) => left.VersionId == right.Id) @@ -1221,7 +1264,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services .Where(dto => dto.Alias == Constants.Conventions.Member.LastLoginDate); List colResult; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { colResult = scope.Database.Fetch(sql); scope.Complete(); @@ -1240,10 +1283,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetById(customMember.Id); + IMember found = MemberService.GetById(customMember.Id); Assert.IsTrue(found.IsApproved); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.cs index 5c61501a10..6e25d7f405 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; @@ -17,6 +21,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MemberTypeServiceTests : UmbracoIntegrationTest { private IMemberService MemberService => GetRequiredService(); + private IMemberTypeService MemberTypeService => GetRequiredService(); [SetUp] @@ -31,9 +36,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes) + foreach (IPropertyType p in memberType.PropertyTypes) { Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); } @@ -44,15 +50,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var prop = memberType.PropertyTypes.First().Alias; + string prop = memberType.PropertyTypes.First().Alias; memberType.SetMemberCanEditProperty(prop, true); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) + foreach (IPropertyType p in memberType.PropertyTypes.Where(x => x.Alias != prop)) { Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); } + Assert.IsTrue(memberType.MemberCanEditProperty(prop)); } @@ -61,9 +69,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes) + foreach (IPropertyType p in memberType.PropertyTypes) { Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); } @@ -74,15 +83,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var prop = memberType.PropertyTypes.First().Alias; + string prop = memberType.PropertyTypes.First().Alias; memberType.SetMemberCanViewProperty(prop, true); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) + foreach (IPropertyType p in memberType.PropertyTypes.Where(x => x.Alias != prop)) { Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); } + Assert.IsTrue(memberType.MemberCanViewProperty(prop)); } @@ -93,14 +104,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberTypeService.Save(memberType); IMember member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); MemberService.Save(member); - var initProps = member.Properties.Count; + int initProps = member.Properties.Count; - //remove a property (NOT ONE OF THE DEFAULTS) - var standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + // remove a property (NOT ONE OF THE DEFAULTS) + Dictionary standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); memberType.RemovePropertyType(memberType.PropertyTypes.First(x => standardProps.ContainsKey(x.Alias) == false).Alias); MemberTypeService.Save(memberType); - //re-load it from the db + // re-load it from the db member = MemberService.GetById(member.Id); Assert.AreEqual(initProps - 1, member.Properties.Count); @@ -119,12 +130,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Empty_Description_Is_Always_Null_After_Saving_Member_Type() { - var service = MemberTypeService; - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + IMemberTypeService service = MemberTypeService; + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); memberType.Description = null; service.Save(memberType); - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType("memberType2", "Member Type 2"); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType("memberType2", "Member Type 2"); memberType2.Description = string.Empty; service.Save(memberType2); @@ -132,9 +143,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsNull(memberType2.Description); } - //[Test] - //public void Can_Save_MemberType_Structure_And_Create_A_Member_Based_On_It() - //{ + // [Test] + // public void Can_Save_MemberType_Structure_And_Create_A_Member_Based_On_It() + // { // // Arrange // var cs = MemberService; // var cts = MemberTypeService; @@ -148,7 +159,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // /*,"Navigation"*/); // cts.Save(ctBase); - // var ctHomePage = new MemberType(ctBase) + // var ctHomePage = new MemberType(ctBase) // { // Name = "Home Page", // Alias = "HomePage", @@ -160,19 +171,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // /*,"Navigation"*/); // cts.Save(ctHomePage); - // // Act + // // Act // var homeDoc = cs.CreateMember("Test", "test@test.com", "test", "HomePage"); - // // Assert + // // Assert // Assert.That(ctBase.HasIdentity, Is.True); // Assert.That(ctHomePage.HasIdentity, Is.True); // Assert.That(homeDoc.HasIdentity, Is.True); // Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); - //} + // } - //[Test] - //public void Can_Create_And_Save_MemberType_Composition() - //{ + // [Test] + // public void Can_Create_And_Save_MemberType_Composition() + // { // /* // * Global // * - Components @@ -182,23 +193,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // var global = MemberTypeBuilder.CreateSimpleContentType("global", "Global"); // service.Save(global); - // var components = MemberTypeBuilder.CreateSimpleContentType("components", "Components", global); + // var components = MemberTypeBuilder.CreateSimpleContentType("components", "Components", global); // service.Save(components); - // var component = MemberTypeBuilder.CreateSimpleContentType("component", "Component", components); + // var component = MemberTypeBuilder.CreateSimpleContentType("component", "Component", components); // service.Save(component); - // var category = MemberTypeBuilder.CreateSimpleContentType("category", "Category", global); + // var category = MemberTypeBuilder.CreateSimpleContentType("category", "Category", global); // service.Save(category); - // var success = category.AddContentType(component); + // var success = category.AddContentType(component); - // Assert.That(success, Is.False); - //} + // Assert.That(success, Is.False); + // } - //[Test] - //public void Can_Remove_ContentType_Composition_From_ContentType() - //{ + // [Test] + // public void Can_Remove_ContentType_Composition_From_ContentType() + // { // //Test for U4-2234 // var cts = ContentTypeService; // //Arrange @@ -211,11 +222,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // var homepage = CreateHomepage(site); // cts.Save(homepage); - // //Add banner to homepage + // //Add banner to homepage // var added = homepage.AddContentType(banner); // cts.Save(homepage); - // //Assert composition + // //Assert composition // var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); // var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); // Assert.That(added, Is.True); @@ -223,42 +234,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert.That(bannerPropertyExists, Is.True); // Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); - // //Remove banner from homepage + // //Remove banner from homepage // var removed = homepage.RemoveContentType(banner.Alias); // cts.Save(homepage); - // //Assert composition + // //Assert composition // var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); // var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); // Assert.That(removed, Is.True); // Assert.That(bannerStillExists, Is.False); // Assert.That(bannerPropertyStillExists, Is.False); // Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); - //} + // } - //[Test] - //public void Can_Copy_ContentType_By_Performing_Clone() - //{ + // [Test] + // public void Can_Copy_ContentType_By_Performing_Clone() + // { // // Arrange // var service = ContentTypeService; // var metaContentType = MemberTypeBuilder.CreateMetaContentType(); // service.Save(metaContentType); - // var simpleContentType = MemberTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType); + // var simpleContentType = MemberTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType); // service.Save(simpleContentType); // var categoryId = simpleContentType.Id; - // // Act + // // Act // var sut = simpleContentType.Clone("newcategory"); // service.Save(sut); - // // Assert + // // Assert // Assert.That(sut.HasIdentity, Is.True); - // var contentType = service.GetContentType(sut.Id); + // var contentType = service.GetContentType(sut.Id); // var category = service.GetContentType(categoryId); - // Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); + // Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); // Assert.AreEqual(contentType.ParentId, category.ParentId); // Assert.AreEqual(contentType.Level, category.Level); // Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); @@ -269,10 +280,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); // Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); - //} + // } - //private ContentType CreateComponent() - //{ + // private ContentType CreateComponent() + // { // var component = new ContentType(-1) // { // Alias = "component", @@ -285,15 +296,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var contentCollection = new PropertyTypeCollection(); + // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "componentGroup", Name = "Component Group", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); - // return component; - //} + // return component; + // } - //private ContentType CreateBannerComponent(ContentType parent) - //{ + // private ContentType CreateBannerComponent(ContentType parent) + // { // var banner = new ContentType(parent) // { // Alias = "banner", @@ -306,7 +317,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var propertyType = new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) + // var propertyType = new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) // { // Alias = "bannerName", // Name = "Banner Name", @@ -318,10 +329,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // }; // banner.AddPropertyType(propertyType, "Component"); // return banner; - //} + // } - //private ContentType CreateSite() - //{ + // private ContentType CreateSite() + // { // var site = new ContentType(-1) // { // Alias = "site", @@ -334,15 +345,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var contentCollection = new PropertyTypeCollection(); + // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "hostname", Name = "Hostname", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); - // return site; - //} + // return site; + // } - //private ContentType CreateHomepage(ContentType parent) - //{ + // private ContentType CreateHomepage(ContentType parent) + // { // var contentType = new ContentType(parent) // { // Alias = "homepage", @@ -355,36 +366,36 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var contentCollection = new PropertyTypeCollection(); + // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", HelpText = "", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); - // contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); + // contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); - // return contentType; - //} + // return contentType; + // } - //private IEnumerable CreateContentTypeHierarchy() - //{ + // private IEnumerable CreateContentTypeHierarchy() + // { // //create the master type // var masterContentType = MemberTypeBuilder.CreateSimpleContentType("masterContentType", "MasterContentType"); // masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); // ContentTypeService.Save(masterContentType); - // //add the one we just created + // //add the one we just created // var list = new List { masterContentType }; - // for (var i = 0; i < 10; i++) + // for (var i = 0; i < 10; i++) // { // var contentType = MemberTypeBuilder.CreateSimpleContentType("childType" + i, "ChildType" + i, // //make the last entry in the list, this one's parent // list.Last()); - // list.Add(contentType); + // list.Add(contentType); // } - // return list; - //} + // return list; + // } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs index 9b46a37245..b4b78365c6 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using System.Threading; using NUnit.Framework; +using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; @@ -16,8 +20,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class PublicAccessServiceTests : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IPublicAccessService PublicAccessService => GetRequiredService(); private Content _content; @@ -25,10 +32,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [SetUp] public void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! - var ct = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", defaultTemplateId: template.Id); + ContentType ct = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", defaultTemplateId: template.Id); ContentTypeService.Save(ct); _content = ContentBuilder.CreateSimpleContent(ct, "Test", -1); @@ -39,17 +46,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Add_New_Entry() { // Arrange - - // Act - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { RuleType = "TestType", RuleValue = "TestVal" }, - }); - var result = PublicAccessService.Save(entry); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); + + // Act + Attempt result = PublicAccessService.Save(entry); // Assert Assert.IsTrue(result.Success); @@ -65,19 +73,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Add_Rule() { // Arrange - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { RuleType = "TestType", RuleValue = "TestVal" }, - }); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); PublicAccessService.Save(entry); // Act - var updated = PublicAccessService.AddRule(_content, "TestType2", "AnotherVal"); - //re-get + Attempt> updated = PublicAccessService.AddRule(_content, "TestType2", "AnotherVal"); + + // re-get entry = PublicAccessService.GetEntryForContent(_content); // Assert @@ -90,21 +100,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Add_Multiple_Value_For_Same_Rule_Type() { // Arrange - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { RuleType = "TestType", RuleValue = "TestVal" }, - }); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); PublicAccessService.Save(entry); // Act - var updated1 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal1"); - var updated2 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal2"); + Attempt> updated1 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal1"); + Attempt> updated2 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal2"); - //re-get + // re-get entry = PublicAccessService.GetEntryForContent(_content); // Assert @@ -119,7 +130,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Remove_Rule() { // Arrange - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { @@ -131,12 +142,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services RuleType = "TestType", RuleValue = "TestValue2" }, - }); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); PublicAccessService.Save(entry); // Act - var removed = PublicAccessService.RemoveRule(_content, "TestType", "TestValue1"); - //re-get + Attempt removed = PublicAccessService.RemoveRule(_content, "TestType", "TestValue1"); + + // re-get entry = PublicAccessService.GetEntryForContent(_content); // Assert diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs index 89cde051e3..72a5eb4302 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using System.Threading; using Microsoft.Extensions.Logging; using Moq; @@ -54,7 +57,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - [Test] public void Can_Get_Most_Recent_RedirectUrl() { diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs index 3196b54201..1965c737a5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -18,49 +21,57 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class RelationServiceTests : UmbracoIntegrationTest { private IContentTypeService ContentTypeService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IRelationService RelationService => GetRequiredService(); [Test] public void Get_Paged_Relations_By_Relation_Type() { - //Create content + // Create content var createdContent = new List(); - var contentType = ContentTypeBuilder.CreateBasicContentType("blah"); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType("blah"); ContentTypeService.Save(contentType); for (int i = 0; i < 3; i++) { - var c1 = ContentBuilder.CreateBasicContent(contentType); + Content c1 = ContentBuilder.CreateBasicContent(contentType); ContentService.Save(c1); createdContent.Add(c1); } - //Create media + // Create media var createdMedia = new List(); - var imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); + MediaType imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); MediaTypeService.Save(imageType); for (int i = 0; i < 3; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageType, -1); + Media c1 = MediaBuilder.CreateMediaImage(imageType, -1); MediaService.Save(c1); createdMedia.Add(c1); } - var relType = RelationService.GetRelationTypeByAlias(Constants.Conventions.RelationTypes.RelatedMediaAlias); + IRelationType relType = RelationService.GetRelationTypeByAlias(Constants.Conventions.RelationTypes.RelatedMediaAlias); // Relate content to media - foreach (var content in createdContent) - foreach (var media in createdMedia) + foreach (IContent content in createdContent) + { + foreach (IMedia media in createdMedia) + { RelationService.Relate(content.Id, media.Id, relType); + } + } - var paged = RelationService.GetPagedByRelationTypeId(relType.Id, 0, 4, out var totalRecs).ToList(); + var paged = RelationService.GetPagedByRelationTypeId(relType.Id, 0, 4, out long totalRecs).ToList(); Assert.AreEqual(9, totalRecs); Assert.AreEqual(4, paged.Count); - //next page + // next page paged.AddRange(RelationService.GetPagedByRelationTypeId(relType.Id, 1, 4, out totalRecs)); Assert.AreEqual(9, totalRecs); @@ -73,27 +84,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Return_List_Of_Content_Items_Where_Media_Item_Referenced() { - var mt = MediaTypeBuilder.CreateSimpleMediaType("testMediaType", "Test Media Type"); + MediaType mt = MediaTypeBuilder.CreateSimpleMediaType("testMediaType", "Test Media Type"); MediaTypeService.Save(mt); - var m1 = MediaBuilder.CreateSimpleMedia(mt, "hello 1", -1); + Media m1 = MediaBuilder.CreateSimpleMedia(mt, "hello 1", -1); MediaService.Save(m1); - var ct = ContentTypeBuilder.CreateTextPageContentType("richTextTest"); + ContentType ct = ContentTypeBuilder.CreateTextPageContentType("richTextTest"); ct.AllowedTemplates = Enumerable.Empty(); ContentTypeService.Save(ct); - void createContentWithMediaRefs() + void CreateContentWithMediaRefs() { - var content = ContentBuilder.CreateTextpageContent(ct, "my content 2", -1); - //'bodyText' is a property with a RTE property editor which we knows automatically tracks relations + Content content = ContentBuilder.CreateTextpageContent(ct, "my content 2", -1); + + // 'bodyText' is a property with a RTE property editor which we knows automatically tracks relations content.Properties["bodyText"].SetValue(@"

"); ContentService.Save(content); } - for (var i = 0; i < 6; i++) - createContentWithMediaRefs(); //create 6 content items referencing the same media + for (int i = 0; i < 6; i++) + { + CreateContentWithMediaRefs(); // create 6 content items referencing the same media + } var relations = RelationService.GetByChildId(m1.Id, Constants.Conventions.RelationTypes.RelatedMediaAlias).ToList(); Assert.AreEqual(6, relations.Count); @@ -105,12 +119,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Create_RelationType_Without_Name() { - var rs = RelationService; + IRelationService rs = RelationService; IRelationType rt = new RelationType("Test", "repeatedEventOccurence", false, Constants.ObjectTypes.Document, Constants.ObjectTypes.Media); Assert.DoesNotThrow(() => rs.Save(rt)); - //re-get + // re-get rt = RelationService.GetRelationTypeById(rt.Id); Assert.AreEqual("Test", rt.Name); @@ -123,12 +137,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Relation_Type_Without_Object_Types() { - var rs = RelationService; + IRelationService rs = RelationService; IRelationType rt = new RelationType("repeatedEventOccurence", "repeatedEventOccurence", false, null, null); Assert.DoesNotThrow(() => rs.Save(rt)); - //re-get + // re-get rt = RelationService.GetRelationTypeById(rt.Id); Assert.IsNull(rt.ChildObjectType); @@ -138,7 +152,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Relation_Returns_Parent_Child_Object_Types_When_Creating() { - var r = CreateAndSaveRelation("Test", "test"); + IRelation r = CreateAndSaveRelation("Test", "test"); Assert.AreEqual(Constants.ObjectTypes.Document, r.ParentObjectType); Assert.AreEqual(Constants.ObjectTypes.Media, r.ChildObjectType); @@ -147,7 +161,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Relation_Returns_Parent_Child_Object_Types_When_Getting() { - var r = CreateAndSaveRelation("Test", "test"); + IRelation r = CreateAndSaveRelation("Test", "test"); // re-get r = RelationService.GetById(r.Id); @@ -159,9 +173,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Insert_Bulk_Relations() { - var rs = RelationService; + IRelationService rs = RelationService; - var newRelations = CreateRelations(10); + IEnumerable newRelations = CreateRelations(10); Assert.IsTrue(newRelations.All(x => !x.HasIdentity)); @@ -173,43 +187,45 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Update_Bulk_Relations() { - var rs = RelationService; + IRelationService rs = RelationService; - var date = DateTime.Now.AddDays(-10); - var newRelations = CreateRelations(10); - foreach (var r in newRelations) + DateTime date = DateTime.Now.AddDays(-10); + IEnumerable newRelations = CreateRelations(10); + foreach (IRelation r in newRelations) { r.CreateDate = date; r.UpdateDate = date; } - //insert + // insert RelationService.Save(newRelations); Assert.IsTrue(newRelations.All(x => x.UpdateDate == date)); - var newDate = DateTime.Now.AddDays(-5); - foreach (var r in newRelations) + DateTime newDate = DateTime.Now.AddDays(-5); + foreach (IRelation r in newRelations) + { r.UpdateDate = newDate; + } - //update + // update RelationService.Save(newRelations); Assert.IsTrue(newRelations.All(x => x.UpdateDate == newDate)); } private IRelation CreateAndSaveRelation(string name, string alias) { - var rs = RelationService; + IRelationService rs = RelationService; var rt = new RelationType(name, alias, false, null, null); rs.Save(rt); - var ct = ContentTypeBuilder.CreateBasicContentType(); + ContentType ct = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(ct); - var mt = MediaTypeBuilder.CreateImageMediaType("img"); + MediaType mt = MediaTypeBuilder.CreateImageMediaType("img"); MediaTypeService.Save(mt); - var c1 = ContentBuilder.CreateBasicContent(ct); - var c2 = MediaBuilder.CreateMediaImage(mt, -1); + Content c1 = ContentBuilder.CreateBasicContent(ct); + Media c2 = MediaBuilder.CreateMediaImage(mt, -1); ContentService.Save(c1); MediaService.Save(c2); @@ -226,21 +242,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services /// private IEnumerable CreateRelations(int count) { - var rs = RelationService; - var rtName = Guid.NewGuid().ToString(); + IRelationService rs = RelationService; + string rtName = Guid.NewGuid().ToString(); var rt = new RelationType(rtName, rtName, false, null, null); rs.Save(rt); - var ct = ContentTypeBuilder.CreateBasicContentType(); + ContentType ct = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(ct); - var mt = MediaTypeBuilder.CreateImageMediaType("img"); + MediaType mt = MediaTypeBuilder.CreateImageMediaType("img"); MediaTypeService.Save(mt); return Enumerable.Range(1, count).Select(index => { - var c1 = ContentBuilder.CreateBasicContent(ct); - var c2 = MediaBuilder.CreateMediaImage(mt, -1); + Content c1 = ContentBuilder.CreateBasicContent(ct); + Media c2 = MediaBuilder.CreateMediaImage(mt, -1); ContentService.Save(c1); MediaService.Save(c2); @@ -248,6 +264,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }).ToList(); } - //TODO: Create a relation for entities of the wrong Entity Type (GUID) based on the Relation Type's defined parent/child object types + // TODO: Create a relation for entities of the wrong Entity Type (GUID) based on the Relation Type's defined parent/child object types } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs index c48f56e9a7..3c3455fabd 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using System.Threading; using Newtonsoft.Json; using NUnit.Framework; @@ -15,8 +18,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { /// /// Tests covering methods in the TagService class. - /// This is more of an integration test as it involves multiple layers - /// as well as configuration. + /// Involves multiple layers as well as configuration. /// [TestFixture] [Apartment(ApartmentState.STA)] @@ -24,18 +26,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class TagServiceTests : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private ITagService TagService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IJsonSerializer Serializer => GetRequiredService(); + private PropertyEditorCollection PropertyEditorCollection => GetRequiredService(); + private IContentType _contentType; [SetUp] public void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! _contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", defaultTemplateId: template.Id); @@ -56,7 +65,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // change content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "elephant" }, true); - content1.RemoveTags(PropertyEditorCollection, DataTypeService, Serializer,"tags", new[] { "cow" }); + content1.RemoveTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow" }); ContentService.SaveAndPublish(content1); // more changes @@ -67,14 +76,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // get it back content1 = ContentService.GetById(content1.Id); - var tagsValue = content1.GetValue("tags").ToString(); - var tagsValues = JsonConvert.DeserializeObject(tagsValue); + string tagsValue = content1.GetValue("tags").ToString(); + string[] tagsValues = JsonConvert.DeserializeObject(tagsValue); Assert.AreEqual(3, tagsValues.Length); Assert.Contains("pig", tagsValues); Assert.Contains("goat", tagsValues); Assert.Contains("elephant", tagsValues); - var tags = TagService.GetTagsForProperty(content1.Id, "tags").ToArray(); + ITag[] tags = TagService.GetTagsForProperty(content1.Id, "tags").ToArray(); Assert.IsTrue(tags.All(x => x.Group == "default")); tagsValues = tags.Select(x => x.Text).ToArray(); @@ -87,15 +96,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagList_Contains_NodeCount() { - var content1 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow", "pig", "goat" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow", "pig" }); ContentService.SaveAndPublish(content2); - var content3 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 3", -1); + Content content3 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 3", -1); content3.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow" }); ContentService.SaveAndPublish(content3); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs index 9600d62051..f727963d84 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Diagnostics; @@ -36,7 +39,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ThreadSafetyServiceTest : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); [SetUp] @@ -45,12 +50,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services CreateTestData(); } - private const int MaxThreadCount = 20; private void Save(ContentService service, IContent content) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.Execute("SET LOCK_TIMEOUT 60000"); service.Save(content); @@ -60,7 +64,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void Save(MediaService service, IMedia media) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.Execute("SET LOCK_TIMEOUT 60000"); service.Save(media); @@ -75,8 +79,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // comment out to trace locks return done; - //new Thread(() => - //{ + // new Thread(() => + // { // using (var scope = ScopeProvider.CreateScope()) // while (done.IsSet == false) // { @@ -89,17 +93,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // } // Thread.Sleep(50); // } - //}).Start(); - //return done; + // }).Start(); + // return done; } [Test] public void Ensure_All_Threads_Execute_Successfully_Content_Service() { if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null) + { Assert.Ignore("Do not run on VSTS."); + } - var log = GetRequiredService>(); + ILogger log = GetRequiredService>(); // the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton var contentService = (ContentService)ContentService; @@ -109,9 +115,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services log.LogInformation("Starting..."); - var done = TraceLocks(); + ManualResetEventSlim done = TraceLocks(); - for (var i = 0; i < MaxThreadCount; i++) + for (int i = 0; i < MaxThreadCount; i++) { var t = new Thread(() => { @@ -119,23 +125,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { log.LogInformation("[{0}] Running...", Thread.CurrentThread.ManagedThreadId); - var name1 = "test-" + Guid.NewGuid(); - var content1 = contentService.Create(name1, -1, "umbTextpage"); + string name1 = "test-" + Guid.NewGuid(); + IContent content1 = contentService.Create(name1, -1, "umbTextpage"); log.LogInformation("[{0}] Saving content #1.", Thread.CurrentThread.ManagedThreadId); Save(contentService, content1); - Thread.Sleep(100); //quick pause for maximum overlap! + Thread.Sleep(100); // quick pause for maximum overlap! - var name2 = "test-" + Guid.NewGuid(); - var content2 = contentService.Create(name2, -1, "umbTextpage"); + string name2 = "test-" + Guid.NewGuid(); + IContent content2 = contentService.Create(name2, -1, "umbTextpage"); log.LogInformation("[{0}] Saving content #2.", Thread.CurrentThread.ManagedThreadId); Save(contentService, content2); } catch (Exception e) { - lock (exceptions) { exceptions.Add(e); } + lock (exceptions) + { + exceptions.Add(e); + } } }); threads.Add(t); @@ -154,8 +163,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services log.LogInformation("Checking exceptions"); if (exceptions.Count == 0) { - //now look up all items, there should be 40! - var items = contentService.GetRootContent(); + // now look up all items, there should be 40! + IEnumerable items = contentService.GetRootContent(); Assert.AreEqual(2 * MaxThreadCount, items.Count()); } else @@ -168,9 +177,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Ensure_All_Threads_Execute_Successfully_Media_Service() { if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null) + { Assert.Ignore("Do not run on VSTS."); + } - var log = GetRequiredService>(); + ILogger log = GetRequiredService>(); // mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton var mediaService = (MediaService)MediaService; @@ -180,9 +191,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services log.LogInformation("Starting..."); - var done = TraceLocks(); + ManualResetEventSlim done = TraceLocks(); - for (var i = 0; i < MaxThreadCount; i++) + for (int i = 0; i < MaxThreadCount; i++) { var t = new Thread(() => { @@ -190,30 +201,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { log.LogInformation("[{0}] Running...", Thread.CurrentThread.ManagedThreadId); - var name1 = "test-" + Guid.NewGuid(); - var media1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder); + string name1 = "test-" + Guid.NewGuid(); + IMedia media1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder); log.LogInformation("[{0}] Saving media #1.", Thread.CurrentThread.ManagedThreadId); Save(mediaService, media1); - Thread.Sleep(100); //quick pause for maximum overlap! + Thread.Sleep(100); // quick pause for maximum overlap! - var name2 = "test-" + Guid.NewGuid(); - var media2 = mediaService.CreateMedia(name2, -1, Constants.Conventions.MediaTypes.Folder); + string name2 = "test-" + Guid.NewGuid(); + IMedia media2 = mediaService.CreateMedia(name2, -1, Constants.Conventions.MediaTypes.Folder); log.LogInformation("[{0}] Saving media #2.", Thread.CurrentThread.ManagedThreadId); Save(mediaService, media2); } catch (Exception e) { - lock (exceptions) { exceptions.Add(e); } + lock (exceptions) + { + exceptions.Add(e); + } } }); threads.Add(t); } - //start all threads + // start all threads threads.ForEach(x => x.Start()); - //wait for all to complete + // wait for all to complete threads.ForEach(x => x.Join()); done.Set(); @@ -221,20 +235,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services if (exceptions.Count == 0) { // now look up all items, there should be 40! - var items = mediaService.GetRootMedia(); + IEnumerable items = mediaService.GetRootMedia(); Assert.AreEqual(2 * MaxThreadCount, items.Count()); } else { throw new Exception("Exceptions!", exceptions.First()); // rethrow the first one... } - } public void CreateTestData() { // Create and Save ContentType "umbTextpage" -> 1045 - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage"); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage"); contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"); ContentTypeService.Save(contentType); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs index 8b5189378d..e0d29ca634 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; @@ -27,23 +30,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class UserServiceTests : UmbracoIntegrationTest { - private UserService UserService => (UserService) GetRequiredService(); + private UserService UserService => (UserService)GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); [Test] public void Get_User_Permissions_For_Unassigned_Permission_Nodes() { // Arrange - var user = CreateTestUser(out _); + IUser user = CreateTestUser(out _); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -52,7 +58,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.Save(content); // Act - var permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); + EntityPermission[] permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); @@ -65,14 +71,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_User_Permissions_For_Assigned_Permission_Nodes() { // Arrange - var user = CreateTestUser(out var userGroup); + IUser user = CreateTestUser(out IUserGroup userGroup); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -87,7 +93,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[2], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); + EntityPermission[] permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); @@ -100,14 +106,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_UserGroup_Assigned_Permissions() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -122,7 +128,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content.ElementAt(2), ActionBrowse.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissions(userGroup, false, content[0].Id, content[1].Id, content[2].Id).ToArray(); + EntityPermission[] permissions = UserService.GetPermissions(userGroup, false, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); @@ -135,14 +141,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_UserGroup_Assigned_And_Default_Permissions() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -156,7 +162,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[1], ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissions(userGroup, true, content[0].Id, content[1].Id, content[2].Id) + EntityPermission[] permissions = UserService.GetPermissions(userGroup, true, content[0].Id, content[1].Id, content[2].Id) .ToArray(); // Assert @@ -170,31 +176,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_All_User_Permissions_For_All_Nodes_With_Explicit_Permission() { // Arrange - var userGroup1 = CreateTestUserGroup(); - var userGroup2 = CreateTestUserGroup("test2", "Test 2"); - var userGroup3 = CreateTestUserGroup("test3", "Test 3"); - var user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); + UserGroup userGroup1 = CreateTestUserGroup(); + UserGroup userGroup2 = CreateTestUserGroup("test2", "Test 2"); + UserGroup userGroup3 = CreateTestUserGroup("test3", "Test 3"); + IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); - var defaultPermissionCount = userGroup3.Permissions.Count(); + int defaultPermissionCount = userGroup3.Permissions.Count(); user.AddGroup(userGroup1); user.AddGroup(userGroup2); user.AddGroup(userGroup3); UserService.Save(user); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); - //assign permissions - we aren't assigning anything explicit for group3 and nothing explicit for content[2] /w group2 + + // assign permissions - we aren't assigning anything explicit for group3 and nothing explicit for content[2] /w group2 ContentService.SetPermission(content[0], ActionBrowse.ActionLetter, new int[] { userGroup1.Id }); ContentService.SetPermission(content[0], ActionDelete.ActionLetter, new int[] { userGroup1.Id }); ContentService.SetPermission(content[0], ActionMove.ActionLetter, new int[] { userGroup2.Id }); @@ -203,46 +210,52 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[2], ActionDelete.ActionLetter, new int[] { userGroup1.Id }); // Act - //we don't pass in any nodes so it will return all of them - var result = UserService.GetPermissions(user).ToArray(); + // we don't pass in any nodes so it will return all of them + EntityPermission[] result = UserService.GetPermissions(user).ToArray(); var permissions = result .GroupBy(x => x.EntityId) .ToDictionary(x => x.Key, x => x.GroupBy(a => a.UserGroupId).ToDictionary(a => a.Key, a => a.ToArray())); // Assert - //there will be 3 since that is how many content items there are + // there will be 3 since that is how many content items there are Assert.AreEqual(3, permissions.Count); - //test permissions contains content[0] + // test permissions contains content[0] Assert.IsTrue(permissions.ContainsKey(content[0].Id)); - //test that this permissions set contains permissions for all groups + + // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup3.Id)); - //test that the correct number of permissions are returned for each group + + // test that the correct number of permissions are returned for each group Assert.AreEqual(2, permissions[content[0].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(1, permissions[content[0].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[0].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); - //test permissions contains content[1] + // test permissions contains content[1] Assert.IsTrue(permissions.ContainsKey(content[1].Id)); - //test that this permissions set contains permissions for all groups + + // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup3.Id)); - //test that the correct number of permissions are returned for each group + + // test that the correct number of permissions are returned for each group Assert.AreEqual(1, permissions[content[1].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(1, permissions[content[1].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[1].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); - //test permissions contains content[2] + // test permissions contains content[2] Assert.IsTrue(permissions.ContainsKey(content[2].Id)); - //test that this permissions set contains permissions for all groups + + // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup3.Id)); - //test that the correct number of permissions are returned for each group + + // test that the correct number of permissions are returned for each group Assert.AreEqual(1, permissions[content[2].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[2].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[2].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); @@ -252,14 +265,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_All_User_Group_Permissions_For_All_Nodes() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -274,7 +287,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[2], ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act - //we don't pass in any nodes so it will return all of them + // we don't pass in any nodes so it will return all of them var permissions = UserService.GetPermissions(userGroup, true) .GroupBy(x => x.EntityId) .ToDictionary(x => x.Key, x => x); @@ -292,11 +305,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Calculate_Permissions_For_User_For_Path() { - //see: http://issues.umbraco.org/issue/U4-10075#comment=67-40085 + // see: http://issues.umbraco.org/issue/U4-10075#comment=67-40085 // for an overview of what this is testing - const string path = "-1,1,2,3,4"; - var pathIds = path.GetIdsFromPathReversed(); + int[] pathIds = path.GetIdsFromPathReversed(); const int groupA = 7; const int groupB = 8; @@ -304,51 +316,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var userGroups = new Dictionary { - {groupA, new[] {"S", "D", "F"}}, - {groupB, new[] {"S", "D", "G", "K"}}, - {groupC, new[] {"F", "G"}} + { groupA, new[] { "S", "D", "F" } }, + { groupB, new[] { "S", "D", "G", "K" } }, + { groupC, new[] { "F", "G" } } }; - var permissions = new[] + EntityPermission[] permissions = new[] { - new EntityPermission(groupA, 1, userGroups[groupA], isDefaultPermissions:true), - new EntityPermission(groupA, 2, userGroups[groupA], isDefaultPermissions:true), - new EntityPermission(groupA, 3, userGroups[groupA], isDefaultPermissions:true), - new EntityPermission(groupA, 4, userGroups[groupA], isDefaultPermissions:true), + new EntityPermission(groupA, 1, userGroups[groupA], isDefaultPermissions: true), + new EntityPermission(groupA, 2, userGroups[groupA], isDefaultPermissions: true), + new EntityPermission(groupA, 3, userGroups[groupA], isDefaultPermissions: true), + new EntityPermission(groupA, 4, userGroups[groupA], isDefaultPermissions: true), - new EntityPermission(groupB, 1, userGroups[groupB], isDefaultPermissions:true), - new EntityPermission(groupB, 2, new []{"F", "R"}, isDefaultPermissions:false), - new EntityPermission(groupB, 3, userGroups[groupB], isDefaultPermissions:true), - new EntityPermission(groupB, 4, userGroups[groupB], isDefaultPermissions:true), + new EntityPermission(groupB, 1, userGroups[groupB], isDefaultPermissions: true), + new EntityPermission(groupB, 2, new[] { "F", "R" }, isDefaultPermissions: false), + new EntityPermission(groupB, 3, userGroups[groupB], isDefaultPermissions: true), + new EntityPermission(groupB, 4, userGroups[groupB], isDefaultPermissions: true), - new EntityPermission(groupC, 1, userGroups[groupC], isDefaultPermissions:true), - new EntityPermission(groupC, 2, userGroups[groupC], isDefaultPermissions:true), - new EntityPermission(groupC, 3, new []{"Q", "Z"}, isDefaultPermissions:false), - new EntityPermission(groupC, 4, userGroups[groupC], isDefaultPermissions:true), + new EntityPermission(groupC, 1, userGroups[groupC], isDefaultPermissions: true), + new EntityPermission(groupC, 2, userGroups[groupC], isDefaultPermissions: true), + new EntityPermission(groupC, 3, new[] { "Q", "Z" }, isDefaultPermissions: false), + new EntityPermission(groupC, 4, userGroups[groupC], isDefaultPermissions: true), }; - //Permissions for Id 4 - var result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds); + // Permissions for Id 4 + EntityPermissionSet result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds); Assert.AreEqual(4, result.EntityId); - var allPermissions = result.GetAllPermissions().ToArray(); + string[] allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(6, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "R", "Q", "Z" })); - //Permissions for Id 3 + // Permissions for Id 3 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(1).ToArray()); Assert.AreEqual(3, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(6, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "R", "Q", "Z" })); - //Permissions for Id 2 + // Permissions for Id 2 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(2).ToArray()); Assert.AreEqual(2, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(5, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "G", "R" })); - //Permissions for Id 1 + // Permissions for Id 1 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(3).ToArray()); Assert.AreEqual(1, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); @@ -359,16 +371,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_1() { - var path = "-1,1,2,3"; - var pathIds = path.GetIdsFromPathReversed(); - var defaults = new[] { "A", "B" }; + string path = "-1,1,2,3"; + int[] pathIds = path.GetIdsFromPathReversed(); + string[] defaults = new[] { "A", "B" }; var permissions = new List { - new EntityPermission(9876, 1, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 2, new []{"B","C", "D"}, isDefaultPermissions:false), - new EntityPermission(9876, 3, defaults, isDefaultPermissions:true) + new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 2, new[] { "B", "C", "D" }, isDefaultPermissions: false), + new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; - var result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); + EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); Assert.AreEqual(3, result.AssignedPermissions.Length); Assert.IsFalse(result.IsDefaultPermissions); Assert.IsTrue(result.AssignedPermissions.ContainsAll(new[] { "B", "C", "D" })); @@ -379,32 +391,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_2() { - var path = "-1,1,2,3"; - var pathIds = path.GetIdsFromPathReversed(); - var defaults = new[] { "A", "B", "C" }; + string path = "-1,1,2,3"; + int[] pathIds = path.GetIdsFromPathReversed(); + string[] defaults = new[] { "A", "B", "C" }; var permissions = new List { - new EntityPermission(9876, 1, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 2, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 3, defaults, isDefaultPermissions:true) + new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 2, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; - var result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: false); + EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: false); Assert.IsNull(result); } [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_3() { - var path = "-1,1,2,3"; - var pathIds = path.GetIdsFromPathReversed(); - var defaults = new[] { "A", "B" }; + string path = "-1,1,2,3"; + int[] pathIds = path.GetIdsFromPathReversed(); + string[] defaults = new[] { "A", "B" }; var permissions = new List { - new EntityPermission(9876, 1, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 2, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 3, defaults, isDefaultPermissions:true) + new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 2, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; - var result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); + EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); Assert.AreEqual(2, result.AssignedPermissions.Length); Assert.IsTrue(result.IsDefaultPermissions); Assert.IsTrue(result.AssignedPermissions.ContainsAll(defaults)); @@ -416,18 +428,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_User_Implicit_Permissions() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parent = ContentBuilder.CreateSimpleContent(contentType); + Content parent = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parent); - var child1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parent.Id); + Content child1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parent.Id); ContentService.Save(child1); - var child2 = ContentBuilder.CreateSimpleContent(contentType, "child2", child1.Id); + Content child2 = ContentBuilder.CreateSimpleContent(contentType, "child2", child1.Id); ContentService.Save(child2); ContentService.SetPermission(parent, ActionBrowse.ActionLetter, new int[] { userGroup.Id }); @@ -437,20 +449,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(parent, ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissionsForPath(userGroup, child2.Path); + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, child2.Path); // Assert - var allPermissions = permissions.GetAllPermissions().ToArray(); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(3, allPermissions.Length); } [Test] public void Can_Delete_User() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); UserService.Delete(user, true); - var deleted = UserService.GetUserById(user.Id); + IUser deleted = UserService.GetUserById(user.Id); // Assert Assert.That(deleted, Is.Null); @@ -459,10 +471,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Disables_User_Instead_Of_Deleting_If_Flag_Not_Set() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); UserService.Delete(user); - var deleted = UserService.GetUserById(user.Id); + IUser deleted = UserService.GetUserById(user.Id); // Assert Assert.That(deleted, Is.Not.Null); @@ -471,8 +483,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Exists_By_Username() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); - var user2 = UserService.CreateUserWithIdentity("john2@umbraco.io", "john2@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user2 = UserService.CreateUserWithIdentity("john2@umbraco.io", "john2@umbraco.io"); Assert.IsTrue(UserService.Exists("JohnDoe")); Assert.IsFalse(UserService.Exists("notFound")); Assert.IsTrue(UserService.Exists("john2@umbraco.io")); @@ -481,7 +493,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Email() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByEmail(user.Email)); Assert.IsNull(UserService.GetByEmail("do@not.find")); @@ -490,7 +502,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Username() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByUsername(user.Username)); Assert.IsNull(UserService.GetByUsername("notFound")); @@ -499,7 +511,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Username_With_Backslash() { - var user = UserService.CreateUserWithIdentity("mydomain\\JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("mydomain\\JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByUsername(user.Username)); Assert.IsNull(UserService.GetByUsername("notFound")); @@ -508,7 +520,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Object_Id() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetUserById(user.Id)); Assert.IsNull(UserService.GetUserById(9876)); @@ -517,14 +529,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Starts_With() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //don't find this - var customUser = UserBuilder.CreateUser(); + + // don't find this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@hello.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("tes", 0, 100, out _, StringPropertyMatchType.StartsWith); + IEnumerable found = UserService.FindByEmail("tes", 0, 100, out _, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } @@ -532,14 +545,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Ends_With() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //include this - var customUser = UserBuilder.CreateUser(); + + // include this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("test.com", 0, 100, out _, StringPropertyMatchType.EndsWith); + IEnumerable found = UserService.FindByEmail("test.com", 0, 100, out _, StringPropertyMatchType.EndsWith); Assert.AreEqual(11, found.Count()); } @@ -547,14 +561,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Contains() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //include this - var customUser = UserBuilder.CreateUser(); + + // include this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("test", 0, 100, out _, StringPropertyMatchType.Contains); + IEnumerable found = UserService.FindByEmail("test", 0, 100, out _, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } @@ -562,14 +577,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Exact() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //include this - var customUser = UserBuilder.CreateUser(); + + // include this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("hello@test.com", 0, 100, out _, StringPropertyMatchType.Exact); + IEnumerable found = UserService.FindByEmail("hello@test.com", 0, 100, out _, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } @@ -577,12 +593,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - var found = UserService.GetAll(0, 2, out var totalRecs); + IEnumerable found = UserService.GetAll(0, 2, out long totalRecs); Assert.AreEqual(2, found.Count()); + // + 1 because of the built in admin user Assert.AreEqual(11, totalRecs); Assert.AreEqual("admin", found.First().Username); @@ -592,10 +609,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users_With_Filter() { - var users = UserBuilder. CreateMulipleUsers(10).ToArray(); + IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); UserService.Save(users); - var found = UserService.GetAll(0, 2, out var totalRecs, "username", Direction.Ascending, filter: "test"); + IEnumerable found = UserService.GetAll(0, 2, out long totalRecs, "username", Direction.Ascending, filter: "test"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); @@ -606,19 +623,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users_For_Group() { - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); UserService.Save(userGroup); - var users = UserBuilder. CreateMulipleUsers(10).ToArray(); - for (var i = 0; i < 10;) + IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); + for (int i = 0; i < 10;) { users[i].AddGroup(userGroup.ToReadOnlyGroup()); i = i + 2; } + UserService.Save(users); long totalRecs; - var found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, includeUserGroups: new[] { userGroup.Alias }); + IEnumerable found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, includeUserGroups: new[] { userGroup.Alias }); Assert.AreEqual(2, found.Count()); Assert.AreEqual(5, totalRecs); @@ -629,24 +647,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users_For_Group_With_Filter() { - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); UserService.Save(userGroup); - var users = UserBuilder. CreateMulipleUsers(10).ToArray(); - for (var i = 0; i < 10;) + IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); + for (int i = 0; i < 10;) { users[i].AddGroup(userGroup.ToReadOnlyGroup()); i = i + 2; } - for (var i = 0; i < 10;) + + for (int i = 0; i < 10;) { users[i].Name = "blah" + users[i].Name; i = i + 3; } + UserService.Save(users); long totalRecs; - var found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, userGroups: new[] { userGroup.Alias }, filter: "blah"); + IEnumerable found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, userGroups: new[] { userGroup.Alias }, filter: "blah"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(2, totalRecs); @@ -657,12 +677,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Count_All_Users() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); UserService.Save(customUser); - var found = UserService.GetCount(MemberCountType.All); + int found = UserService.GetCount(MemberCountType.All); // + 1 because of the built in admin user Assert.AreEqual(12, found); @@ -672,24 +692,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Count_All_Online_Users() { - var users = UserBuilder. CreateMulipleUsers(10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); + IEnumerable users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); throw new NotImplementedException(); } [Test] public void Count_All_Locked_Users() { - var users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsLockedOut = i % 2 == 0); + IEnumerable users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsLockedOut = i % 2 == 0); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); customUser.IsLockedOut = true; UserService.Save(customUser); - var found = UserService.GetCount(MemberCountType.LockedOut); + int found = UserService.GetCount(MemberCountType.LockedOut); Assert.AreEqual(6, found); } @@ -697,14 +717,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Count_All_Approved_Users() { - var users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsApproved = i % 2 == 0); + IEnumerable users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsApproved = i % 2 == 0); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); customUser.IsApproved = false; UserService.Save(customUser); - var found = UserService.GetCount(MemberCountType.Approved); + int found = UserService.GetCount(MemberCountType.Approved); // + 1 because of the built in admin user Assert.AreEqual(6, found); @@ -714,7 +734,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Persist_New_User() { // Act - var membershipUser = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser membershipUser = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); // Assert Assert.That(membershipUser.HasIdentity, Is.True); @@ -728,10 +748,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Act // NOTE: Normally the hash'ing would be handled in the membership provider, so the service just saves the password - var password = "123456"; + string password = "123456"; var hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); - var encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); + string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); var globalSettings = new GlobalSettings(); var membershipUser = new User(globalSettings, "JohnDoe", "john@umbraco.io", encodedPassword, encodedPassword); UserService.Save(membershipUser); @@ -756,11 +776,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services userGroup.AddAllowedSection("mediat"); UserService.Save(userGroup); - var result1 = UserService.GetUserGroupById(userGroup.Id); + IUserGroup result1 = UserService.GetUserGroupById(userGroup.Id); Assert.AreEqual(2, result1.AllowedSections.Count()); - //adds some allowed sections + // adds some allowed sections userGroup.AddAllowedSection("test1"); userGroup.AddAllowedSection("test2"); userGroup.AddAllowedSection("test3"); @@ -771,19 +791,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(6, result1.AllowedSections.Count()); - //simulate clearing the sections - foreach (var s in userGroup.AllowedSections) + // simulate clearing the sections + foreach (string s in userGroup.AllowedSections) { result1.RemoveAllowedSection(s); } - //now just re-add a couple + // now just re-add a couple result1.AddAllowedSection("test3"); result1.AddAllowedSection("test4"); UserService.Save(result1); // Assert - //re-get + // re-get result1 = UserService.GetUserGroupById(userGroup.Id); Assert.AreEqual(2, result1.AllowedSections.Count()); } @@ -804,18 +824,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services UserService.Save(userGroup1); UserService.Save(userGroup2); - //adds some allowed sections + // adds some allowed sections userGroup1.AddAllowedSection("test"); userGroup2.AddAllowedSection("test"); UserService.Save(userGroup1); UserService.Save(userGroup2); - //now clear the section from all users + // now clear the section from all users UserService.DeleteSectionFromAllUserGroups("test"); // Assert - var result1 = UserService.GetUserGroupById(userGroup1.Id); - var result2 = UserService.GetUserGroupById(userGroup2.Id); + IUserGroup result1 = UserService.GetUserGroupById(userGroup1.Id); + IUserGroup result2 = UserService.GetUserGroupById(userGroup2.Id); Assert.IsFalse(result1.AllowedSections.Contains("test")); Assert.IsFalse(result2.AllowedSections.Contains("test")); } @@ -847,15 +867,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services UserService.Save(userGroup3); // Assert - var result1 = UserService.GetUserGroupById(userGroup1.Id); - var result2 = UserService.GetUserGroupById(userGroup2.Id); - var result3 = UserService.GetUserGroupById(userGroup3.Id); + IUserGroup result1 = UserService.GetUserGroupById(userGroup1.Id); + IUserGroup result2 = UserService.GetUserGroupById(userGroup2.Id); + IUserGroup result3 = UserService.GetUserGroupById(userGroup3.Id); Assert.IsTrue(result1.AllowedSections.Contains("test")); Assert.IsTrue(result2.AllowedSections.Contains("test")); Assert.IsFalse(result3.AllowedSections.Contains("test")); - //now add the section to all groups - foreach (var userGroup in new[] { userGroup1, userGroup2, userGroup3 }) + // now add the section to all groups + foreach (UserGroup userGroup in new[] { userGroup1, userGroup2, userGroup3 }) { userGroup.AddAllowedSection("test"); UserService.Save(userGroup); @@ -881,7 +901,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_User_With_Empty_Username() { // Arrange - var user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); user.Username = string.Empty; // Act & Assert @@ -892,7 +912,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_User_With_Empty_Name() { // Arrange - var user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); user.Name = string.Empty; // Act & Assert @@ -903,10 +923,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Profile_Username() { // Arrange - var user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); + IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); // Act - var profile = UserService.GetProfileByUserName(user.Username); + IProfile profile = UserService.GetProfileByUserName(user.Username); // Assert Assert.IsNotNull(profile); @@ -918,10 +938,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Profile_Id() { // Arrange - var user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); + IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); // Act - var profile = UserService.GetProfileById((int)user.Id); + IProfile profile = UserService.GetProfileById((int)user.Id); // Assert Assert.IsNotNull(profile); @@ -932,7 +952,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Profile_Id_Must_Return_Null_If_User_Does_Not_Exist() { - var profile = UserService.GetProfileById(42); + IProfile profile = UserService.GetProfileById(42); // Assert Assert.IsNull(profile); @@ -941,7 +961,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void GetProfilesById_Must_Return_Empty_If_User_Does_Not_Exist() { - var profiles = UserService.GetProfilesById(42); + IEnumerable profiles = UserService.GetProfilesById(42); // Assert CollectionAssert.IsEmpty(profiles); @@ -951,10 +971,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_User_By_Username() { // Arrange - var originalUser = CreateTestUser(out _); + IUser originalUser = CreateTestUser(out _); // Act - var updatedItem = (User)UserService.GetByUsername(originalUser.Username); // Assert @@ -975,31 +994,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Assigned_StartNodes_For_User() { - var startContentItems = BuildContentItems(3); + Content[] startContentItems = BuildContentItems(3); - var testUserGroup = CreateTestUserGroup(); + UserGroup testUserGroup = CreateTestUserGroup(); - var userGroupId = testUserGroup.Id; + int userGroupId = testUserGroup.Id; CreateTestUsers(startContentItems.Select(x => x.Id).ToArray(), testUserGroup, 3); - var usersInGroup = UserService.GetAllInGroup(userGroupId); + IEnumerable usersInGroup = UserService.GetAllInGroup(userGroupId); - foreach (var user in usersInGroup) + foreach (IUser user in usersInGroup) + { Assert.AreEqual(user.StartContentIds.Length, startContentItems.Length); + } } private Content[] BuildContentItems(int numberToCreate) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); var startContentItems = new List(); - for (var i = 0; i < numberToCreate; i++) + for (int i = 0; i < numberToCreate; i++) + { startContentItems.Add(ContentBuilder.CreateSimpleContent(contentType)); + } ContentService.Save(startContentItems); @@ -1010,7 +1033,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { userGroup = CreateTestUserGroup(); - var user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); + IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); user.AddGroup(userGroup.ToReadOnlyGroup()); @@ -1023,9 +1046,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { var users = new List(); - for (var i = 0; i < numberToCreate; i++) + for (int i = 0; i < numberToCreate; i++) { - var user = UserService.CreateUserWithIdentity($"test{i}", $"test{i}@test.com"); + IUser user = UserService.CreateUserWithIdentity($"test{i}", $"test{i}@test.com"); user.AddGroup(userGroup.ToReadOnlyGroup()); var updateable = (User)user; @@ -1041,8 +1064,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private UserGroup CreateTestUserGroup(string alias = "testGroup", string name = "Test Group") { - var permissions = "ABCDEFGHIJ1234567".ToCharArray().Select(x => x.ToString()).ToArray(); - var userGroup = UserGroupBuilder.CreateUserGroup(alias, name, permissions: permissions); + string[] permissions = "ABCDEFGHIJ1234567".ToCharArray().Select(x => x.ToString()).ToArray(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(alias, name, permissions: permissions); UserService.Save(userGroup); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs index dc88455d68..4350029159 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; @@ -44,13 +47,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters ContentTypes = new[] { new NestedContentConfiguration.ContentType { Alias = "feature" } - } + } }; - var complexTestEditor = Services.GetRequiredService(); - var testEditor = Services.GetRequiredService(); - var dataTypeService = Services.GetRequiredService(); - var serializer = Services.GetRequiredService(); + ComplexTestEditor complexTestEditor = Services.GetRequiredService(); + TestEditor testEditor = Services.GetRequiredService(); + IDataTypeService dataTypeService = Services.GetRequiredService(); + IConfigurationEditorJsonSerializer serializer = Services.GetRequiredService(); var complexDataType = new DataType(complexTestEditor, serializer) { @@ -65,85 +68,84 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters dataTypeService.Save(complexDataType); dataTypeService.Save(testDataType); - var fileService = Services.GetRequiredService(); - var template = TemplateBuilder.CreateTextPageTemplate(); + IFileService fileService = Services.GetRequiredService(); + Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); _contentType = ContentTypeBuilder.CreateTextPageContentType(ContentTypeAlias, defaultTemplateId: template.Id); // add complex editor - foreach (var pt in _contentType.PropertyTypes) + foreach (IPropertyType pt in _contentType.PropertyTypes) { pt.DataTypeId = testDataType.Id; } _contentType.AddPropertyType( - new PropertyType(_shortStringHelper, "complexTest", ValueStorageType.Ntext) { Alias = "complex", Name = "Complex", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = complexDataType.Id }, + new PropertyType(_shortStringHelper, "complexTest", ValueStorageType.Ntext) { Alias = "complex", Name = "Complex", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = complexDataType.Id }, "Content"); // make them all validate with a regex rule that will not pass - foreach (var prop in _contentType.PropertyTypes) + foreach (IPropertyType prop in _contentType.PropertyTypes) { prop.ValidationRegExp = "^donotmatch$"; prop.ValidationRegExpMessage = "Does not match!"; } - var contentTypeService = Services.GetRequiredService(); + IContentTypeService contentTypeService = Services.GetRequiredService(); contentTypeService.Save(_contentType); } - // - // protected override void Compose() - // { - // base.Compose(); - // - // var complexEditorConfig = new NestedContentConfiguration - // { - // ContentTypes = new[] - // { - // new NestedContentConfiguration.ContentType { Alias = "feature" } - // } - // }; - // var dataTypeService = new Mock(); - // dataTypeService.Setup(x => x.GetDataType(It.IsAny())) - // .Returns((int id) => id == ComplexDataTypeId - // ? Mock.Of(x => x.Configuration == complexEditorConfig) - // : Mock.Of()); - // - // var contentTypeService = new Mock(); - // contentTypeService.Setup(x => x.GetAll(It.IsAny())) - // .Returns(() => new List - // { - // _contentType - // }); - // - // var textService = new Mock(); - // textService.Setup(x => x.Localize("validation/invalidPattern", It.IsAny(), It.IsAny>())).Returns(() => "invalidPattern"); - // textService.Setup(x => x.Localize("validation/invalidNull", It.IsAny(), It.IsAny>())).Returns("invalidNull"); - // textService.Setup(x => x.Localize("validation/invalidEmpty", It.IsAny(), It.IsAny>())).Returns("invalidEmpty"); - // - // composition.Services.AddUnique(x => Mock.Of(x => x.GetDataType(It.IsAny()) == Mock.Of())); - // composition.Services.AddUnique(x => dataTypeService.Object); - // composition.Services.AddUnique(x => contentTypeService.Object); - // composition.Services.AddUnique(x => textService.Object); - // - // Composition.WithCollectionBuilder() - // .Add() - // .Add(); - // } + //// protected override void Compose() + //// { + //// base.Compose(); + //// + //// var complexEditorConfig = new NestedContentConfiguration + //// { + //// ContentTypes = new[] + //// { + //// new NestedContentConfiguration.ContentType { Alias = "feature" } + //// } + //// }; + //// var dataTypeService = new Mock(); + //// dataTypeService.Setup(x => x.GetDataType(It.IsAny())) + //// .Returns((int id) => id == ComplexDataTypeId + //// ? Mock.Of(x => x.Configuration == complexEditorConfig) + //// : Mock.Of()); + //// + //// var contentTypeService = new Mock(); + //// contentTypeService.Setup(x => x.GetAll(It.IsAny())) + //// .Returns(() => new List + //// { + //// _contentType + //// }); + //// + //// var textService = new Mock(); + //// textService.Setup(x => x.Localize("validation/invalidPattern", It.IsAny(), It.IsAny>())).Returns(() => "invalidPattern"); + //// textService.Setup(x => x.Localize("validation/invalidNull", It.IsAny(), It.IsAny>())).Returns("invalidNull"); + //// textService.Setup(x => x.Localize("validation/invalidEmpty", It.IsAny(), It.IsAny>())).Returns("invalidEmpty"); + //// + //// composition.Services.AddUnique(x => Mock.Of(x => x.GetDataType(It.IsAny()) == Mock.Of())); + //// composition.Services.AddUnique(x => dataTypeService.Object); + //// composition.Services.AddUnique(x => contentTypeService.Object); + //// composition.Services.AddUnique(x => textService.Object); + //// + //// Composition.WithCollectionBuilder() + //// .Add() + //// .Add(); + //// } [Test] public void Validating_ContentItemSave() { - var logger = Services.GetRequiredService>(); - var backofficeSecurityFactory = Services.GetRequiredService(); + ILogger logger = Services.GetRequiredService>(); + IBackOfficeSecurityFactory backofficeSecurityFactory = Services.GetRequiredService(); backofficeSecurityFactory.EnsureBackOfficeSecurity(); - var propertyValidationService = Services.GetRequiredService(); - var umbracoMapper = Services.GetRequiredService(); + IPropertyValidationService propertyValidationService = Services.GetRequiredService(); + UmbracoMapper umbracoMapper = Services.GetRequiredService(); var validator = new ContentSaveModelValidator(logger, propertyValidationService); - var content = ContentBuilder.CreateTextpageContent(_contentType, "test", -1); + Content content = ContentBuilder.CreateTextpageContent(_contentType, "test", -1); var id1 = new Guid("c8df5136-d606-41f0-9134-dea6ae0c2fd9"); var id2 = new Guid("f916104a-4082-48b2-a515-5c4bf2230f38"); @@ -151,7 +153,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters // TODO: Ok now test with a 4th level complex nested editor - var complexValue = @"[{ + string complexValue = @"[{ ""key"": """ + id1.ToString() + @""", ""name"": ""Hello world"", ""ncContentTypeAlias"": """ + ContentTypeAlias + @""", @@ -175,7 +177,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters content.SetValue("complex", complexValue); // map the persisted properties to a model representing properties to save - //var saveProperties = content.Properties.Select(x => Mapper.Map(x)).ToList(); + // var saveProperties = content.Properties.Select(x => Mapper.Map(x)).ToList(); var saveProperties = content.Properties.Select(x => { return new ContentPropertyBasic @@ -214,13 +216,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters ContentItemBinder.BindModel(save, content, _modelBinderHelper, umbracoMapper); var modelState = new ModelStateDictionary(); - var isValid = validator.ValidatePropertiesData(save, saveVariants[0], saveVariants[0].PropertyCollectionDto, modelState); + bool isValid = validator.ValidatePropertiesData(save, saveVariants[0], saveVariants[0].PropertyCollectionDto, modelState); // list results for debugging - foreach (var state in modelState) + foreach (KeyValuePair state in modelState) { Console.WriteLine(state.Key); - foreach (var error in state.Value.Errors) + foreach (ModelError error in state.Value.Errors) { Console.WriteLine("\t" + error.ErrorMessage); } @@ -231,26 +233,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters Assert.AreEqual(11, modelState.Keys.Count()); const string complexPropertyKey = "_Properties.complex.invariant.null"; Assert.IsTrue(modelState.Keys.Contains(complexPropertyKey)); - foreach (var state in modelState.Where(x => x.Key != complexPropertyKey)) + foreach (KeyValuePair state in modelState.Where(x => x.Key != complexPropertyKey)) { - foreach (var error in state.Value.Errors) + foreach (ModelError error in state.Value.Errors) { Assert.IsFalse(error.ErrorMessage.DetectIsJson()); // non complex is just an error message } } - var complexEditorErrors = modelState.Single(x => x.Key == complexPropertyKey).Value.Errors; - Assert.AreEqual(1, complexEditorErrors.Count); - var nestedError = complexEditorErrors[0]; - var jsonError = JsonConvert.DeserializeObject(nestedError.ErrorMessage); - var modelStateKeys = new[] { "_Properties.title.invariant.null.innerFieldId", "_Properties.title.invariant.null.value", "_Properties.bodyText.invariant.null.innerFieldId", "_Properties.bodyText.invariant.null.value" }; + ModelErrorCollection complexEditorErrors = modelState.Single(x => x.Key == complexPropertyKey).Value.Errors; + Assert.AreEqual(1, complexEditorErrors.Count); + ModelError nestedError = complexEditorErrors[0]; + JArray jsonError = JsonConvert.DeserializeObject(nestedError.ErrorMessage); + + string[] modelStateKeys = new[] { "_Properties.title.invariant.null.innerFieldId", "_Properties.title.invariant.null.value", "_Properties.bodyText.invariant.null.innerFieldId", "_Properties.bodyText.invariant.null.value" }; AssertNestedValidation(jsonError, 0, id1, modelStateKeys); AssertNestedValidation(jsonError, 1, id2, modelStateKeys.Concat(new[] { "_Properties.complex.invariant.null.innerFieldId", "_Properties.complex.invariant.null.value" }).ToArray()); var nestedJsonError = jsonError.SelectToken("$[1].complex") as JArray; Assert.IsNotNull(nestedJsonError); AssertNestedValidation(nestedJsonError, 0, id3, modelStateKeys); - - } private void AssertNestedValidation(JArray jsonError, int index, Guid id, string[] modelStateKeys) @@ -259,7 +260,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters Assert.AreEqual(id.ToString(), jsonError.SelectToken("$[" + index + "].$id").Value()); Assert.AreEqual("textPage", jsonError.SelectToken("$[" + index + "].$elementTypeAlias").Value()); Assert.IsNotNull(jsonError.SelectToken("$[" + index + "].ModelState")); - foreach (var key in modelStateKeys) + foreach (string key in modelStateKeys) { var error = jsonError.SelectToken("$[" + index + "].ModelState['" + key + "']") as JArray; Assert.IsNotNull(error); @@ -267,38 +268,45 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters } } - //[HideFromTypeFinder] + // [HideFromTypeFinder] [DataEditor("complexTest", "test", "test")] public class ComplexTestEditor : NestedContentPropertyEditor { - public ComplexTestEditor(ILoggerFactory loggerFactory, Lazy propertyEditors, IDataTypeService dataTypeService, IContentTypeService contentTypeService, ILocalizationService localizationService, - IIOHelper ioHelper, ILocalizedTextService localizedTextService, IShortStringHelper shortStringHelper, IJsonSerializer jsonSerializer) - : base(loggerFactory, propertyEditors, dataTypeService, localizationService, contentTypeService, ioHelper, shortStringHelper, localizedTextService, jsonSerializer) + public ComplexTestEditor( + ILoggerFactory loggerFactory, + Lazy propertyEditors, + IDataTypeService dataTypeService, + IContentTypeService contentTypeService, + ILocalizationService localizationService, + IIOHelper ioHelper, + ILocalizedTextService localizedTextService, + IShortStringHelper shortStringHelper, + IJsonSerializer jsonSerializer) + : base(loggerFactory, propertyEditors, dataTypeService, localizationService, contentTypeService, ioHelper, shortStringHelper, localizedTextService, jsonSerializer) { } protected override IDataValueEditor CreateValueEditor() { - var editor = base.CreateValueEditor(); + IDataValueEditor editor = base.CreateValueEditor(); editor.Validators.Add(new NeverValidateValidator()); return editor; } } - //[HideFromTypeFinder] - [DataEditor("test", "test", "test")] // This alias aligns with the prop editor alias for all properties created from MockedContentTypes.CreateTextPageContentType - public class TestEditor : DataEditor - { - public TestEditor( - ILoggerFactory loggerFactory, - IDataTypeService dataTypeService, - ILocalizationService localizationService, - ILocalizedTextService localizedTextService, - IShortStringHelper shortStringHelper, - IJsonSerializer jsonSerializer) - : base(loggerFactory, dataTypeService, localizationService, localizedTextService, shortStringHelper, jsonSerializer) + // [HideFromTypeFinder] + [DataEditor("test", "test", "test")] // This alias aligns with the prop editor alias for all properties created from MockedContentTypes.CreateTextPageContentType + public class TestEditor : DataEditor + { + public TestEditor( + ILoggerFactory loggerFactory, + IDataTypeService dataTypeService, + ILocalizationService localizationService, + ILocalizedTextService localizedTextService, + IShortStringHelper shortStringHelper, + IJsonSerializer jsonSerializer) + : base(loggerFactory, dataTypeService, localizationService, localizedTextService, shortStringHelper, jsonSerializer) { - } protected override IDataValueEditor CreateValueEditor() => new TestValueEditor(DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer, Attribute); @@ -316,7 +324,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters { Validators.Add(new NeverValidateValidator()); } - } } @@ -327,6 +334,5 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters yield return new ValidationResult("WRONG!", new[] { "innerFieldId" }); } } - } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs index 37863da472..1f07a1f45f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; @@ -16,7 +19,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.BackOffice [Test] public void AddUmbracoBackOfficeIdentity_ExpectBackOfficeUserStoreResolvable() { - var userStore = Services.GetService>(); + IUserStore userStore = Services.GetService>(); Assert.IsNotNull(userStore); Assert.AreEqual(typeof(BackOfficeUserStore), userStore.GetType()); @@ -25,7 +28,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.BackOffice [Test] public void AddUmbracoBackOfficeIdentity_ExpectBackOfficeClaimsPrincipalFactoryResolvable() { - var principalFactory = Services.GetService>(); + IUserClaimsPrincipalFactory principalFactory = Services.GetService>(); Assert.IsNotNull(principalFactory); Assert.AreEqual(typeof(BackOfficeClaimsPrincipalFactory), principalFactory.GetType()); @@ -34,7 +37,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.BackOffice [Test] public void AddUmbracoBackOfficeIdentity_ExpectBackOfficeUserManagerResolvable() { - var userManager = Services.GetService(); + IBackOfficeUserManager userManager = Services.GetService(); Assert.NotNull(userManager); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs index 7e43eb4b83..a57b9b34fa 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs @@ -15,11 +15,13 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; using Umbraco.Core.DependencyInjection; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Scoping; @@ -43,7 +45,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components ILogger logger = loggerFactory.CreateLogger("GenericLogger"); var globalSettings = new GlobalSettings(); var connectionStrings = new ConnectionStrings(); - var f = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, Options.Create(globalSettings), Options.Create(connectionStrings), new Lazy(() => new MapperCollection(Enumerable.Empty())), TestHelper.DbProviderFactoryCreator); + var f = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, Options.Create(globalSettings), Options.Create(connectionStrings), new Lazy(() => new MapperCollection(Enumerable.Empty())), TestHelper.DbProviderFactoryCreator, + new DatabaseSchemaCreatorFactory(loggerFactory.CreateLogger(), loggerFactory, new UmbracoVersion())); var fs = new FileSystems(mock.Object, loggerFactory.CreateLogger(), loggerFactory, IOHelper, Options.Create(globalSettings), Mock.Of()); var coreDebug = new CoreDebugSettings(); IMediaFileSystem mediaFileSystem = Mock.Of(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UmbracoRequestPathsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UmbracoRequestPathsTests.cs index 722376d61a..24f0b04080 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UmbracoRequestPathsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UmbracoRequestPathsTests.cs @@ -35,7 +35,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing [TestCase("/umbraco_client/Tree/Themes/umbraco/style.css?cdv=37", true)] [TestCase("/base/somebasehandler", false)] [TestCase("/", false)] - [TestCase("/home.aspx", false)] + [TestCase("/home.aspx", true)] // has ext, assume client side + [TestCase("http://www.domain.com/Umbraco/test/test.aspx", true)] // has ext, assume client side + [TestCase("http://www.domain.com/umbraco/test/test.js", true)] public void Is_Client_Side_Request(string url, bool assert) { IHostingEnvironment hostingEnvironment = CreateHostingEnvironment(); @@ -63,9 +65,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing [TestCase("http://www.domain.com/Umbraco/", "", true)] [TestCase("http://www.domain.com/umbraco/default.aspx", "", true)] [TestCase("http://www.domain.com/umbraco/test/test", "", false)] - [TestCase("http://www.domain.com/umbraco/test/test/test", "", false)] - [TestCase("http://www.domain.com/Umbraco/test/test.aspx", "", true)] - [TestCase("http://www.domain.com/umbraco/test/test.js", "", true)] + [TestCase("http://www.domain.com/umbraco/test/test/test", "", false)] [TestCase("http://www.domain.com/umbrac", "", false)] [TestCase("http://www.domain.com/test", "", false)] [TestCase("http://www.domain.com/test/umbraco", "", false)] @@ -77,7 +77,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing [TestCase("http://www.domain.com/myvdir/umbraco/api/blah", "myvdir", false)] [TestCase("http://www.domain.com/MyVdir/umbraco/api/blah", "/myvdir", false)] [TestCase("http://www.domain.com/MyVdir/Umbraco/", "myvdir", true)] - [TestCase("http://www.domain.com/umbraco/test/legacyAjaxCalls.ashx?some=query&blah=js", "", true)] public void Is_Back_Office_Request(string input, string virtualPath, bool expected) { var source = new Uri(input); @@ -85,7 +84,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing var umbracoRequestPaths = new UmbracoRequestPaths(Options.Create(_globalSettings), hostingEnvironment); Assert.AreEqual(expected, umbracoRequestPaths.IsBackOfficeRequest(source.AbsolutePath)); } - + [TestCase("http://www.domain.com/install", true)] [TestCase("http://www.domain.com/Install/", true)] [TestCase("http://www.domain.com/install/default.aspx", true)] diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj index 1e774f4b00..88ff4a67ce 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj @@ -30,4 +30,12 @@ + + + + + + + + diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs index d8e5a04c59..2e400aa8c5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs @@ -2,12 +2,13 @@ // See LICENSE for more details. using AutoFixture.NUnit3; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using Umbraco.Core.Security; using Umbraco.Tests.UnitTests.AutoFixture; using Umbraco.Web.BackOffice.Controllers; -using Umbraco.Web.Common.Exceptions; namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Controllers { @@ -27,7 +28,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Controllers .Setup(x => x.FindByIdAsync(It.IsAny())) .ReturnsAsync(user); - Assert.ThrowsAsync(() => sut.PostUnlockUsers(userIds)); + var result = sut.PostUnlockUsers(userIds).Result as ObjectResult; + Assert.AreEqual(StatusCodes.Status400BadRequest, result.StatusCode); } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs index fe442a023b..fcace95718 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs @@ -99,10 +99,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters .SetupGet(x => x.CurrentUser) .Returns(currentUserMock.Object); + var backofficeSecurityAccessorMock = new Mock(); + backofficeSecurityAccessorMock + .SetupGet(x => x.BackOfficeSecurity) + .Returns(backofficeSecurityMock.Object); + var serviceProviderMock = new Mock(); serviceProviderMock - .Setup(x => x.GetService(typeof(IBackOfficeSecurity))) - .Returns(backofficeSecurityMock.Object); + .Setup(x => x.GetService(typeof(IBackOfficeSecurityAccessor))) + .Returns(backofficeSecurityAccessorMock.Object); httpContext.RequestServices = serviceProviderMock.Object; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs index 90f491b15f..e24169455c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs @@ -313,7 +313,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views { public override Task ExecuteAsync() => throw new NotImplementedException(); - public void SetViewData(ViewDataDictionary viewData) => ViewData = (ViewDataDictionary)BindViewData(viewData); + public void SetViewData(ViewDataDictionary viewData) => ViewData = (ViewDataDictionary)BindViewData(Context, viewData); } public class RenderModelTestPage : TestPage diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs index 0b9e1d6420..a531c77fe1 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformerTests.cs @@ -10,7 +10,6 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration.Models; -using Umbraco.Core.Models.PublishedContent; using Umbraco.Extensions; using Umbraco.Tests.TestHelpers; using Umbraco.Web; @@ -84,7 +83,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Routing public async Task Noop_When_Runtime_Level_Not_Run() { UmbracoRouteValueTransformer transformer = GetTransformer( - Mock.Of(x => x.UmbracoContext == null), + Mock.Of(), Mock.Of()); RouteValueDictionary result = await transformer.TransformAsync(new DefaultHttpContext(), new RouteValueDictionary()); @@ -95,7 +94,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Routing public async Task Noop_When_No_Umbraco_Context() { UmbracoRouteValueTransformer transformer = GetTransformerWithRunState( - Mock.Of(x => x.UmbracoContext == null)); + Mock.Of()); RouteValueDictionary result = await transformer.TransformAsync(new DefaultHttpContext(), new RouteValueDictionary()); Assert.AreEqual(0, result.Count); diff --git a/src/Umbraco.Tests/Models/RangeTests.cs b/src/Umbraco.Tests/Models/RangeTests.cs new file mode 100644 index 0000000000..3fb4e8708b --- /dev/null +++ b/src/Umbraco.Tests/Models/RangeTests.cs @@ -0,0 +1,179 @@ +using System.Globalization; +using NUnit.Framework; +using Umbraco.Core.Models; + +namespace Umbraco.Tests.Models +{ + [TestFixture] + public class RangeTests + { + [TestCase(0, 0, "0,0")] + [TestCase(0, 1, "0,1")] + [TestCase(1, 1, "1,1")] + public void RangeInt32_ToString(int minimum, int maximum, string expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.ToString()); + } + + [TestCase(0, 0.5, "0,0.5")] + [TestCase(0.5, 0.5, "0.5,0.5")] + [TestCase(0.5, 1, "0.5,1")] + public void RangeDouble_ToString(double minimum, double maximum, string expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.ToString()); + } + + [TestCase(0, 0, "0")] + [TestCase(0, 1, "0,1")] + [TestCase(1, 1, "1")] + public void RangeInt32_ToStringFormatRange(int minimum, int maximum, string expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.ToString("{0}", "{0},{1}", CultureInfo.InvariantCulture)); + } + + [TestCase(0, 0.5, "0,0.5")] + [TestCase(0.5, 0.5, "0.5")] + [TestCase(0.5, 1, "0.5,1")] + public void RangeDouble_ToStringFormatRange(double minimum, double maximum, string expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.ToString("{0}", "{0},{1}", CultureInfo.InvariantCulture)); + } + + [TestCase(0, 0, "0,0")] + [TestCase(0, 1, "0,1")] + [TestCase(1, 1, "1,1")] + public void RangeInt32_ToStringFormat(int minimum, int maximum, string expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.ToString("{0},{1}", CultureInfo.InvariantCulture)); + } + + [TestCase(0, 0.5, "0,0.5")] + [TestCase(0.5, 0.5, "0.5,0.5")] + [TestCase(0.5, 1, "0.5,1")] + public void RangeDouble_ToStringFormat(double minimum, double maximum, string expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.ToString("{0},{1}", CultureInfo.InvariantCulture)); + } + + [TestCase(0, 0, true)] + [TestCase(0, 1, true)] + [TestCase(-1, 1, true)] + [TestCase(1, 0, false)] + [TestCase(0, -1, false)] + public void RangeInt32_IsValid(int minimum, int maximum, bool expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.IsValid()); + } + + [TestCase(0, 0, 0, true)] + [TestCase(0, 1, 0, true)] + [TestCase(0, 1, 1, true)] + [TestCase(-1, 1, 0, true)] + [TestCase(0, 0, 1, false)] + [TestCase(0, 0, -1, false)] + public void RangeInt32_ContainsValue(int minimum, int maximum, int value, bool expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum, + Maximum = maximum + }.ContainsValue(value)); + } + + [TestCase(0, 0, 0, 0, true)] + [TestCase(0, 1, 0, 1, true)] + [TestCase(0, 1, 1, 1, false)] + [TestCase(-1, 1, 0, 0, false)] + [TestCase(0, 0, 1, 1, false)] + [TestCase(0, 0, -1, 1, true)] + public void RangeInt32_IsInsideRange(int minimum1, int maximum1, int minimum2, int maximum2, bool expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum1, + Maximum = maximum1 + }.IsInsideRange(new Range() + { + Minimum = minimum2, + Maximum = maximum2 + })); + } + + [TestCase(0, 0, 0, 0, true)] + [TestCase(0, 1, 0, 1, true)] + [TestCase(0, 1, 1, 1, true)] + [TestCase(-1, 1, 0, 0, true)] + [TestCase(0, 0, 1, 1, false)] + [TestCase(0, 0, -1, 1, false)] + public void RangeInt32_ContainsRange(int minimum1, int maximum1, int minimum2, int maximum2, bool expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum1, + Maximum = maximum1 + }.ContainsRange(new Range() + { + Minimum = minimum2, + Maximum = maximum2 + })); + } + + [TestCase(0, 0, 0, 0, true)] + [TestCase(0, 1, 0, 1, true)] + [TestCase(0, 1, 1, 1, false)] + [TestCase(0, 0, 1, 1, false)] + public void RangeInt32_Equals(int minimum1, int maximum1, int minimum2, int maximum2, bool expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum1, + Maximum = maximum1 + }.Equals(new Range() + { + Minimum = minimum2, + Maximum = maximum2 + })); + } + + [TestCase(0, 0, 0, 0, true)] + [TestCase(0, 1, 0, 1, true)] + [TestCase(0, 1, 1, 1, false)] + [TestCase(0, 0, 1, 1, false)] + public void RangeInt32_EqualsValues(int minimum1, int maximum1, int minimum2, int maximum2, bool expected) + { + Assert.AreEqual(expected, new Range() + { + Minimum = minimum1, + Maximum = maximum1 + }.Equals(minimum2, maximum2)); + } + } +} diff --git a/src/Umbraco.Tests/Persistence/FaultHandling/ConnectionRetryTest.cs b/src/Umbraco.Tests/Persistence/FaultHandling/ConnectionRetryTest.cs index fd3b525039..5409b1d493 100644 --- a/src/Umbraco.Tests/Persistence/FaultHandling/ConnectionRetryTest.cs +++ b/src/Umbraco.Tests/Persistence/FaultHandling/ConnectionRetryTest.cs @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Persistence.FaultHandling { const string connectionString = @"server=.\SQLEXPRESS;database=EmptyForTest;user id=x;password=umbraco"; const string providerName = Constants.DbProviderNames.SqlServer; - var factory = new UmbracoDatabaseFactory(Mock.Of>(), NullLoggerFactory.Instance, connectionString, providerName, new Lazy(() => Mock.Of()), TestHelper.DbProviderFactoryCreator); + var factory = new UmbracoDatabaseFactory(Mock.Of>(), NullLoggerFactory.Instance, connectionString, providerName, new Lazy(() => Mock.Of()), TestHelper.DbProviderFactoryCreator, TestHelper.DatabaseSchemaCreatorFactory); using (var database = factory.CreateDatabase()) { @@ -35,7 +35,7 @@ namespace Umbraco.Tests.Persistence.FaultHandling { const string connectionString = @"server=.\SQLEXPRESS;database=EmptyForTest;user id=umbraco;password=umbraco"; const string providerName = Constants.DbProviderNames.SqlServer; - var factory = new UmbracoDatabaseFactory(Mock.Of>(), NullLoggerFactory.Instance, connectionString, providerName, new Lazy(() => Mock.Of()), TestHelper.DbProviderFactoryCreator); + var factory = new UmbracoDatabaseFactory(Mock.Of>(), NullLoggerFactory.Instance, connectionString, providerName, new Lazy(() => Mock.Of()), TestHelper.DbProviderFactoryCreator, TestHelper.DatabaseSchemaCreatorFactory); using (var database = factory.CreateDatabase()) { diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index 71809d063a..63b3b13e13 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -25,10 +25,9 @@ using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using Umbraco.Web; using Umbraco.Web.Cache; +using Umbraco.Web.Composing; using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.NuCache; -using Umbraco.Web.PublishedCache.NuCache.DataSource; -using Current = Umbraco.Web.Composing.Current; namespace Umbraco.Tests.Scoping { @@ -106,8 +105,6 @@ namespace Umbraco.Tests.Scoping hostingEnvironment, Microsoft.Extensions.Options.Options.Create(nuCacheSettings)); - lifetime.Raise(e => e.ApplicationInit += null, EventArgs.Empty); - return snapshotService; } diff --git a/src/Umbraco.Tests/TestHelpers/TestHelper.cs b/src/Umbraco.Tests/TestHelpers/TestHelper.cs index 8c89905c97..8a3d4a6297 100644 --- a/src/Umbraco.Tests/TestHelpers/TestHelper.cs +++ b/src/Umbraco.Tests/TestHelpers/TestHelper.cs @@ -37,9 +37,11 @@ using File = System.IO.File; using Umbraco.Tests.Common.Builders; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Umbraco.Core.Configuration.Models; using Umbraco.Core.DependencyInjection; using Umbraco.Core.Mail; +using Umbraco.Core.Migrations.Install; namespace Umbraco.Tests.TestHelpers { @@ -59,6 +61,7 @@ namespace Umbraco.Tests.TestHelpers } public override IDbProviderFactoryCreator DbProviderFactoryCreator { get; } = new UmbracoDbProviderFactoryCreator(); + public DatabaseSchemaCreatorFactory DatabaseSchemaCreatorFactory { get; } = new DatabaseSchemaCreatorFactory(Mock.Of>(), NullLoggerFactory.Instance, new UmbracoVersion()); public override IBulkSqlInsertProvider BulkSqlInsertProvider { get; } = new SqlCeBulkSqlInsertProvider(); @@ -99,6 +102,7 @@ namespace Umbraco.Tests.TestHelpers public static IJsonSerializer JsonSerializer => _testHelperInternal.JsonSerializer; public static IVariationContextAccessor VariationContextAccessor => _testHelperInternal.VariationContextAccessor; public static IDbProviderFactoryCreator DbProviderFactoryCreator => _testHelperInternal.DbProviderFactoryCreator; + public static DatabaseSchemaCreatorFactory DatabaseSchemaCreatorFactory => _testHelperInternal.DatabaseSchemaCreatorFactory; public static IBulkSqlInsertProvider BulkSqlInsertProvider => _testHelperInternal.BulkSqlInsertProvider; public static IMarchal Marchal => _testHelperInternal.Marchal; public static CoreDebugSettings CoreDebugSettings => _testHelperInternal.CoreDebugSettings; diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index 3b17861fb3..21c66f8922 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -10,6 +10,7 @@ using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.SqlSyntax; @@ -78,7 +79,8 @@ namespace Umbraco.Tests.TestHelpers globalSettings, connectionStrings, new Lazy(() => mappers), - TestHelper.DbProviderFactoryCreator); + TestHelper.DbProviderFactoryCreator, + new DatabaseSchemaCreatorFactory(Mock.Of>(),loggerFactory, new UmbracoVersion())); } fileSystems ??= new FileSystems(Current.Factory, loggerFactory.CreateLogger(), loggerFactory, TestHelper.IOHelper, Options.Create(globalSettings), TestHelper.GetHostingEnvironment()); diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index b47da98709..f8a6e132a9 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -91,7 +91,7 @@ namespace Umbraco.Tests.TestHelpers return TestObjects.GetDatabaseFactoryMock(); var lazyMappers = new Lazy(f.GetRequiredService); - var factory = new UmbracoDatabaseFactory(f.GetRequiredService>(), f.GetRequiredService(), GetDbConnectionString(), GetDbProviderName(), lazyMappers, TestHelper.DbProviderFactoryCreator); + var factory = new UmbracoDatabaseFactory(f.GetRequiredService>(), f.GetRequiredService(), GetDbConnectionString(), GetDbProviderName(), lazyMappers, TestHelper.DbProviderFactoryCreator, f.GetRequiredService()); return factory; }); } diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index 433ef1de02..78f9fc3013 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -31,6 +31,7 @@ using Umbraco.Core.Mail; using Umbraco.Core.Manifest; using Umbraco.Core.Mapping; using Umbraco.Core.Media; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; @@ -487,7 +488,8 @@ namespace Umbraco.Tests.Testing globalSettings, connectionStrings, new Lazy(f.GetRequiredService), - TestHelper.DbProviderFactoryCreator)); + TestHelper.DbProviderFactoryCreator, + new DatabaseSchemaCreatorFactory(LoggerFactory.CreateLogger(), LoggerFactory, UmbracoVersion))); Builder.Services.AddUnique(f => f.GetService().SqlContext); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index fe9d41f681..d84908062d 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -117,6 +117,12 @@ + + + + + + @@ -145,6 +151,8 @@ + + @@ -306,9 +314,6 @@ - - - $(NuGetPackageFolders.Split(';')[0]) diff --git a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs index 502ffbcba2..11931b5f47 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; @@ -28,12 +27,10 @@ using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Common.Controllers; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Common.Filters; using Umbraco.Web.Common.Security; using Umbraco.Web.Models; using Umbraco.Web.Models.ContentEditing; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Controllers { @@ -117,11 +114,15 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// Returns the configuration for the backoffice user membership provider - used to configure the change password dialog /// - /// - [Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)] + [AllowAnonymous] // Needed for users that are invited when they use the link from the mail they are not authorized + [Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)] // Needed to enforce the principle set on the request, if one exists. public IDictionary GetPasswordConfig(int userId) { - return _passwordConfiguration.GetConfiguration(userId != _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); + Attempt currentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId(); + return _passwordConfiguration.GetConfiguration( + currentUserId.Success + ? currentUserId.Result != userId + : true); } /// @@ -152,7 +153,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (result.Succeeded == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Errors.ToErrorMessage()); + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Errors.ToErrorMessage()); } await _signInManager.SignOutAsync(); @@ -208,7 +209,7 @@ namespace Umbraco.Web.BackOffice.Controllers else { AddModelErrors(result); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } } @@ -351,7 +352,7 @@ namespace Umbraco.Web.BackOffice.Controllers // by our angular helper because it thinks that we need to re-perform the request once we are // authorized and we don't want to return a 403 because angular will show a warning message indicating // that the user doesn't have access to perform this function, we just want to return a normal invalid message. - throw new HttpResponseException(HttpStatusCode.BadRequest); + return BadRequest(); } /// @@ -469,7 +470,7 @@ namespace Umbraco.Web.BackOffice.Controllers { if (ModelState.IsValid == false) { - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); diff --git a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs index 07f20e1e03..066f6e3463 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs @@ -91,7 +91,7 @@ namespace Umbraco.Web.BackOffice.Controllers var keepOnlyKeys = new Dictionary { {"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl", "previewHubUrl"}}, - {"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "canSendRequiredEmail", "usernameIsEmail"}}, + {"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "loginLogoImage", "canSendRequiredEmail", "usernameIsEmail"}}, {"application", new[] {"applicationPath", "cacheBuster"}}, {"isDebuggingEnabled", new string[] { }}, {"features", new [] {"disabledFeatures"}} @@ -394,6 +394,7 @@ namespace Umbraco.Web.BackOffice.Controllers {"cssPath", _hostingEnvironment.ToAbsolute(globalSettings.UmbracoCssPath).TrimEnd('/')}, {"allowPasswordReset", _securitySettings.AllowPasswordReset}, {"loginBackgroundImage", _contentSettings.LoginBackgroundImage}, + {"loginLogoImage", _contentSettings.LoginLogoImage }, {"showUserInvite", EmailSender.CanSendRequiredEmail(globalSettings)}, {"canSendRequiredEmail", EmailSender.CanSendRequiredEmail(globalSettings)}, {"showAllowSegmentationForDocumentTypes", false}, diff --git a/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs b/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs index d1feaf11e9..e2ec2fecd7 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -21,7 +21,6 @@ using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; using Stylesheet = Umbraco.Core.Models.Stylesheet; using StylesheetRule = Umbraco.Web.Models.ContentEditing.StylesheetRule; @@ -84,13 +83,19 @@ namespace Umbraco.Web.BackOffice.Controllers var view = new PartialView(PartialViewType.PartialView, display.VirtualPath); view.Content = display.Content; var result = _fileService.CreatePartialView(view, display.Snippet, currentUser.Id); - return result.Success == true ? Ok() : throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Exception.Message); + if (result.Success) + return Ok(); + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Exception.Message); case Core.Constants.Trees.PartialViewMacros: var viewMacro = new PartialView(PartialViewType.PartialViewMacro, display.VirtualPath); viewMacro.Content = display.Content; var resultMacro = _fileService.CreatePartialViewMacro(viewMacro, display.Snippet, currentUser.Id); - return resultMacro.Success == true ? Ok() : throw HttpResponseException.CreateNotificationValidationErrorResponse(resultMacro.Exception.Message); + if (resultMacro.Success) + return Ok(); + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(resultMacro.Exception.Message); case Core.Constants.Trees.Scripts: var script = new Script(display.VirtualPath); @@ -116,7 +121,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (string.IsNullOrWhiteSpace(parentId)) throw new ArgumentException("Value cannot be null or whitespace.", "parentId"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); if (name.ContainsAny(Path.GetInvalidPathChars())) { - throw HttpResponseException.CreateNotificationValidationErrorResponse(_localizedTextService.Localize("codefile/createFolderIllegalChars")); + return ValidationErrorResult.CreateNotificationValidationErrorResult(_localizedTextService.Localize("codefile/createFolderIllegalChars")); } // if the parentId is root (-1) then we just need an empty string as we are @@ -233,7 +238,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// This is a string but will be 'partialViews', 'partialViewMacros' /// Returns a list of if a correct type is sent - public IEnumerable GetSnippets(string type) + public ActionResult> GetSnippets(string type) { if (string.IsNullOrWhiteSpace(type)) throw new ArgumentException("Value cannot be null or whitespace.", "type"); @@ -252,10 +257,10 @@ namespace Umbraco.Web.BackOffice.Controllers snippets = _fileService.GetPartialViewSnippetNames(); break; default: - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } - return snippets.Select(snippet => new SnippetDisplay() {Name = snippet.SplitPascalCasing(_shortStringHelper).ToFirstUpperInvariant(), FileName = snippet}); + return snippets.Select(snippet => new SnippetDisplay() { Name = snippet.SplitPascalCasing(_shortStringHelper).ToFirstUpperInvariant(), FileName = snippet }).ToList(); } /// diff --git a/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs b/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs index 4a9bf52605..eb7cf7e411 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs @@ -2,9 +2,10 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Net.Mime; using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; @@ -14,7 +15,6 @@ using Umbraco.Core.Events; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Models.ContentEditing; -using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Validation; using Umbraco.Core.Persistence; @@ -24,23 +24,19 @@ using Umbraco.Core.Security; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Core.Strings; -using Umbraco.Web.Actions; -using Umbraco.Web.ContentApps; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Routing; -using Constants = Umbraco.Core.Constants; using Umbraco.Extensions; +using Umbraco.Web.Actions; +using Umbraco.Web.BackOffice.ActionResults; +using Umbraco.Web.BackOffice.Authorization; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.BackOffice.ModelBinders; -using Umbraco.Web.BackOffice.ActionResults; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.Common.Filters; -using Umbraco.Web.Models.Mapping; -using Microsoft.AspNetCore.Authorization; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.BackOffice.Authorization; -using System.Threading.Tasks; +using Umbraco.Web.ContentApps; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Mapping; +using Umbraco.Web.Routing; namespace Umbraco.Web.BackOffice.Controllers { @@ -337,13 +333,12 @@ namespace Umbraco.Web.BackOffice.Controllers [OutgoingEditorModelEvent] [Authorize(Policy = AuthorizationPolicies.ContentPermissionBrowseById)] [DetermineAmbiguousActionByPassingParameters] - public ContentItemDisplay GetById(int id) + public ActionResult GetById(int id) { var foundContent = GetObjectFromRequest(() => _contentService.GetById(id)); if (foundContent == null) { - HandleContentNotFound(id); - return null;//irrelevant since the above throws + return HandleContentNotFound(id); } var content = MapToDisplay(foundContent); return content; @@ -357,13 +352,12 @@ namespace Umbraco.Web.BackOffice.Controllers [OutgoingEditorModelEvent] [Authorize(Policy = AuthorizationPolicies.ContentPermissionBrowseById)] [DetermineAmbiguousActionByPassingParameters] - public ContentItemDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var foundContent = GetObjectFromRequest(() => _contentService.GetById(id)); if (foundContent == null) { - HandleContentNotFound(id); - return null;//irrelevant since the above throws + return HandleContentNotFound(id); } var content = MapToDisplay(foundContent); @@ -378,7 +372,7 @@ namespace Umbraco.Web.BackOffice.Controllers [OutgoingEditorModelEvent] [Authorize(Policy = AuthorizationPolicies.ContentPermissionBrowseById)] [DetermineAmbiguousActionByPassingParameters] - public ContentItemDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi != null) @@ -386,7 +380,7 @@ namespace Umbraco.Web.BackOffice.Controllers return GetById(guidUdi.Guid); } - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } /// @@ -396,12 +390,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// [OutgoingEditorModelEvent] [DetermineAmbiguousActionByPassingParameters] - public ContentItemDisplay GetEmpty(string contentTypeAlias, int parentId) + public ActionResult GetEmpty(string contentTypeAlias, int parentId) { var contentType = _contentTypeService.Get(contentTypeAlias); if (contentType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return GetEmpty(contentType, parentId); @@ -414,12 +408,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [OutgoingEditorModelEvent] - public ContentItemDisplay GetEmptyByKey(Guid contentTypeKey, int parentId) + public ActionResult GetEmptyByKey(Guid contentTypeKey, int parentId) { var contentType = _contentTypeService.Get(contentTypeKey); if (contentType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return GetEmpty(contentType, parentId); @@ -443,12 +437,12 @@ namespace Umbraco.Web.BackOffice.Controllers [OutgoingEditorModelEvent] [DetermineAmbiguousActionByPassingParameters] - public ContentItemDisplay GetEmpty(int blueprintId, int parentId) + public ActionResult GetEmpty(int blueprintId, int parentId) { var blueprint = _contentService.GetBlueprintById(blueprintId); if (blueprint == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } blueprint.Id = 0; @@ -592,9 +586,14 @@ namespace Umbraco.Web.BackOffice.Controllers var content = _contentService.GetById(contentId); if (content == null) + { return NotFound(); + } - EnsureUniqueName(name, content, nameof(name)); + if (!EnsureUniqueName(name, content, nameof(name))) + { + return new ValidationErrorResult(ModelState.ToErrorDictionary()); + } var blueprint = _contentService.CreateContentFromBlueprint(content, name, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); @@ -609,14 +608,16 @@ namespace Umbraco.Web.BackOffice.Controllers return notificationModel; } - private void EnsureUniqueName(string name, IContent content, string modelName) + private bool EnsureUniqueName(string name, IContent content, string modelName) { var existing = _contentService.GetBlueprintsForContentTypes(content.ContentTypeId); if (existing.Any(x => x.Name == name && x.Id != content.Id)) { ModelState.AddModelError(modelName, _localizedTextService.Localize("blueprints/duplicateBlueprintMessage")); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return false; } + + return true; } /// @@ -624,13 +625,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// [FileUploadCleanupFilter] [ContentSaveValidation] - public async Task PostSaveBlueprint([ModelBinder(typeof(BlueprintItemBinder))] ContentItemSave contentItem) + public async Task> PostSaveBlueprint([ModelBinder(typeof(BlueprintItemBinder))] ContentItemSave contentItem) { var contentItemDisplay = await PostSaveInternal( contentItem, content => { - EnsureUniqueName(content.Name, content, "Name"); + if (!EnsureUniqueName(content.Name, content, "Name")) + { + return OperationResult.Cancel(new EventMessages()); + } _contentService.SaveBlueprint(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); @@ -653,7 +657,7 @@ namespace Umbraco.Web.BackOffice.Controllers [FileUploadCleanupFilter] [ContentSaveValidation] [OutgoingEditorModelEvent] - public async Task PostSave([ModelBinder(typeof(ContentItemBinder))] ContentItemSave contentItem) + public async Task> PostSave([ModelBinder(typeof(ContentItemBinder))] ContentItemSave contentItem) { var contentItemDisplay = await PostSaveInternal( contentItem, @@ -663,7 +667,7 @@ namespace Umbraco.Web.BackOffice.Controllers return contentItemDisplay; } - private async Task PostSaveInternal(ContentItemSave contentItem, Func saveMethod, Func mapToDisplay) + private async Task> PostSaveInternal(ContentItemSave contentItem, Func saveMethod, Func mapToDisplay) { // Recent versions of IE/Edge may send in the full client side file path instead of just the file name. // To ensure similar behavior across all browsers no matter what they do - we strip the FileName property of all @@ -696,7 +700,7 @@ namespace Umbraco.Web.BackOffice.Controllers // add the model state to the outgoing object and throw a validation message var forDisplay = mapToDisplay(contentItem.PersistedContent); forDisplay.Errors = ModelState.ToErrorDictionary(); - throw HttpResponseException.CreateValidationErrorResponse(forDisplay); + return new ValidationErrorResult(forDisplay); } // if there's only one variant and the model state is not valid we cannot publish so change it to save @@ -734,7 +738,7 @@ namespace Umbraco.Web.BackOffice.Controllers //The default validation language will be either: The default languauge, else if the content is brand new and the default culture is // not marked to be saved, it will be the first culture in the list marked for saving. - var defaultCulture = _allLangs.Value.Values.FirstOrDefault(x => x.IsDefault)?.CultureName; + var defaultCulture = _allLangs.Value.Values.FirstOrDefault(x => x.IsDefault)?.IsoCode; var cultureForInvariantErrors = CultureImpact.GetCultureForInvariantErrors( contentItem.PersistedContent, contentItem.Variants.Where(x => x.Save).Select(x => x.Culture).ToArray(), @@ -842,9 +846,15 @@ namespace Umbraco.Web.BackOffice.Controllers v.Notifications.AddRange(n.Notifications); } - //lastly, if it is not valid, add the model state to the outgoing object and throw a 400 HandleInvalidModelState(display, cultureForInvariantErrors); + //lastly, if it is not valid, add the model state to the outgoing object and throw a 400 + if (!ModelState.IsValid) + { + display.Errors = ModelState.ToErrorDictionary(); + return new ValidationErrorResult(display); + } + if (wasCancelled) { AddCancelMessage(display); @@ -853,7 +863,7 @@ namespace Umbraco.Web.BackOffice.Controllers //If the item is new and the operation was cancelled, we need to return a different // status code so the UI can handle it since it won't be able to redirect since there // is no Id to redirect to! - throw HttpResponseException.CreateValidationErrorResponse(display); + return new ValidationErrorResult(display); } } @@ -1475,7 +1485,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (foundContent == null) { - return HandleContentNotFound(id, false); + return HandleContentNotFound(id); } var publishResult = _contentService.SaveAndPublish(foundContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); @@ -1483,7 +1493,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var notificationModel = new SimpleNotificationModel(); AddMessageForPublishStatus(new[] { publishResult }, notificationModel); - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); } return Ok(); @@ -1498,7 +1508,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (found == null) { - return HandleContentNotFound(id, false); + return HandleContentNotFound(id); } _contentService.DeleteBlueprint(found); @@ -1524,7 +1534,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (foundContent == null) { - return HandleContentNotFound(id, false); + return HandleContentNotFound(id); } //if the current item is in the recycle bin @@ -1535,7 +1545,7 @@ namespace Umbraco.Web.BackOffice.Controllers { //returning an object of INotificationModel will ensure that any pending // notification messages are added to the response. - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); } } else @@ -1545,7 +1555,7 @@ namespace Umbraco.Web.BackOffice.Controllers { //returning an object of INotificationModel will ensure that any pending // notification messages are added to the response. - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); } } @@ -1603,7 +1613,7 @@ namespace Umbraco.Web.BackOffice.Controllers { _logger.LogWarning("Content sorting failed, this was probably caused by an event being cancelled"); // TODO: Now you can cancel sorting, does the event messages bubble up automatically? - throw HttpResponseException.CreateValidationErrorResponse("Content sorting failed, this was probably caused by an event being cancelled"); + return new ValidationErrorResult("Content sorting failed, this was probably caused by an event being cancelled"); } return Ok(); @@ -1630,7 +1640,12 @@ namespace Umbraco.Web.BackOffice.Controllers return Forbid(); } - var toMove = ValidateMoveOrCopy(move); + var toMoveResult = ValidateMoveOrCopy(move); + if (!(toMoveResult is null)) + { + return toMoveResult.Result; + } + var toMove = toMoveResult.Value; _contentService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); @@ -1642,7 +1657,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - public async Task PostCopy(MoveOrCopy copy) + public async Task> PostCopy(MoveOrCopy copy) { // Authorize... var resource = new ContentPermissionsResource(_contentService.GetById(copy.ParentId), ActionCopy.ActionLetter); @@ -1652,8 +1667,12 @@ namespace Umbraco.Web.BackOffice.Controllers return Forbid(); } - var toCopy = ValidateMoveOrCopy(copy); - + var toCopyResult = ValidateMoveOrCopy(copy); + if ((toCopyResult.Result is null)) + { + return toCopyResult.Result; + } + var toCopy = toCopyResult.Value; var c = _contentService.Copy(toCopy, copy.ParentId, copy.RelateToOriginal, copy.Recursive, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); return Content(c.Path, MediaTypeNames.Text.Plain, Encoding.UTF8); @@ -1671,7 +1690,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (foundContent == null) { - HandleContentNotFound(model.Id); + return HandleContentNotFound(model.Id); } // Authorize... @@ -1693,7 +1712,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (!unpublishResult.Success) { AddCancelMessage(content); - throw HttpResponseException.CreateValidationErrorResponse(content); + return new ValidationErrorResult(content); } else { @@ -1765,7 +1784,7 @@ namespace Umbraco.Web.BackOffice.Controllers } catch (UriFormatException) { - throw HttpResponseException.CreateValidationErrorResponse(_localizedTextService.Localize("assignDomain/invalidDomain")); + return new ValidationErrorResult(_localizedTextService.Localize("assignDomain/invalidDomain")); } } @@ -1918,9 +1937,6 @@ namespace Umbraco.Web.BackOffice.Controllers AddVariantValidationError(culture, segment, "speechBubbles/contentCultureValidationError"); } } - - base.HandleInvalidModelState(display); - } /// @@ -2020,25 +2036,25 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - private IContent ValidateMoveOrCopy(MoveOrCopy model) + private ActionResult ValidateMoveOrCopy(MoveOrCopy model) { if (model == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var contentService = _contentService; var toMove = contentService.GetById(model.Id); if (toMove == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } if (model.ParentId < 0) { //cannot move if the content item is not allowed at the root if (toMove.ContentType.AllowedAsRoot == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse( + return ValidationErrorResult.CreateNotificationValidationErrorResult( _localizedTextService.Localize("moveOrCopy/notAllowedAtRoot")); } } @@ -2047,7 +2063,7 @@ namespace Umbraco.Web.BackOffice.Controllers var parent = contentService.GetById(model.ParentId); if (parent == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var parentContentType = _contentTypeService.Get(parent.ContentTypeId); @@ -2055,19 +2071,19 @@ namespace Umbraco.Web.BackOffice.Controllers if (parentContentType.AllowedContentTypes.Select(x => x.Id).ToArray() .Any(x => x.Value == toMove.ContentType.Id) == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse( + return ValidationErrorResult.CreateNotificationValidationErrorResult( _localizedTextService.Localize("moveOrCopy/notAllowedByContentType")); } // Check on paths - if ((string.Format(",{0},", parent.Path)).IndexOf(string.Format(",{0},", toMove.Id), StringComparison.Ordinal) > -1) + if ($",{parent.Path},".IndexOf($",{toMove.Id},", StringComparison.Ordinal) > -1) { - throw HttpResponseException.CreateNotificationValidationErrorResponse( + return ValidationErrorResult.CreateNotificationValidationErrorResult( _localizedTextService.Localize("moveOrCopy/notAllowedByPath")); } } - return toMove; + return new ActionResult(toMove); } /// @@ -2392,7 +2408,7 @@ namespace Umbraco.Web.BackOffice.Controllers break; } - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); } [Authorize(Policy = AuthorizationPolicies.ContentPermissionProtectById)] diff --git a/src/Umbraco.Web.BackOffice/Controllers/ContentControllerBase.cs b/src/Umbraco.Web.BackOffice/Controllers/ContentControllerBase.cs index 50012c7921..75d62f1863 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ContentControllerBase.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ContentControllerBase.cs @@ -1,23 +1,16 @@ using System; using System.Linq; -using System.Net; -using System.Net.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; using Umbraco.Core.Dictionary; using Umbraco.Core.Events; -using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Models.Editors; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Core.Strings; -using Umbraco.Extensions; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Common.Filters; using Umbraco.Web.Models.ContentEditing; @@ -77,14 +70,10 @@ namespace Umbraco.Web.BackOffice.Controllers /// protected ILocalizedTextService LocalizedTextService { get; } - protected NotFoundObjectResult HandleContentNotFound(object id, bool throwException = true) + protected NotFoundObjectResult HandleContentNotFound(object id) { ModelState.AddModelError("id", $"content with id: {id} was not found"); var errorResponse = NotFound(ModelState); - if (throwException) - { - throw new HttpResponseException(errorResponse); - } return errorResponse; } @@ -151,16 +140,6 @@ namespace Umbraco.Web.BackOffice.Controllers } } - protected virtual void HandleInvalidModelState(IErrorModel display) - { - //lastly, if it is not valid, add the model state to the outgoing object and throw a 403 - if (!ModelState.IsValid) - { - display.Errors = ModelState.ToErrorDictionary(); - throw HttpResponseException.CreateValidationErrorResponse(display); - } - } - /// /// A helper method to attempt to get the instance from the request storage if it can be found there, /// otherwise gets it from the callback specified diff --git a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs index 50be27a108..ea34005a87 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Net.Mime; using System.Text; using System.Xml; @@ -21,9 +20,9 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.Strings; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Editors; using Umbraco.Web.Models; using Umbraco.Web.Models.ContentEditing; @@ -116,12 +115,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// [DetermineAmbiguousActionByPassingParameters] [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] - public DocumentTypeDisplay GetById(int id) + public ActionResult GetById(int id) { var ct = _contentTypeService.Get(id); if (ct == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(ct); @@ -133,12 +132,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// [DetermineAmbiguousActionByPassingParameters] [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] - public DocumentTypeDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var contentType = _contentTypeService.Get(id); if (contentType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(contentType); @@ -150,16 +149,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// [DetermineAmbiguousActionByPassingParameters] [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] - public DocumentTypeDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var contentType = _contentTypeService.Get(guidUdi.Guid); if (contentType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(contentType); @@ -177,7 +176,7 @@ namespace Umbraco.Web.BackOffice.Controllers var foundType = _contentTypeService.Get(id); if (foundType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } _contentTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); @@ -209,9 +208,18 @@ namespace Umbraco.Web.BackOffice.Controllers ///
[HttpPost] [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] - public IActionResult GetAvailableCompositeContentTypes(GetAvailableCompositionsFilter filter) + public ActionResult GetAvailableCompositeContentTypes(GetAvailableCompositionsFilter filter) { - var result = PerformGetAvailableCompositeContentTypes(filter.ContentTypeId, UmbracoObjectTypes.DocumentType, filter.FilterContentTypes, filter.FilterPropertyTypes, filter.IsElement) + var actionResult = PerformGetAvailableCompositeContentTypes(filter.ContentTypeId, + UmbracoObjectTypes.DocumentType, filter.FilterContentTypes, filter.FilterPropertyTypes, + filter.IsElement); + + if (!(actionResult.Result is null)) + { + return actionResult.Result; + } + + var result = actionResult.Value .Select(x => new { contentType = x.Item1, @@ -239,7 +247,7 @@ namespace Umbraco.Web.BackOffice.Controllers [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] public IActionResult GetWhereCompositionIsUsedInContentTypes(GetAvailableCompositionsFilter filter) { - var result = PerformGetWhereCompositionIsUsedInContentTypes(filter.ContentTypeId, UmbracoObjectTypes.DocumentType) + var result = PerformGetWhereCompositionIsUsedInContentTypes(filter.ContentTypeId, UmbracoObjectTypes.DocumentType).Value .Select(x => new { contentType = x @@ -248,13 +256,13 @@ namespace Umbraco.Web.BackOffice.Controllers } [Authorize(Policy = AuthorizationPolicies.TreeAccessAnyContentOrTypes)] - public ContentPropertyDisplay GetPropertyTypeScaffold(int id) + public ActionResult GetPropertyTypeScaffold(int id) { var dataTypeDiff = _dataTypeService.GetDataType(id); if (dataTypeDiff == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var configuration = _dataTypeService.GetDataType(id).Configuration; @@ -287,9 +295,10 @@ namespace Umbraco.Web.BackOffice.Controllers { var result = _contentTypeService.CreateContainer(parentId, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); - return result - ? Ok(result.Result) //return the id - : throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Exception.Message); + if (result.Success) + return Ok(result.Result); //return the id + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Exception.Message); } [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] @@ -297,9 +306,10 @@ namespace Umbraco.Web.BackOffice.Controllers { var result = _contentTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); - return result - ? Ok(result.Result) //return the id - : throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Exception.Message); + if (result.Success) + return Ok(result.Result); //return the id + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Exception.Message); } [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] @@ -360,7 +370,7 @@ namespace Umbraco.Web.BackOffice.Controllers } [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)] - public DocumentTypeDisplay PostSave(DocumentTypeSave contentTypeSave) + public ActionResult PostSave(DocumentTypeSave contentTypeSave) { //Before we send this model into this saving/mapping pipeline, we need to do some cleanup on variations. //If the doc type does not allow content variations, we need to update all of it's property types to not allow this either @@ -403,7 +413,13 @@ namespace Umbraco.Web.BackOffice.Controllers } }); - var display = _umbracoMapper.Map(savedCt); + if (!(savedCt.Result is null)) + { + return savedCt.Result; + } + + var display = _umbracoMapper.Map(savedCt.Value); + display.AddSuccessNotification( _localizedTextService.Localize("speechBubbles/contentTypeSavedHeader"), diff --git a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeControllerBase.cs b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeControllerBase.cs index 88a83ed217..fe22523ebd 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeControllerBase.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeControllerBase.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Mime; using System.Text; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.Net.Http.Headers; using Umbraco.Core; using Umbraco.Core.Dictionary; using Umbraco.Core.Exceptions; @@ -16,6 +14,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Editors; @@ -72,9 +71,9 @@ namespace Umbraco.Web.BackOffice.Controllers /// be looked up via the db, they need to be passed in. /// /// - /// Wether the composite content types should be applicable for an element type + /// Whether the composite content types should be applicable for an element type /// - protected IEnumerable> PerformGetAvailableCompositeContentTypes(int contentTypeId, + protected ActionResult>> PerformGetAvailableCompositeContentTypes(int contentTypeId, UmbracoObjectTypes type, string[] filterContentTypes, string[] filterPropertyTypes, @@ -92,7 +91,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (contentTypeId > 0) { source = ContentTypeService.Get(contentTypeId); - if (source == null) throw new HttpResponseException(HttpStatusCode.NotFound); + if (source == null) return NotFound(); } allContentTypes = ContentTypeService.GetAll().Cast().ToArray(); break; @@ -101,7 +100,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (contentTypeId > 0) { source =MediaTypeService.Get(contentTypeId); - if (source == null) throw new HttpResponseException(HttpStatusCode.NotFound); + if (source == null) return NotFound(); } allContentTypes =MediaTypeService.GetAll().Cast().ToArray(); break; @@ -110,7 +109,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (contentTypeId > 0) { source = MemberTypeService.Get(contentTypeId); - if (source == null) throw new HttpResponseException(HttpStatusCode.NotFound); + if (source == null) return NotFound(); } allContentTypes = MemberTypeService.GetAll().Cast().ToArray(); break; @@ -178,7 +177,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// Type of content Type, eg documentType or mediaType /// Id of composition content type /// - protected IEnumerable PerformGetWhereCompositionIsUsedInContentTypes(int contentTypeId, UmbracoObjectTypes type) + protected ActionResult> PerformGetWhereCompositionIsUsedInContentTypes(int contentTypeId, UmbracoObjectTypes type) { var id = 0; @@ -205,7 +204,7 @@ namespace Umbraco.Web.BackOffice.Controllers } if (source == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); id = source.Id; } @@ -254,7 +253,7 @@ namespace Umbraco.Web.BackOffice.Controllers return CultureDictionary[text].IfNullOrWhiteSpace(text); } - protected TContentType PerformPostSave( + protected ActionResult PerformPostSave( TContentTypeSave contentTypeSave, Func getContentType, Action saveContentType, @@ -265,7 +264,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var ctId = Convert.ToInt32(contentTypeSave.Id); var ct = ctId > 0 ? getContentType(ctId) : null; - if (ctId > 0 && ct == null) throw new HttpResponseException(HttpStatusCode.NotFound); + if (ctId > 0 && ct == null) return NotFound(); //Validate that there's no other ct with the same alias // it in fact cannot be the same as any content type alias (member, content or media) because @@ -283,7 +282,8 @@ namespace Umbraco.Web.BackOffice.Controllers if (ModelState.IsValid == false) { - throw CreateModelStateValidationException(ctId, contentTypeSave, ct); + var err = CreateModelStateValidationEror(ctId, contentTypeSave, ct); + return new ValidationErrorResult(err); } //filter out empty properties @@ -305,11 +305,11 @@ namespace Umbraco.Web.BackOffice.Controllers catch (Exception ex) { var responseEx = CreateInvalidCompositionResponseException(ex, contentTypeSave, ct, ctId); - if (responseEx != null) throw responseEx; + if (responseEx != null) return new ValidationErrorResult(responseEx); } var exResult = CreateCompositionValidationExceptionIfInvalid(contentTypeSave, ct); - if (exResult != null) throw exResult; + if (exResult != null) return new ValidationErrorResult(exResult); saveContentType(ct); @@ -345,11 +345,14 @@ namespace Umbraco.Web.BackOffice.Controllers catch (Exception ex) { var responseEx = CreateInvalidCompositionResponseException(ex, contentTypeSave, ct, ctId); - throw responseEx ?? ex; + if (responseEx is null) + throw ex; + + return new ValidationErrorResult(responseEx); } var exResult = CreateCompositionValidationExceptionIfInvalid(contentTypeSave, newCt); - if (exResult != null) throw exResult; + if (exResult != null) return new ValidationErrorResult(exResult); //set id to null to ensure its handled as a new type contentTypeSave.Id = null; @@ -416,11 +419,11 @@ namespace Umbraco.Web.BackOffice.Controllers case MoveOperationStatusType.FailedCancelledByEvent: //returning an object of INotificationModel will ensure that any pending // notification messages are added to the response. - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); case MoveOperationStatusType.FailedNotAllowedByPath: var notificationModel = new SimpleNotificationModel(); notificationModel.AddErrorNotification(LocalizedTextService.Localize("moveOrCopy/notAllowedByPath"), ""); - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); default: throw new ArgumentOutOfRangeException(); } @@ -457,11 +460,11 @@ namespace Umbraco.Web.BackOffice.Controllers case MoveOperationStatusType.FailedCancelledByEvent: //returning an object of INotificationModel will ensure that any pending // notification messages are added to the response. - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); case MoveOperationStatusType.FailedNotAllowedByPath: var notificationModel = new SimpleNotificationModel(); notificationModel.AddErrorNotification(LocalizedTextService.Localize("moveOrCopy/notAllowedByPath"), ""); - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); default: throw new ArgumentOutOfRangeException(); } @@ -473,7 +476,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - private HttpResponseException CreateCompositionValidationExceptionIfInvalid(TContentTypeSave contentTypeSave, TContentType composition) + private TContentTypeDisplay CreateCompositionValidationExceptionIfInvalid(TContentTypeSave contentTypeSave, TContentType composition) where TContentTypeSave : ContentTypeSave where TPropertyType : PropertyTypeBasic where TContentTypeDisplay : ContentTypeCompositionDisplay @@ -491,7 +494,7 @@ namespace Umbraco.Web.BackOffice.Controllers //map the 'save' data on top display = UmbracoMapper.Map(contentTypeSave, display); display.Errors = ModelState.ToErrorDictionary(); - throw HttpResponseException.CreateValidationErrorResponse(display); + return display; } return null; } @@ -540,7 +543,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - private HttpResponseException CreateInvalidCompositionResponseException( + private TContentTypeDisplay CreateInvalidCompositionResponseException( Exception ex, TContentTypeSave contentTypeSave, TContentType ct, int ctId) where TContentTypeDisplay : ContentTypeCompositionDisplay where TContentTypeSave : ContentTypeSave @@ -558,7 +561,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (invalidCompositionException != null) { AddCompositionValidationErrors(contentTypeSave, invalidCompositionException.PropertyTypeAliases); - return CreateModelStateValidationException(ctId, contentTypeSave, ct); + return CreateModelStateValidationEror(ctId, contentTypeSave, ct); } return null; } @@ -571,7 +574,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - private HttpResponseException CreateModelStateValidationException(int ctId, TContentTypeSave contentTypeSave, TContentType ct) + private TContentTypeDisplay CreateModelStateValidationEror(int ctId, TContentTypeSave contentTypeSave, TContentType ct) where TContentTypeDisplay : ContentTypeCompositionDisplay where TContentTypeSave : ContentTypeSave { @@ -590,7 +593,7 @@ namespace Umbraco.Web.BackOffice.Controllers } forDisplay.Errors = ModelState.ToErrorDictionary(); - return HttpResponseException.CreateValidationErrorResponse(forDisplay); + return forDisplay; } } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs b/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs index d156551c26..36f1a7455f 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs @@ -16,15 +16,16 @@ using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Mapping; using Umbraco.Core.Media; +using Umbraco.Core.Models; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.BackOffice.Security; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models; using Umbraco.Web.Models.ContentEditing; @@ -170,8 +171,8 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// This only works when the user is logged in (partially) /// - [Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)] // TODO: Why is this necessary? This inherits from UmbracoAuthorizedApiController - public async Task PostSetInvitedUserPassword([FromBody]string newPassword) + [AllowAnonymous] + public async Task> PostSetInvitedUserPassword([FromBody]string newPassword) { var user = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0).ToString()); if (user == null) throw new InvalidOperationException("Could not find user"); @@ -184,7 +185,7 @@ namespace Umbraco.Web.BackOffice.Controllers // so that is why it is being used here. ModelState.AddModelError("value", result.Errors.ToErrorMessage()); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } //They've successfully set their password, we can now update their user account to be approved @@ -201,10 +202,10 @@ namespace Umbraco.Web.BackOffice.Controllers } [AppendUserModifiedHeader] - public IActionResult PostSetAvatar(IList files) + public IActionResult PostSetAvatar(IList file) { //borrow the logic from the user controller - return UsersController.PostSetAvatarInternal(files, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); + return UsersController.PostSetAvatarInternal(file, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); } /// @@ -214,7 +215,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// If the password is being reset it will return the newly reset password, otherwise will return an empty value /// - public async Task> PostChangePassword(ChangingPasswordModel data) + public async Task>> PostChangePassword(ChangingPasswordModel data) { // TODO: Why don't we inject this? Then we can just inject a logger var passwordChanger = new PasswordChanger(_loggerFactory.CreateLogger()); @@ -233,7 +234,7 @@ namespace Umbraco.Web.BackOffice.Controllers ModelState.AddModelError(memberName, passwordChangeResult.Result.ChangeError.ErrorMessage); } - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } // TODO: Why is this necessary? This inherits from UmbracoAuthorizedApiController diff --git a/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs index 0ffe64e251..4cc1f80f9e 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs @@ -1,8 +1,7 @@ -using System; +using System; using System.Collections.Generic; using System.Data; using System.Linq; -using System.Net; using System.Net.Mime; using System.Text; using Microsoft.AspNetCore.Authorization; @@ -16,11 +15,11 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.Security; using Umbraco.Core.Serialization; using Umbraco.Core.Services; +using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.Editors; using Umbraco.Web.Models.ContentEditing; using Constants = Umbraco.Core.Constants; @@ -92,13 +91,14 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public DataTypeDisplay GetById(int id) + public ActionResult GetById(int id) { var dataType = _dataTypeService.GetDataType(id); if (dataType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } + return _umbracoMapper.Map(dataType); } @@ -108,13 +108,14 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public DataTypeDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var dataType = _dataTypeService.GetDataType(id); if (dataType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } + return _umbracoMapper.Map(dataType); } @@ -124,17 +125,18 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public DataTypeDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var dataType = _dataTypeService.GetDataType(guidUdi.Guid); if (dataType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } + return _umbracoMapper.Map(dataType); } @@ -150,7 +152,7 @@ namespace Umbraco.Web.BackOffice.Controllers var foundType = _dataTypeService.GetDataType(id); if (foundType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; _dataTypeService.Delete(foundType, currentUser.Id); @@ -171,12 +173,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// a DataTypeDisplay - public DataTypeDisplay GetCustomListView(string contentTypeAlias) + public ActionResult GetCustomListView(string contentTypeAlias) { var dt = _dataTypeService.GetDataType(Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias); if (dt == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return _umbracoMapper.Map(dt); @@ -208,7 +210,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// The data type id for the pre-values, -1 if it is a new data type /// - public IEnumerable GetPreValues(string editorAlias, int dataTypeId = -1) + public ActionResult> GetPreValues(string editorAlias, int dataTypeId = -1) { var propEd = _propertyEditors[editorAlias]; if (propEd == null) @@ -219,14 +221,14 @@ namespace Umbraco.Web.BackOffice.Controllers if (dataTypeId == -1) { //this is a new data type, so just return the field editors with default values - return _umbracoMapper.Map>(propEd); + return new ActionResult>(_umbracoMapper.Map>(propEd)); } //we have a data type associated var dataType = _dataTypeService.GetDataType(dataTypeId); if (dataType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } //now, lets check if the data type has the current editor selected, if that is true @@ -235,11 +237,11 @@ namespace Umbraco.Web.BackOffice.Controllers if (dataType.EditorAlias == editorAlias) { //this is the currently assigned pre-value editor, return with values. - return _umbracoMapper.Map>(dataType); + return new ActionResult>(_umbracoMapper.Map>(dataType)); } //these are new pre-values, so just return the field editors with default values - return _umbracoMapper.Map>(propEd); + return new ActionResult>(_umbracoMapper.Map>(propEd)); } /// @@ -263,9 +265,10 @@ namespace Umbraco.Web.BackOffice.Controllers var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var result = _dataTypeService.CreateContainer(parentId, name, currentUser.Id); - return result - ? Ok(result.Result) //return the id - : throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Exception.Message); + if (result.Success) + return Ok(result.Result); //return the id + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Exception.Message); } /// @@ -300,7 +303,7 @@ namespace Umbraco.Web.BackOffice.Controllers catch (DuplicateNameException ex) { ModelState.AddModelError("Name", ex.Message); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } // map back to display model, and return @@ -335,11 +338,11 @@ namespace Umbraco.Web.BackOffice.Controllers case MoveOperationStatusType.FailedCancelledByEvent: //returning an object of INotificationModel will ensure that any pending // notification messages are added to the response. - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); case MoveOperationStatusType.FailedNotAllowedByPath: var notificationModel = new SimpleNotificationModel(); notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy/notAllowedByPath"), ""); - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); default: throw new ArgumentOutOfRangeException(); } @@ -350,9 +353,10 @@ namespace Umbraco.Web.BackOffice.Controllers var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var result = _dataTypeService.RenameContainer(id, name, currentUser.Id); - return result - ? Ok(result.Result) - : throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Exception.Message); + if (result.Success) + return Ok(result.Result); + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Exception.Message); } /// diff --git a/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs b/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs index c7f86e12a1..6a03c6ef89 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs @@ -1,24 +1,22 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Umbraco.Core; -using Umbraco.Core.Configuration; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Security; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Security; using Constants = Umbraco.Core.Constants; using Umbraco.Core.Configuration.Models; using Microsoft.Extensions.Options; using Microsoft.AspNetCore.Authorization; +using Umbraco.Extensions; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Authorization; namespace Umbraco.Web.BackOffice.Controllers @@ -101,7 +99,7 @@ namespace Umbraco.Web.BackOffice.Controllers public ActionResult Create(int parentId, string key) { if (string.IsNullOrEmpty(key)) - throw HttpResponseException.CreateNotificationValidationErrorResponse("Key can not be empty."); // TODO: translate + return ValidationErrorResult.CreateNotificationValidationErrorResult("Key can not be empty."); // TODO: translate if (_localizationService.DictionaryItemExists(key)) { @@ -109,7 +107,7 @@ namespace Umbraco.Web.BackOffice.Controllers "dictionaryItem/changeKeyError", _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserCulture(_localizedTextService, _globalSettings), new Dictionary { { "0", key } }); - throw HttpResponseException.CreateNotificationValidationErrorResponse(message); + return ValidationErrorResult.CreateNotificationValidationErrorResult(message); } try @@ -130,7 +128,7 @@ namespace Umbraco.Web.BackOffice.Controllers catch (Exception ex) { _logger.LogError(ex, "Error creating dictionary with {Name} under {ParentId}", key, parentId); - throw HttpResponseException.CreateNotificationValidationErrorResponse("Error creating dictionary item"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Error creating dictionary item"); } } @@ -141,11 +139,8 @@ namespace Umbraco.Web.BackOffice.Controllers /// The id. /// /// - /// The . + /// The . Returns a not found response when dictionary item does not exist /// - /// - /// Returns a not found response when dictionary item does not exist - /// [DetermineAmbiguousActionByPassingParameters] public ActionResult GetById(int id) { @@ -163,11 +158,8 @@ namespace Umbraco.Web.BackOffice.Controllers /// The id. /// /// - /// The . + /// The . Returns a not found response when dictionary item does not exist /// - /// - /// Returns a not found response when dictionary item does not exist - /// [DetermineAmbiguousActionByPassingParameters] public ActionResult GetById(Guid id) { @@ -185,11 +177,8 @@ namespace Umbraco.Web.BackOffice.Controllers /// The id. /// /// - /// The . + /// The . Returns a not found response when dictionary item does not exist /// - /// - /// Returns a not found response when dictionary item does not exist - /// [DetermineAmbiguousActionByPassingParameters] public ActionResult GetById(Udi id) { @@ -213,13 +202,13 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// The . /// - public DictionaryDisplay PostSave(DictionarySave dictionary) + public ActionResult PostSave(DictionarySave dictionary) { var dictionaryItem = _localizationService.GetDictionaryItemById(int.Parse(dictionary.Id.ToString())); if (dictionaryItem == null) - throw HttpResponseException.CreateNotificationValidationErrorResponse("Dictionary item does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Dictionary item does not exist"); var userCulture = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserCulture(_localizedTextService, _globalSettings); @@ -236,7 +225,7 @@ namespace Umbraco.Web.BackOffice.Controllers userCulture, new Dictionary { { "0", dictionary.Name } }); ModelState.AddModelError("Name", message); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } dictionaryItem.ItemKey = dictionary.Name; @@ -263,7 +252,7 @@ namespace Umbraco.Web.BackOffice.Controllers catch (Exception ex) { _logger.LogError(ex, "Error saving dictionary with {Name} under {ParentId}", dictionary.Name, dictionary.ParentId); - throw HttpResponseException.CreateNotificationValidationErrorResponse("Something went wrong saving dictionary"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Something went wrong saving dictionary"); } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs b/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs index 219ca694e8..13ef66fa15 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs @@ -1,37 +1,33 @@ -using System; +using System; using System.Collections.Generic; -using System.Net; -using Umbraco.Core; -using Umbraco.Core.Models.Membership; -using Umbraco.Web.Models.ContentEditing; using System.Linq; -using System.Net.Http; using System.Reflection; using Microsoft.AspNetCore.Http; -using Umbraco.Core.Models; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Umbraco.Core; using Umbraco.Core.Mapping; +using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.Strings; +using Umbraco.Core.Trees; using Umbraco.Core.Xml; using Umbraco.Extensions; using Umbraco.Web.BackOffice.ModelBinders; +using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.ModelBinders; using Umbraco.Web.Models; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Mapping; using Umbraco.Web.Models.TemplateQuery; +using Umbraco.Web.Routing; using Umbraco.Web.Search; using Umbraco.Web.Services; using Umbraco.Web.Trees; -using Constants = Umbraco.Core.Constants; -using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.Common.ModelBinders; -using Umbraco.Web.Models.Mapping; -using Umbraco.Web.Routing; -using Umbraco.Web.Security; -using Umbraco.Core.Trees; namespace Umbraco.Web.BackOffice.Controllers { @@ -206,11 +202,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetPath(int id, UmbracoEntityTypes type) + public IConvertToActionResult GetPath(int id, UmbracoEntityTypes type) { - var foundContent = GetResultForId(id, type); + var foundContentResult = GetResultForId(id, type); + var foundContent = foundContentResult.Value; + if (foundContent is null) + { + return foundContentResult; + } - return foundContent.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); + return new ActionResult>(foundContent.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse)); } /// @@ -220,11 +221,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetPath(Guid id, UmbracoEntityTypes type) + public IConvertToActionResult GetPath(Guid id, UmbracoEntityTypes type) { - var foundContent = GetResultForKey(id, type); + var foundContentResult = GetResultForKey(id, type); + var foundContent = foundContentResult.Value; + if (foundContent is null) + { + return foundContentResult; + } - return foundContent.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); + return new ActionResult>(foundContent.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse)); } /// @@ -234,14 +240,15 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetPath(Udi id, UmbracoEntityTypes type) + public IActionResult GetPath(Udi id, UmbracoEntityTypes type) { var guidUdi = id as GuidUdi; if (guidUdi != null) { - return GetPath(guidUdi.Guid, type); + return GetPath(guidUdi.Guid, type).Convert(); } - throw new HttpResponseException(HttpStatusCode.NotFound); + + return NotFound(); } /// @@ -255,7 +262,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var intId = _entityService.GetId(udi); if (!intId.Success) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); UmbracoEntityTypes entityType; switch (udi.EntityType) { @@ -269,7 +276,7 @@ namespace Umbraco.Web.BackOffice.Controllers entityType = UmbracoEntityTypes.Member; break; default: - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return GetUrl(intId.Result, entityType, culture); } @@ -323,7 +330,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - public EntityBasic GetByQuery(string query, int nodeContextId, UmbracoEntityTypes type) + public ActionResult GetByQuery(string query, int nodeContextId, UmbracoEntityTypes type) { // TODO: Rename this!!! It's misleading, it should be GetByXPath @@ -357,11 +364,11 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] [DetermineAmbiguousActionByPassingParameters] - public UrlAndAnchors GetUrlAndAnchors(Udi id, string culture = "*") + public ActionResult GetUrlAndAnchors(Udi id, string culture = "*") { var intId = _entityService.GetId(id); if (!intId.Success) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); return GetUrlAndAnchors(intId.Result, culture); } @@ -394,7 +401,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public EntityBasic GetById(int id, UmbracoEntityTypes type) + public ActionResult GetById(int id, UmbracoEntityTypes type) { return GetResultForId(id, type); } @@ -406,7 +413,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public EntityBasic GetById(Guid id, UmbracoEntityTypes type) + public ActionResult GetById(Guid id, UmbracoEntityTypes type) { return GetResultForKey(id, type); } @@ -418,14 +425,15 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public EntityBasic GetById(Udi id, UmbracoEntityTypes type) + public ActionResult GetById(Udi id, UmbracoEntityTypes type) { var guidUdi = id as GuidUdi; if (guidUdi != null) { return GetResultForKey(guidUdi.Guid, type); } - throw new HttpResponseException(HttpStatusCode.NotFound); + + return NotFound(); } #endregion @@ -442,13 +450,14 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] [HttpPost] [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetByIds([FromJsonPath]int[] ids, UmbracoEntityTypes type) + public ActionResult> GetByIds([FromJsonPath]int[] ids, UmbracoEntityTypes type) { if (ids == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } - return GetResultForIds(ids, type); + + return new ActionResult>(GetResultForIds(ids, type)); } /// @@ -463,13 +472,14 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] [HttpPost] [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetByIds([FromJsonPath]Guid[] ids, UmbracoEntityTypes type) + public ActionResult> GetByIds([FromJsonPath]Guid[] ids, UmbracoEntityTypes type) { if (ids == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } - return GetResultForKeys(ids, type); + + return new ActionResult>(GetResultForKeys(ids, type)); } /// @@ -486,16 +496,16 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] [HttpPost] [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetByIds([FromJsonPath]Udi[] ids, [FromQuery]UmbracoEntityTypes type) + public ActionResult> GetByIds([FromJsonPath]Udi[] ids, [FromQuery]UmbracoEntityTypes type) { if (ids == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } if (ids.Length == 0) { - return Enumerable.Empty(); + return Enumerable.Empty().ToList(); } //all udi types will need to be the same in this list so we'll determine by the first @@ -504,10 +514,10 @@ namespace Umbraco.Web.BackOffice.Controllers var guidUdi = ids[0] as GuidUdi; if (guidUdi != null) { - return GetResultForKeys(ids.Select(x => ((GuidUdi)x).Guid).ToArray(), type); + return new ActionResult>(GetResultForKeys(ids.Select(x => ((GuidUdi)x).Guid).ToArray(), type)); } - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } #endregion @@ -563,7 +573,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public PagedResult GetPagedChildren( + public ActionResult> GetPagedChildren( string id, UmbracoEntityTypes type, int pageNumber, @@ -581,13 +591,13 @@ namespace Umbraco.Web.BackOffice.Controllers if (Guid.TryParse(id, out _)) { //Not supported currently - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } if (UdiParser.TryParse(id, out _)) { //Not supported currently - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } //so we don't have an INT, GUID or UDI, it's just a string, so now need to check if it's a special id or a member type @@ -625,7 +635,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public PagedResult GetPagedChildren( + public ActionResult> GetPagedChildren( int id, UmbracoEntityTypes type, int pageNumber, @@ -636,9 +646,9 @@ namespace Umbraco.Web.BackOffice.Controllers Guid? dataTypeKey = null) { if (pageNumber <= 0) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); if (pageSize <= 0) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var objectType = ConvertToObjectType(type); if (objectType.HasValue) @@ -725,7 +735,7 @@ namespace Umbraco.Web.BackOffice.Controllers } } - public PagedResult GetPagedDescendants( + public ActionResult> GetPagedDescendants( int id, UmbracoEntityTypes type, int pageNumber, @@ -736,9 +746,9 @@ namespace Umbraco.Web.BackOffice.Controllers Guid? dataTypeKey = null) { if (pageNumber <= 0) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); if (pageSize <= 0) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); // re-normalize since NULL can be passed in filter = filter ?? string.Empty; @@ -973,7 +983,7 @@ namespace Umbraco.Web.BackOffice.Controllers } } - private EntityBasic GetResultForKey(Guid key, UmbracoEntityTypes entityType) + private ActionResult GetResultForKey(Guid key, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) @@ -981,7 +991,7 @@ namespace Umbraco.Web.BackOffice.Controllers var found = _entityService.Get(key, objectType.Value); if (found == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return _umbracoMapper.Map(found); } @@ -1005,7 +1015,7 @@ namespace Umbraco.Web.BackOffice.Controllers } } - private EntityBasic GetResultForId(int id, UmbracoEntityTypes entityType) + private ActionResult GetResultForId(int id, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) @@ -1013,7 +1023,7 @@ namespace Umbraco.Web.BackOffice.Controllers var found = _entityService.Get(id, objectType.Value); if (found == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return MapEntity(found); } diff --git a/src/Umbraco.Web.BackOffice/Controllers/ExamineManagementController.cs b/src/Umbraco.Web.BackOffice/Controllers/ExamineManagementController.cs index 72f07c02f3..3174c3ca4a 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ExamineManagementController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ExamineManagementController.cs @@ -1,8 +1,7 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Examine; -using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Umbraco.Core; @@ -10,8 +9,8 @@ using Umbraco.Core.Cache; using Umbraco.Core.IO; using Umbraco.Examine; using Umbraco.Extensions; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Search; using SearchResult = Umbraco.Web.Models.ContentEditing.SearchResult; @@ -62,14 +61,14 @@ namespace Umbraco.Web.BackOffice.Controllers return model; } - public SearchResults GetSearchResults(string searcherName, string query, int pageIndex = 0, int pageSize = 20) + public ActionResult GetSearchResults(string searcherName, string query, int pageIndex = 0, int pageSize = 20) { if (query.IsNullOrWhiteSpace()) return SearchResults.Empty(); var msg = ValidateSearcher(searcherName, out var searcher); if (!msg.IsSuccessStatusCode()) - throw new HttpResponseException(msg); + return msg; // NativeQuery will work for a single word/phrase too (but depends on the implementation) the lucene one will work. var results = searcher.CreateQuery().NativeQuery(query).Execute(maxResults: pageSize * (pageIndex + 1)); @@ -105,11 +104,11 @@ namespace Umbraco.Web.BackOffice.Controllers var validate = ValidateIndex(indexName, out var index); if (!validate.IsSuccessStatusCode()) - throw new HttpResponseException(validate); + return validate; validate = ValidatePopulator(index); if (!validate.IsSuccessStatusCode()) - throw new HttpResponseException(validate); + return validate; var cacheKey = "temp_indexing_op_" + indexName; var found = _runtimeCache.Get(cacheKey); @@ -130,11 +129,11 @@ namespace Umbraco.Web.BackOffice.Controllers { var validate = ValidateIndex(indexName, out var index); if (!validate.IsSuccessStatusCode()) - throw new HttpResponseException(validate); + return validate; validate = ValidatePopulator(index); if (!validate.IsSuccessStatusCode()) - throw new HttpResponseException(validate); + return validate; _logger.LogInformation("Rebuilding index '{IndexName}'", indexName); diff --git a/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs b/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs index 969c267821..c011f67279 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs @@ -6,16 +6,14 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Filters; +using Umbraco.Extensions; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.Editors; using Language = Umbraco.Web.Models.ContentEditing.Language; namespace Umbraco.Web.BackOffice.Controllers @@ -98,7 +96,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (language.IsDefault) { var message = $"Language '{language.IsoCode}' is currently set to 'default' and can not be deleted."; - throw HttpResponseException.CreateNotificationValidationErrorResponse(message); + return ValidationErrorResult.CreateNotificationValidationErrorResult(message); } // service is happy deleting a language that's fallback for another language, @@ -114,10 +112,10 @@ namespace Umbraco.Web.BackOffice.Controllers /// [Authorize(Policy = AuthorizationPolicies.TreeAccessLanguages)] [HttpPost] - public Language SaveLanguage(Language language) + public ActionResult SaveLanguage(Language language) { if (!ModelState.IsValid) - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); // this is prone to race conditions but the service will not let us proceed anyways var existingByCulture = _localizationService.GetLanguageByIsoCode(language.IsoCode); @@ -133,7 +131,7 @@ namespace Umbraco.Web.BackOffice.Controllers { //someone is trying to create a language that already exist ModelState.AddModelError("IsoCode", "The language " + language.IsoCode + " already exists"); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } var existingById = language.Id != default ? _localizationService.GetLanguageById(language.Id) : null; @@ -150,7 +148,7 @@ namespace Umbraco.Web.BackOffice.Controllers catch (CultureNotFoundException) { ModelState.AddModelError("IsoCode", "No Culture found with name " + language.IsoCode); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } // create it (creating a new language cannot create a fallback cycle) @@ -173,7 +171,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (existingById.IsDefault && !language.IsDefault) { ModelState.AddModelError("IsDefault", "Cannot un-default the default language."); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } existingById.IsDefault = language.IsDefault; @@ -188,12 +186,12 @@ namespace Umbraco.Web.BackOffice.Controllers if (!languages.ContainsKey(existingById.FallbackLanguageId.Value)) { ModelState.AddModelError("FallbackLanguage", "The selected fall back language does not exist."); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } if (CreatesCycle(existingById, languages)) { ModelState.AddModelError("FallbackLanguage", $"The selected fall back language {languages[existingById.FallbackLanguageId.Value].IsoCode} would create a circular path."); - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/LogViewerController.cs b/src/Umbraco.Web.BackOffice/Controllers/LogViewerController.cs index 5165d3a092..d77f76a4b2 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/LogViewerController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/LogViewerController.cs @@ -1,13 +1,13 @@ -using System; +using System; using System.Collections.Generic; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Logging.Viewer; using Umbraco.Core.Models; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; namespace Umbraco.Web.BackOffice.Controllers { @@ -44,53 +44,53 @@ namespace Umbraco.Web.BackOffice.Controllers } [HttpGet] - public int GetNumberOfErrors([FromQuery] DateTime? startDate = null,[FromQuery] DateTime? endDate = null) + public ActionResult GetNumberOfErrors([FromQuery] DateTime? startDate = null,[FromQuery] DateTime? endDate = null) { var logTimePeriod = GetTimePeriod(startDate, endDate); //We will need to stop the request if trying to do this on a 1GB file if (CanViewLogs(logTimePeriod) == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Unable to view logs, due to size"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Unable to view logs, due to size"); } return _logViewer.GetNumberOfErrors(logTimePeriod); } [HttpGet] - public LogLevelCounts GetLogLevelCounts([FromQuery] DateTime? startDate = null,[FromQuery] DateTime? endDate = null) + public ActionResult GetLogLevelCounts([FromQuery] DateTime? startDate = null,[FromQuery] DateTime? endDate = null) { var logTimePeriod = GetTimePeriod(startDate, endDate); //We will need to stop the request if trying to do this on a 1GB file if (CanViewLogs(logTimePeriod) == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Unable to view logs, due to size"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Unable to view logs, due to size"); } return _logViewer.GetLogLevelCounts(logTimePeriod); } [HttpGet] - public IEnumerable GetMessageTemplates([FromQuery] DateTime? startDate = null,[FromQuery] DateTime? endDate = null) + public ActionResult> GetMessageTemplates([FromQuery] DateTime? startDate = null,[FromQuery] DateTime? endDate = null) { var logTimePeriod = GetTimePeriod(startDate, endDate); //We will need to stop the request if trying to do this on a 1GB file if (CanViewLogs(logTimePeriod) == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Unable to view logs, due to size"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Unable to view logs, due to size"); } - return _logViewer.GetMessageTemplates(logTimePeriod); + return new ActionResult>(_logViewer.GetMessageTemplates(logTimePeriod)); } [HttpGet] - public PagedResult GetLogs(string orderDirection = "Descending", int pageNumber = 1, string filterExpression = null, [FromQuery(Name = "logLevels[]")]string[] logLevels = null, [FromQuery]DateTime? startDate = null, [FromQuery]DateTime? endDate = null) + public ActionResult> GetLogs(string orderDirection = "Descending", int pageNumber = 1, string filterExpression = null, [FromQuery(Name = "logLevels[]")]string[] logLevels = null, [FromQuery]DateTime? startDate = null, [FromQuery]DateTime? endDate = null) { var logTimePeriod = GetTimePeriod(startDate, endDate); //We will need to stop the request if trying to do this on a 1GB file if (CanViewLogs(logTimePeriod) == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Unable to view logs, due to size"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Unable to view logs, due to size"); } var direction = orderDirection == "Descending" ? Direction.Descending : Direction.Ascending; diff --git a/src/Umbraco.Web.BackOffice/Controllers/MacroRenderingController.cs b/src/Umbraco.Web.BackOffice/Controllers/MacroRenderingController.cs index d11b89f6f0..739ef9942e 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MacroRenderingController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MacroRenderingController.cs @@ -1,9 +1,7 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Net; -using System.Net.Http; using System.Text; using System.Threading; using Microsoft.AspNetCore.Mvc; @@ -15,8 +13,8 @@ using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Templates; using Umbraco.Core.Services; using Umbraco.Core.Strings; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Routing; namespace Umbraco.Web.BackOffice.Controllers @@ -63,15 +61,15 @@ namespace Umbraco.Web.BackOffice.Controllers /// Note that ALL logged in users have access to this method because editors will need to insert macros into rte (content/media/members) and it's used for /// inserting into templates/views/etc... it doesn't expose any sensitive data. /// - public IEnumerable GetMacroParameters(int macroId) + public ActionResult> GetMacroParameters(int macroId) { var macro = _macroService.GetById(macroId); if (macro == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } - return _umbracoMapper.Map>(macro).OrderBy(x => x.SortOrder); + return new ActionResult>(_umbracoMapper.Map>(macro).OrderBy(x => x.SortOrder)); } /// @@ -116,7 +114,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var m = _macroService.GetByAlias(macroAlias); if (m == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); var publishedContent = umbracoContext.Content.GetById(true, pageId); diff --git a/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs b/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs index 3ca89fa5ff..1ad7442289 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs @@ -1,4 +1,4 @@ -using Umbraco.Core.Services; +using Umbraco.Core.Services; using System; using System.Collections.Generic; using System.IO; @@ -12,14 +12,12 @@ using Umbraco.Core.Strings; using Umbraco.Web.Models.ContentEditing; using Constants = Umbraco.Core.Constants; using Umbraco.Core.PropertyEditors; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.Security; using Umbraco.Core; using Umbraco.Core.Mapping; using Umbraco.Core.Security; using Microsoft.AspNetCore.Authorization; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Authorization; namespace Umbraco.Web.BackOffice.Controllers @@ -74,19 +72,19 @@ namespace Umbraco.Web.BackOffice.Controllers { if (string.IsNullOrWhiteSpace(name)) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Name can not be empty"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Name can not be empty"); } var alias = name.ToSafeAlias(_shortStringHelper); if (_macroService.GetByAlias(alias) != null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Macro with this alias already exists"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Macro with this alias already exists"); } if (name == null || name.Length > 255) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Name cannnot be more than 255 characters in length."); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Name cannnot be more than 255 characters in length."); } try @@ -106,19 +104,19 @@ namespace Umbraco.Web.BackOffice.Controllers { const string errorMessage = "Error creating macro"; _logger.LogError(exception, errorMessage); - throw HttpResponseException.CreateNotificationValidationErrorResponse(errorMessage); + return ValidationErrorResult.CreateNotificationValidationErrorResult(errorMessage); } } [HttpGet] [DetermineAmbiguousActionByPassingParameters] - public MacroDisplay GetById(int id) + public ActionResult GetById(int id) { var macro = _macroService.GetById(id); if (macro == null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Macro with id {id} does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult($"Macro with id {id} does not exist"); } var macroDisplay = MapToDisplay(macro); @@ -128,13 +126,13 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] [DetermineAmbiguousActionByPassingParameters] - public MacroDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var macro = _macroService.GetById(id); if (macro == null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Macro with id {id} does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult($"Macro with id {id} does not exist"); } var macroDisplay = MapToDisplay(macro); @@ -144,16 +142,16 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] [DetermineAmbiguousActionByPassingParameters] - public MacroDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Macro with id {id} does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult($"Macro with id {id} does not exist"); var macro = _macroService.GetById(guidUdi.Guid); if (macro == null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Macro with id {id} does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult($"Macro with id {id} does not exist"); } var macroDisplay = MapToDisplay(macro); @@ -162,13 +160,13 @@ namespace Umbraco.Web.BackOffice.Controllers } [HttpPost] - public OkResult DeleteById(int id) + public IActionResult DeleteById(int id) { var macro = _macroService.GetById(id); if (macro == null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Macro with id {id} does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult($"Macro with id {id} does not exist"); } _macroService.Delete(macro); @@ -177,23 +175,23 @@ namespace Umbraco.Web.BackOffice.Controllers } [HttpPost] - public MacroDisplay Save(MacroDisplay macroDisplay) + public ActionResult Save(MacroDisplay macroDisplay) { if (macroDisplay == null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"No macro data found in request"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("No macro data found in request"); } if (macroDisplay.Name == null || macroDisplay.Name.Length > 255) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Name cannnot be more than 255 characters in length."); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Name cannnot be more than 255 characters in length."); } var macro = _macroService.GetById(int.Parse(macroDisplay.Id.ToString())); if (macro == null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Macro with id {macroDisplay.Id} does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult($"Macro with id {macroDisplay.Id} does not exist"); } if (macroDisplay.Alias != macro.Alias) @@ -202,7 +200,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (macroByAlias != null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse($"Macro with this alias already exists"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Macro with this alias already exists"); } } @@ -230,7 +228,7 @@ namespace Umbraco.Web.BackOffice.Controllers { const string errorMessage = "Error creating macro"; _logger.LogError(exception, errorMessage); - throw HttpResponseException.CreateNotificationValidationErrorResponse(errorMessage); + return ValidationErrorResult.CreateNotificationValidationErrorResult(errorMessage); } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs b/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs index 67cd41ff29..e822e7df84 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs @@ -1,14 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Core; @@ -36,9 +36,9 @@ using Umbraco.Web.BackOffice.ActionResults; using Umbraco.Web.BackOffice.Authorization; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.BackOffice.ModelBinders; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.ContentApps; using Umbraco.Web.Models.ContentEditing; @@ -121,12 +121,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [OutgoingEditorModelEvent] - public MediaItemDisplay GetEmpty(string contentTypeAlias, int parentId) + public ActionResult GetEmpty(string contentTypeAlias, int parentId) { var contentType = _mediaTypeService.Get(contentTypeAlias); if (contentType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var emptyContent = _mediaService.CreateMedia("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); @@ -213,14 +213,15 @@ namespace Umbraco.Web.BackOffice.Controllers [OutgoingEditorModelEvent] [Authorize(Policy = AuthorizationPolicies.MediaPermissionPathById)] [DetermineAmbiguousActionByPassingParameters] - public MediaItemDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi != null) { return GetById(guidUdi.Guid); } - throw new HttpResponseException(HttpStatusCode.NotFound); + + return NotFound(); } /// @@ -377,7 +378,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// [FilterAllowedOutgoingMedia(typeof(IEnumerable>), "Items")] [DetermineAmbiguousActionByPassingParameters] - public PagedResult> GetChildren(Guid id, + public ActionResult>> GetChildren(Guid id, int pageNumber = 0, int pageSize = 0, string orderBy = "SortOrder", @@ -390,7 +391,8 @@ namespace Umbraco.Web.BackOffice.Controllers { return GetChildren(entity.Id, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter); } - throw new HttpResponseException(HttpStatusCode.NotFound); + + return NotFound(); } /// @@ -406,7 +408,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// [FilterAllowedOutgoingMedia(typeof(IEnumerable>), "Items")] [DetermineAmbiguousActionByPassingParameters] - public PagedResult> GetChildren(Udi id, + public ActionResult>> GetChildren(Udi id, int pageNumber = 0, int pageSize = 0, string orderBy = "SortOrder", @@ -424,7 +426,7 @@ namespace Umbraco.Web.BackOffice.Controllers } } - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } #endregion @@ -442,7 +444,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (foundMedia == null) { - return HandleContentNotFound(id, false); + return HandleContentNotFound(id); } //if the current item is in the recycle bin @@ -453,7 +455,7 @@ namespace Umbraco.Web.BackOffice.Controllers { //returning an object of INotificationModel will ensure that any pending // notification messages are added to the response. - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); } } else @@ -463,7 +465,7 @@ namespace Umbraco.Web.BackOffice.Controllers { //returning an object of INotificationModel will ensure that any pending // notification messages are added to the response. - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); } } @@ -485,7 +487,13 @@ namespace Umbraco.Web.BackOffice.Controllers return Forbid(); } - var toMove = ValidateMoveOrCopy(move); + var toMoveResult = ValidateMoveOrCopy(move); + var toMove = toMoveResult.Value; + if (toMove is null && toMoveResult is IConvertToActionResult convertToActionResult) + { + return convertToActionResult.Convert(); + } + var destinationParentID = move.ParentId; var sourceParentID = toMove.ParentId; @@ -493,11 +501,11 @@ namespace Umbraco.Web.BackOffice.Controllers if (sourceParentID == destinationParentID) { - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel(new BackOfficeNotification("",_localizedTextService.Localize("media/moveToSameFolderFailed"),NotificationStyle.Error))); + return new ValidationErrorResult(new SimpleNotificationModel(new BackOfficeNotification("",_localizedTextService.Localize("media/moveToSameFolderFailed"),NotificationStyle.Error))); } if (moveResult == false) { - throw HttpResponseException.CreateValidationErrorResponse(new SimpleNotificationModel()); + return new ValidationErrorResult(new SimpleNotificationModel()); } else { @@ -512,7 +520,7 @@ namespace Umbraco.Web.BackOffice.Controllers [FileUploadCleanupFilter] [MediaItemSaveValidation] [OutgoingEditorModelEvent] - public MediaItemDisplay PostSave( + public ActionResult PostSave( [ModelBinder(typeof(MediaItemBinder))] MediaItemSave contentItem) { @@ -558,7 +566,7 @@ namespace Umbraco.Web.BackOffice.Controllers // add the model state to the outgoing object and throw validation response var forDisplay = _umbracoMapper.Map(contentItem.PersistedContent); forDisplay.Errors = ModelState.ToErrorDictionary(); - throw HttpResponseException.CreateValidationErrorResponse(forDisplay); + return new ValidationErrorResult(forDisplay); } } @@ -569,7 +577,11 @@ namespace Umbraco.Web.BackOffice.Controllers var display = _umbracoMapper.Map(contentItem.PersistedContent); //lastly, if it is not valid, add the model state to the outgoing object and throw a 403 - HandleInvalidModelState(display); + if (!ModelState.IsValid) + { + display.Errors = ModelState.ToErrorDictionary(); + return new ValidationErrorResult(display, StatusCodes.Status403Forbidden); + } //put the correct msgs in switch (contentItem.Action) @@ -591,7 +603,7 @@ namespace Umbraco.Web.BackOffice.Controllers // is no Id to redirect to! if (saveStatus.Result.Result == OperationResultType.FailedCancelledByEvent && IsCreatingAction(contentItem.Action)) { - throw HttpResponseException.CreateValidationErrorResponse(display); + return new ValidationErrorResult(display); } } @@ -649,7 +661,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (_mediaService.Sort(sortedMedia) == false) { _logger.LogWarning("Media sorting failed, this was probably caused by an event being cancelled"); - throw HttpResponseException.CreateValidationErrorResponse("Media sorting failed, this was probably caused by an event being cancelled"); + return new ValidationErrorResult("Media sorting failed, this was probably caused by an event being cancelled"); } return Ok(); } @@ -662,7 +674,12 @@ namespace Umbraco.Web.BackOffice.Controllers public async Task> PostAddFolder(PostedFolder folder) { - var parentId = await GetParentIdAsIntAsync(folder.ParentId, validatePermissions:true); + var parentIdResult = await GetParentIdAsIntAsync(folder.ParentId, validatePermissions:true); + if (!(parentIdResult.Result is null)) + { + return new ActionResult(parentIdResult.Result); + } + var parentId = parentIdResult.Value; if (!parentId.HasValue) { return NotFound("The passed id doesn't exist"); @@ -694,11 +711,18 @@ namespace Umbraco.Web.BackOffice.Controllers } //get the string json from the request - var parentId = await GetParentIdAsIntAsync(currentFolder, validatePermissions: true); + var parentIdResult = await GetParentIdAsIntAsync(currentFolder, validatePermissions:true); + if (!(parentIdResult.Result is null)) + { + return parentIdResult.Result; + } + + var parentId = parentIdResult.Value; if (!parentId.HasValue) { return NotFound("The passed id doesn't exist"); } + var tempFiles = new PostedFiles(); @@ -842,7 +866,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// and if that check fails an unauthorized exception will occur /// /// - private async Task GetParentIdAsIntAsync(string parentId, bool validatePermissions) + private async Task> GetParentIdAsIntAsync(string parentId, bool validatePermissions) { int intParentId; @@ -871,7 +895,7 @@ namespace Umbraco.Web.BackOffice.Controllers } else { - throw HttpResponseException.CreateValidationErrorResponse("The request was not formatted correctly, the parentId is not an integer, Guid or UDI"); + return new ValidationErrorResult("The request was not formatted correctly, the parentId is not an integer, Guid or UDI"); } } @@ -883,12 +907,12 @@ namespace Umbraco.Web.BackOffice.Controllers var authorizationResult = await _authorizationService.AuthorizeAsync(User, new MediaPermissionsResource(_mediaService.GetById(intParentId)), requirement); if (!authorizationResult.Succeeded) { - throw new HttpResponseException( - HttpStatusCode.Forbidden, + return new ValidationErrorResult( new SimpleNotificationModel(new BackOfficeNotification( _localizedTextService.Localize("speechBubbles/operationFailedHeader"), _localizedTextService.Localize("speechBubbles/invalidUserPermissionsText"), - NotificationStyle.Warning))); + NotificationStyle.Warning)), + StatusCodes.Status403Forbidden); } } @@ -900,18 +924,18 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - private IMedia ValidateMoveOrCopy(MoveOrCopy model) + private ActionResult ValidateMoveOrCopy(MoveOrCopy model) { if (model == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var toMove = _mediaService.GetById(model.Id); if (toMove == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } if (model.ParentId < 0) { @@ -922,7 +946,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var notificationModel = new SimpleNotificationModel(); notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy/notAllowedAtRoot"), ""); - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); } } else @@ -930,7 +954,7 @@ namespace Umbraco.Web.BackOffice.Controllers var parent = _mediaService.GetById(model.ParentId); if (parent == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } //check if the item is allowed under this one @@ -940,7 +964,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var notificationModel = new SimpleNotificationModel(); notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy/notAllowedByContentType"), ""); - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); } // Check on paths @@ -948,15 +972,13 @@ namespace Umbraco.Web.BackOffice.Controllers { var notificationModel = new SimpleNotificationModel(); notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy/notAllowedByPath"), ""); - throw HttpResponseException.CreateValidationErrorResponse(notificationModel); + return new ValidationErrorResult(notificationModel); } } - return toMove; + return new ActionResult(toMove); } - - public PagedResult GetPagedReferences(int id, string entityType, int pageNumber = 1, int pageSize = 100) { if (pageNumber <= 0 || pageSize <= 0) diff --git a/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs index 32dc2ef888..b8952e580f 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs @@ -1,7 +1,6 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; -using System.Net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Umbraco.Core; @@ -11,10 +10,9 @@ using Umbraco.Core.Models; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.Strings; -using Umbraco.Web.BackOffice.Filters; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Editors; using Umbraco.Web.Models.ContentEditing; @@ -78,12 +76,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// [DetermineAmbiguousActionByPassingParameters] [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaOrMediaTypes)] - public MediaTypeDisplay GetById(int id) + public ActionResult GetById(int id) { var ct = _mediaTypeService.Get(id); if (ct == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(ct); @@ -97,12 +95,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// [DetermineAmbiguousActionByPassingParameters] [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaOrMediaTypes)] - public MediaTypeDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var mediaType = _mediaTypeService.Get(id); if (mediaType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(mediaType); @@ -116,16 +114,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// [DetermineAmbiguousActionByPassingParameters] [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaOrMediaTypes)] - public MediaTypeDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var mediaType = _mediaTypeService.Get(guidUdi.Guid); if (mediaType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(mediaType); @@ -145,7 +143,7 @@ namespace Umbraco.Web.BackOffice.Controllers var foundType = _mediaTypeService.Get(id); if (foundType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } _mediaTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); @@ -178,9 +176,16 @@ namespace Umbraco.Web.BackOffice.Controllers [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaTypes)] public IActionResult GetAvailableCompositeMediaTypes(GetAvailableCompositionsFilter filter) { - var result = PerformGetAvailableCompositeContentTypes(filter.ContentTypeId, UmbracoObjectTypes.MediaType, - filter.FilterContentTypes, filter.FilterPropertyTypes, filter.IsElement) - .Select(x => new + var actionResult = PerformGetAvailableCompositeContentTypes(filter.ContentTypeId, + UmbracoObjectTypes.MediaType, filter.FilterContentTypes, filter.FilterPropertyTypes, + filter.IsElement); + + if (!(actionResult.Result is null)) + { + return actionResult.Result; + } + + var result = actionResult.Value.Select(x => new { contentType = x.Item1, allowed = x.Item2 @@ -200,7 +205,7 @@ namespace Umbraco.Web.BackOffice.Controllers public IActionResult GetWhereCompositionIsUsedInContentTypes(GetAvailableCompositionsFilter filter) { var result = - PerformGetWhereCompositionIsUsedInContentTypes(filter.ContentTypeId, UmbracoObjectTypes.MediaType) + PerformGetWhereCompositionIsUsedInContentTypes(filter.ContentTypeId, UmbracoObjectTypes.MediaType).Value .Select(x => new { contentType = x @@ -257,9 +262,10 @@ namespace Umbraco.Web.BackOffice.Controllers { var result = _mediaTypeService.CreateContainer(parentId, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); - return result - ? Ok(result.Result) //return the id - : throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Exception.Message); + if (result.Success) + return Ok(result.Result); //return the id + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Exception.Message); } [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaTypes)] @@ -267,20 +273,27 @@ namespace Umbraco.Web.BackOffice.Controllers { var result = _mediaTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); - return result - ? Ok(result.Result) //return the id - : throw HttpResponseException.CreateNotificationValidationErrorResponse(result.Exception.Message); + if (result.Success) + return Ok(result.Result); //return the id + else + return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Exception.Message); } [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaTypes)] - public MediaTypeDisplay PostSave(MediaTypeSave contentTypeSave) + public ActionResult PostSave(MediaTypeSave contentTypeSave) { var savedCt = PerformPostSave( contentTypeSave, i => _mediaTypeService.Get(i), type => _mediaTypeService.Save(type)); - var display = _umbracoMapper.Map(savedCt); + if (!(savedCt.Result is null)) + { + return savedCt.Result; + } + + var display = _umbracoMapper.Map(savedCt.Value); + display.AddSuccessNotification( _localizedTextService.Localize("speechBubbles/mediaTypeSavedHeader"), @@ -373,15 +386,15 @@ namespace Umbraco.Web.BackOffice.Controllers /// [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaOrMediaTypes)] [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetAllowedChildren(Guid contentId) + public ActionResult> GetAllowedChildren(Guid contentId) { var entity = _entityService.Get(contentId); if (entity != null) { - return GetAllowedChildren(entity.Id); + return new ActionResult>(GetAllowedChildren(entity.Id)); } - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } /// @@ -390,7 +403,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// [Authorize(Policy = AuthorizationPolicies.TreeAccessMediaOrMediaTypes)] [DetermineAmbiguousActionByPassingParameters] - public IEnumerable GetAllowedChildren(Udi contentId) + public ActionResult> GetAllowedChildren(Udi contentId) { var guidUdi = contentId as GuidUdi; if (guidUdi != null) @@ -398,11 +411,11 @@ namespace Umbraco.Web.BackOffice.Controllers var entity = _entityService.Get(guidUdi.Guid); if (entity != null) { - return GetAllowedChildren(entity.Id); + return new ActionResult>(GetAllowedChildren(entity.Id)); } } - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } #endregion diff --git a/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs b/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs index 267539c97f..26d84756bd 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs @@ -1,13 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; -using System.Net; using System.Net.Http; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -27,14 +27,12 @@ using Umbraco.Core.Strings; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.BackOffice.ModelBinders; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Common.Filters; using Umbraco.Web.ContentApps; using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Security; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Controllers { @@ -168,18 +166,18 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [OutgoingEditorModelEvent] - public MemberDisplay GetEmpty(string contentTypeAlias = null) + public ActionResult GetEmpty(string contentTypeAlias = null) { IMember emptyContent; if (contentTypeAlias == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var contentType = _memberTypeService.Get(contentTypeAlias); if (contentType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var passwordGenerator = new PasswordGenerator(_passwordConfig); @@ -218,7 +216,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var forDisplay = _umbracoMapper.Map(contentItem.PersistedContent); forDisplay.Errors = ModelState.ToErrorDictionary(); - throw HttpResponseException.CreateValidationErrorResponse(forDisplay); + return new ValidationErrorResult(forDisplay); } //We're gonna look up the current roles now because the below code can cause @@ -241,7 +239,7 @@ namespace Umbraco.Web.BackOffice.Controllers break; default: //we don't support anything else for members - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } //TODO: There's 3 things saved here and we should do this all in one transaction, which we can do here by wrapping in a scope @@ -268,7 +266,11 @@ namespace Umbraco.Web.BackOffice.Controllers var display = _umbracoMapper.Map(contentItem.PersistedContent); //lastly, if it is not valid, add the model state to the outgoing object and throw a 403 - HandleInvalidModelState(display); + if (!ModelState.IsValid) + { + display.Errors = ModelState.ToErrorDictionary(); + return new ValidationErrorResult(display, StatusCodes.Status403Forbidden); + } var localizedTextService = _localizedTextService; //put the correct messages in @@ -450,7 +452,7 @@ namespace Umbraco.Web.BackOffice.Controllers var foundMember = _memberService.GetByKey(key); if (foundMember == null) { - return HandleContentNotFound(key, false); + return HandleContentNotFound(key); } _memberService.Delete(foundMember); diff --git a/src/Umbraco.Web.BackOffice/Controllers/MemberGroupController.cs b/src/Umbraco.Web.BackOffice/Controllers/MemberGroupController.cs index a7cbaf96c1..43df969ef5 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MemberGroupController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MemberGroupController.cs @@ -1,17 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; -using System.Net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; using Constants = Umbraco.Core.Constants; @@ -46,12 +43,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public MemberGroupDisplay GetById(int id) + public ActionResult GetById(int id) { var memberGroup = _memberGroupService.GetById(id); if (memberGroup == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(memberGroup); @@ -65,12 +62,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public MemberGroupDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var memberGroup = _memberGroupService.GetById(id); if (memberGroup == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return _umbracoMapper.Map(memberGroup); @@ -82,16 +79,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public MemberGroupDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var memberGroup = _memberGroupService.GetById(guidUdi.Guid); if (memberGroup == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return _umbracoMapper.Map(memberGroup); @@ -110,7 +107,7 @@ namespace Umbraco.Web.BackOffice.Controllers var memberGroup = _memberGroupService.GetById(id); if (memberGroup == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } _memberGroupService.Delete(memberGroup); @@ -129,14 +126,14 @@ namespace Umbraco.Web.BackOffice.Controllers return _umbracoMapper.Map(item); } - public MemberGroupDisplay PostSave(MemberGroupSave saveModel) + public ActionResult PostSave(MemberGroupSave saveModel) { var id = int.Parse(saveModel.Id.ToString()); var memberGroup = id > 0 ? _memberGroupService.GetById(id) : new MemberGroup(); if (memberGroup == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } memberGroup.Name = saveModel.Name; diff --git a/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs index e203386958..7944da1f0a 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs @@ -1,31 +1,19 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; -using System.Net; -using System.Net.Http; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; using Umbraco.Core.Dictionary; -using Umbraco.Core.Logging; +using Umbraco.Core.Mapping; using Umbraco.Core.Models; -using Umbraco.Core.Persistence; +using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.Strings; -using Umbraco.Web.Models.ContentEditing; -using Constants = Umbraco.Core.Constants; -using Umbraco.Core.Mapping; -using Umbraco.Core.Security; -using Umbraco.Web.BackOffice.Controllers; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.Editors; -using Umbraco.Web.Routing; -using Umbraco.Web.Security; -using Microsoft.AspNetCore.Authorization; using Umbraco.Web.Common.Authorization; +using Umbraco.Web.Editors; +using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.BackOffice.Controllers { @@ -74,15 +62,15 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public MemberTypeDisplay GetById(int id) + public ActionResult GetById(int id) { - var ct = _memberTypeService.Get(id); - if (ct == null) + var mt = _memberTypeService.Get(id); + if (mt == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } - var dto =_umbracoMapper.Map(ct); + var dto =_umbracoMapper.Map(mt); return dto; } @@ -92,12 +80,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public MemberTypeDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var memberType = _memberTypeService.Get(id); if (memberType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(memberType); @@ -110,16 +98,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public MemberTypeDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var memberType = _memberTypeService.Get(guidUdi.Guid); if (memberType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var dto = _umbracoMapper.Map(memberType); @@ -138,7 +126,7 @@ namespace Umbraco.Web.BackOffice.Controllers var foundType = _memberTypeService.Get(id); if (foundType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } _memberTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); @@ -163,7 +151,16 @@ namespace Umbraco.Web.BackOffice.Controllers [FromQuery]string[] filterContentTypes, [FromQuery]string[] filterPropertyTypes) { - var result = PerformGetAvailableCompositeContentTypes(contentTypeId, UmbracoObjectTypes.MemberType, filterContentTypes, filterPropertyTypes, false) + var actionResult = PerformGetAvailableCompositeContentTypes(contentTypeId, + UmbracoObjectTypes.MemberType, filterContentTypes, filterPropertyTypes, + false); + + if (!(actionResult.Result is null)) + { + return actionResult.Result; + } + + var result = actionResult.Value .Select(x => new { contentType = x.Item1, @@ -221,7 +218,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (ct.IsSensitiveProperty(foundOnContentType.Alias) && prop.IsSensitiveData == false) { //if these don't match, then we cannot continue, this user is not allowed to change this value - throw new HttpResponseException(HttpStatusCode.Forbidden); + return Forbid(); } } } @@ -230,7 +227,7 @@ namespace Umbraco.Web.BackOffice.Controllers //if it is new, then we can just verify if any property has sensitive data turned on which is not allowed if (props.Any(prop => prop.IsSensitiveData)) { - throw new HttpResponseException(HttpStatusCode.Forbidden); + return Forbid(); } } } @@ -241,7 +238,12 @@ namespace Umbraco.Web.BackOffice.Controllers getContentType: i => ct, saveContentType: type => _memberTypeService.Save(type)); - var display =_umbracoMapper.Map(savedCt); + if (!(savedCt.Result is null)) + { + return savedCt.Result; + } + + var display =_umbracoMapper.Map(savedCt.Value); display.AddSuccessNotification( _localizedTextService.Localize("speechBubbles/memberTypeSavedHeader"), @@ -249,7 +251,5 @@ namespace Umbraco.Web.BackOffice.Controllers return display; } - - } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs b/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs index 7f6bfe781f..d900076e03 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -10,12 +10,14 @@ using Microsoft.Net.Http.Headers; using Semver; using Umbraco.Core; using Umbraco.Core.Hosting; +using Umbraco.Core.Models; using Umbraco.Core.Models.Packaging; using Umbraco.Core.Security; using Umbraco.Core.Services; +using Umbraco.Extensions; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; namespace Umbraco.Web.BackOffice.Controllers { @@ -45,11 +47,11 @@ namespace Umbraco.Web.BackOffice.Controllers return _packagingService.GetAllCreatedPackages(); } - public PackageDefinition GetCreatedPackageById(int id) + public ActionResult GetCreatedPackageById(int id) { var package = _packagingService.GetCreatedPackageById(id); if (package == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); return package; } @@ -64,14 +66,14 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - public PackageDefinition PostSavePackage(PackageDefinition model) + public ActionResult PostSavePackage(PackageDefinition model) { if (ModelState.IsValid == false) - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); //save it if (!_packagingService.SaveCreatedPackage(model)) - throw HttpResponseException.CreateNotificationValidationErrorResponse( + return ValidationErrorResult.CreateNotificationValidationErrorResult( model.Id == default ? $"A package with the name {model.Name} already exists" : $"The package with id {model.Id} was not found"); @@ -105,7 +107,7 @@ namespace Umbraco.Web.BackOffice.Controllers var fullPath = _hostingEnvironment.MapPathWebRoot(package.PackagePath); if (!System.IO.File.Exists(fullPath)) - throw HttpResponseException.CreateNotificationValidationErrorResponse("No file found for path " + package.PackagePath); + return ValidationErrorResult.CreateNotificationValidationErrorResult("No file found for path " + package.PackagePath); var fileName = Path.GetFileName(package.PackagePath); @@ -126,10 +128,10 @@ namespace Umbraco.Web.BackOffice.Controllers } - public PackageDefinition GetInstalledPackageById(int id) + public ActionResult GetInstalledPackageById(int id) { var pack = _packagingService.GetInstalledPackageById(id); - if (pack == null) throw new HttpResponseException(HttpStatusCode.NotFound); + if (pack == null) return NotFound(); return pack; } diff --git a/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs b/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs index d1f5d36b0f..a8a191de1a 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -15,14 +15,12 @@ using Umbraco.Core.Packaging; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.WebAssets; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models; using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Security; using Microsoft.AspNetCore.Authorization; using Umbraco.Web.Common.Authorization; +using Umbraco.Web.Common.ActionsResults; namespace Umbraco.Web.BackOffice.Controllers { @@ -189,7 +187,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (installType == PackageInstallType.AlreadyInstalled) { //this package is already installed - throw HttpResponseException.CreateNotificationValidationErrorResponse( + return ValidationErrorResult.CreateNotificationValidationErrorResult( _localizedTextService.Localize("packager/packageAlreadyInstalled")); } @@ -216,7 +214,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [HttpGet] - public async Task Fetch(string packageGuid) + public async Task> Fetch(string packageGuid) { //Default path string fileName = packageGuid + ".umb"; @@ -243,7 +241,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (installType == PackageInstallType.AlreadyInstalled) { - throw HttpResponseException.CreateNotificationValidationErrorResponse( + return ValidationErrorResult.CreateNotificationValidationErrorResult( _localizedTextService.Localize("packager/packageAlreadyInstalled")); } @@ -258,7 +256,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [HttpPost] - public PackageInstallModel Import(PackageInstallModel model) + public ActionResult Import(PackageInstallModel model) { var zipFile = new FileInfo(Path.Combine(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Packages), model.ZipFileName)); @@ -269,7 +267,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var packageMinVersion = packageInfo.UmbracoVersion; if (_umbracoVersion.Current < packageMinVersion) - throw HttpResponseException.CreateNotificationValidationErrorResponse( + return ValidationErrorResult.CreateNotificationValidationErrorResult( _localizedTextService.Localize("packager/targetVersionMismatch", new[] {packageMinVersion.ToString()})); } @@ -288,7 +286,7 @@ namespace Umbraco.Web.BackOffice.Controllers //save to the installedPackages.config, this will create a new entry with a new Id if (!_packagingService.SaveInstalledPackage(packageDefinition)) - throw HttpResponseException.CreateNotificationValidationErrorResponse("Could not save the package"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Could not save the package"); model.Id = packageDefinition.Id; break; diff --git a/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs b/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs index 0405012898..eec088478f 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.Extensions.Options; using System; using System.IO; +using System.Linq; using System.Threading.Tasks; using Umbraco.Core; using Umbraco.Core.Configuration; @@ -43,6 +44,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly ICookieManager _cookieManager; private readonly IRuntimeMinifier _runtimeMinifier; private readonly ICompositeViewEngine _viewEngines; + private readonly IUmbracoContextAccessor _umbracoContextAccessor; public PreviewController( UmbracoFeatures features, @@ -53,7 +55,8 @@ namespace Umbraco.Web.BackOffice.Controllers IHostingEnvironment hostingEnvironment, ICookieManager cookieManager, IRuntimeMinifier runtimeMinifier, - ICompositeViewEngine viewEngines) + ICompositeViewEngine viewEngines, + IUmbracoContextAccessor umbracoContextAccessor) { _features = features; _globalSettings = globalSettings.Value; @@ -64,14 +67,22 @@ namespace Umbraco.Web.BackOffice.Controllers _cookieManager = cookieManager; _runtimeMinifier = runtimeMinifier; _viewEngines = viewEngines; + _umbracoContextAccessor = umbracoContextAccessor; } [Authorize(Policy = AuthorizationPolicies.BackOfficeAccessWithoutApproval)] [DisableBrowserCache] - public ActionResult Index() + public ActionResult Index(int? id = null) { var availableLanguages = _localizationService.GetAllLanguages(); + if (id.HasValue) + { + var content = _umbracoContextAccessor.UmbracoContext.Content.GetById(true, id.Value); + if (content is null) + return NotFound(); + availableLanguages = availableLanguages.Where(language => content.Cultures.ContainsKey(language.IsoCode)); + } var model = new BackOfficePreviewModel(_features, availableLanguages); if (model.PreviewExtendedHeaderView.IsNullOrWhiteSpace() == false) @@ -90,6 +101,7 @@ namespace Umbraco.Web.BackOffice.Controllers return View(viewPath, model); } + /// /// Returns the JavaScript file for preview /// diff --git a/src/Umbraco.Web.BackOffice/Controllers/RelationTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/RelationTypeController.cs index b2706babee..0a6d174bdd 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/RelationTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/RelationTypeController.cs @@ -1,7 +1,6 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; -using System.Net; using System.Net.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; @@ -12,10 +11,9 @@ using Umbraco.Core.Strings; using Umbraco.Web.Models.ContentEditing; using Constants = Umbraco.Core.Constants; using Umbraco.Core.Mapping; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; using Microsoft.AspNetCore.Authorization; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Authorization; namespace Umbraco.Web.BackOffice.Controllers @@ -50,13 +48,13 @@ namespace Umbraco.Web.BackOffice.Controllers /// The relation type ID. /// Returns the . [DetermineAmbiguousActionByPassingParameters] - public RelationTypeDisplay GetById(int id) + public ActionResult GetById(int id) { var relationType = _relationService.GetRelationTypeById(id); if (relationType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var display = _umbracoMapper.Map(relationType); @@ -69,12 +67,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// The relation type ID. /// Returns the . [DetermineAmbiguousActionByPassingParameters] - public RelationTypeDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var relationType = _relationService.GetRelationTypeById(id); if (relationType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return _umbracoMapper.Map(relationType); } @@ -85,16 +83,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// The relation type ID. /// Returns the . [DetermineAmbiguousActionByPassingParameters] - public RelationTypeDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var relationType = _relationService.GetRelationTypeById(guidUdi.Guid); if (relationType == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return _umbracoMapper.Map(relationType); } @@ -144,7 +142,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// The relation type to create. /// A containing the persisted relation type's ID. - public int PostCreate(RelationTypeSave relationType) + public ActionResult PostCreate(RelationTypeSave relationType) { var relationTypePersisted = new RelationType(relationType.Name, relationType.Name.ToSafeAlias(_shortStringHelper, true), relationType.IsBidirectional, relationType.ChildObjectType, relationType.ParentObjectType); @@ -157,7 +155,7 @@ namespace Umbraco.Web.BackOffice.Controllers catch (Exception ex) { _logger.LogError(ex, "Error creating relation type with {Name}", relationType.Name); - throw HttpResponseException.CreateNotificationValidationErrorResponse("Error creating relation type."); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Error creating relation type."); } } @@ -166,13 +164,13 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// The relation type to update. /// A display object containing the updated relation type. - public RelationTypeDisplay PostSave(RelationTypeSave relationType) + public ActionResult PostSave(RelationTypeSave relationType) { var relationTypePersisted = _relationService.GetRelationTypeById(relationType.Key); if (relationTypePersisted == null) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("Relation type does not exist"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Relation type does not exist"); } _umbracoMapper.Map(relationType, relationTypePersisted); @@ -188,7 +186,7 @@ namespace Umbraco.Web.BackOffice.Controllers catch (Exception ex) { _logger.LogError(ex, "Error saving relation type with {Id}", relationType.Id); - throw HttpResponseException.CreateNotificationValidationErrorResponse("Something went wrong when saving the relation type"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("Something went wrong when saving the relation type"); } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs b/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs index f3c0415b75..5b1e5fb18a 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Infrastructure; using Umbraco.Core; @@ -8,12 +9,10 @@ using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Security; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Controllers; using Umbraco.Web.BackOffice.Trees; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Trees; -using Umbraco.Web.Security; using Umbraco.Web.Services; namespace Umbraco.Web.BackOffice.Controllers @@ -50,7 +49,7 @@ namespace Umbraco.Web.BackOffice.Controllers _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; } - public async Task> GetSections() + public async Task>> GetSections() { var sections = _sectionService.GetAllowedSections(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); @@ -76,7 +75,12 @@ namespace Umbraco.Web.BackOffice.Controllers // get the first tree in the section and get its root node route path var sectionRoot = await appTreeController.GetApplicationTrees(section.Alias, null, null); - section.RoutePath = GetRoutePathForFirstTree(sectionRoot); + + if (!(sectionRoot.Result is null)) + { + return sectionRoot.Result; + } + section.RoutePath = GetRoutePathForFirstTree(sectionRoot.Value); } return sectionModels; diff --git a/src/Umbraco.Web.BackOffice/Controllers/TemplateController.cs b/src/Umbraco.Web.BackOffice/Controllers/TemplateController.cs index fe75cf5a0a..560e3bc78c 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/TemplateController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/TemplateController.cs @@ -1,7 +1,6 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; -using System.Net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Umbraco.Core; @@ -10,10 +9,8 @@ using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Core.Strings; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; using Constants = Umbraco.Core.Constants; @@ -63,11 +60,11 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public TemplateDisplay GetById(int id) + public ActionResult GetById(int id) { var template = _fileService.GetTemplate(id); if (template == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); return _umbracoMapper.Map(template); } @@ -79,11 +76,11 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public TemplateDisplay GetById(Guid id) + public ActionResult GetById(Guid id) { var template = _fileService.GetTemplate(id); if (template == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); return _umbracoMapper.Map(template); } @@ -94,16 +91,16 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [DetermineAmbiguousActionByPassingParameters] - public TemplateDisplay GetById(Udi id) + public ActionResult GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var template = _fileService.GetTemplate(guidUdi.Guid); if (template == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } return _umbracoMapper.Map(template); @@ -120,7 +117,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var template = _fileService.GetTemplate(id); if (template == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); _fileService.DeleteTemplate(template.Alias); return Ok(); @@ -167,7 +164,7 @@ namespace Umbraco.Web.BackOffice.Controllers // update var template = _fileService.GetTemplate(display.Id); if (template == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var changeMaster = template.MasterTemplateAlias != display.MasterTemplateAlias; var changeAlias = template.Alias != display.Alias; @@ -239,7 +236,7 @@ namespace Umbraco.Web.BackOffice.Controllers { master = _fileService.GetTemplate(display.MasterTemplateAlias); if (master == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } // we need to pass the template name as alias to keep the template file casing consistent with templates created with content diff --git a/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs b/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs index 64aef74257..ff5ade53c1 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs @@ -1,7 +1,8 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Umbraco.Core.Mapping; using Umbraco.Core.Models; @@ -9,15 +10,13 @@ using Umbraco.Core.Models.Membership; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.Strings; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.BackOffice.ActionResults; +using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.Authorization; using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Security; using Constants = Umbraco.Core.Constants; -using Microsoft.AspNetCore.Authorization; -using Umbraco.Web.Common.Authorization; namespace Umbraco.Web.BackOffice.Controllers { @@ -52,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Controllers } [UserGroupValidate] - public UserGroupDisplay PostSaveUserGroup(UserGroupSave userGroupSave) + public ActionResult PostSaveUserGroup(UserGroupSave userGroupSave) { if (userGroupSave == null) throw new ArgumentNullException(nameof(userGroupSave)); @@ -62,14 +61,14 @@ namespace Umbraco.Web.BackOffice.Controllers var isAuthorized = authHelper.AuthorizeGroupAccess(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, userGroupSave.Alias); if (isAuthorized == false) - throw new HttpResponseException(HttpStatusCode.Unauthorized, isAuthorized.Result); + return Unauthorized(isAuthorized.Result); //if sections were added we need to check that the current user has access to that section isAuthorized = authHelper.AuthorizeSectionChanges(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, userGroupSave.PersistedUserGroup.AllowedSections, userGroupSave.Sections); if (isAuthorized == false) - throw new HttpResponseException(HttpStatusCode.Unauthorized, isAuthorized.Result); + return Unauthorized(isAuthorized.Result); //if start nodes were changed we need to check that the current user has access to them isAuthorized = authHelper.AuthorizeStartNodeChanges(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, @@ -78,7 +77,7 @@ namespace Umbraco.Web.BackOffice.Controllers userGroupSave.PersistedUserGroup.StartMediaId, userGroupSave.StartMediaId); if (isAuthorized == false) - throw new HttpResponseException(HttpStatusCode.Unauthorized, isAuthorized.Result); + return Unauthorized(isAuthorized.Result); //need to ensure current user is in a group if not an admin to avoid a 401 EnsureNonAdminUserIsInSavedUserGroup(userGroupSave); diff --git a/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs b/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs index fca8c49004..b543146f19 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization; using System.Security.Cryptography; +using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -14,7 +16,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; @@ -35,13 +36,9 @@ using Umbraco.Web.BackOffice.Security; using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Editors; using Umbraco.Web.Models; using Umbraco.Web.Models.ContentEditing; -using Constants = Umbraco.Core.Constants; -using IUser = Umbraco.Core.Models.Membership.IUser; -using Task = System.Threading.Tasks.Task; namespace Umbraco.Web.BackOffice.Controllers { @@ -122,27 +119,27 @@ namespace Umbraco.Web.BackOffice.Controllers /// Returns a list of the sizes of gravatar URLs for the user or null if the gravatar server cannot be reached /// /// - public string[] GetCurrentUserAvatarUrls() + public ActionResult GetCurrentUserAvatarUrls() { var urls = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserAvatarUrls(_appCaches.RuntimeCache, _mediaFileSystem, _imageUrlGenerator); if (urls == null) - throw new HttpResponseException(HttpStatusCode.BadRequest, "Could not access Gravatar endpoint"); + return new ValidationErrorResult("Could not access Gravatar endpoint"); return urls; } [AppendUserModifiedHeader("id")] [Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)] - public IActionResult PostSetAvatar(int id, IList files) + public IActionResult PostSetAvatar(int id, IList file) { - return PostSetAvatarInternal(files, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, id); + return PostSetAvatarInternal(file, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, id); } internal static IActionResult PostSetAvatarInternal(IList files, IUserService userService, IAppCache cache, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, ContentSettings contentSettings, IHostingEnvironment hostingEnvironment, IImageUrlGenerator imageUrlGenerator, int id) { if (files is null) { - throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); + return new UnsupportedMediaTypeResult(); } var root = hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads); @@ -160,7 +157,7 @@ namespace Umbraco.Web.BackOffice.Controllers return new NotFoundResult(); if (files.Count > 1) - throw HttpResponseException.CreateValidationErrorResponse("The request was not formatted correctly, only one file can be attached to the request"); + return new ValidationErrorResult("The request was not formatted correctly, only one file can be attached to the request"); //get the file info var file = files.First(); @@ -225,12 +222,12 @@ namespace Umbraco.Web.BackOffice.Controllers /// [OutgoingEditorModelEvent] [Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)] - public UserDisplay GetById(int id) + public ActionResult GetById(int id) { var user = _userService.GetUserById(id); if (user == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var result = _umbracoMapper.Map(user); return result; @@ -243,20 +240,20 @@ namespace Umbraco.Web.BackOffice.Controllers /// [OutgoingEditorModelEvent] [Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)] - public IEnumerable GetByIds([FromJsonPath]int[] ids) + public ActionResult> GetByIds([FromJsonPath]int[] ids) { if (ids == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } if (ids.Length == 0) - return Enumerable.Empty(); + return Enumerable.Empty().ToList(); var users = _userService.GetUsersById(ids); if (users == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var result = _umbracoMapper.MapEnumerable(users); @@ -337,13 +334,13 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - public async Task PostCreateUser(UserInvite userSave) + public async Task> PostCreateUser(UserInvite userSave) { if (userSave == null) throw new ArgumentNullException("userSave"); if (ModelState.IsValid == false) { - throw new HttpResponseException(HttpStatusCode.BadRequest, ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } if (_securitySettings.UsernameIsEmail) @@ -358,11 +355,16 @@ namespace Umbraco.Web.BackOffice.Controllers } CheckUniqueEmail(userSave.Email, null); + if (ModelState.IsValid == false) + { + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); + } + //Perform authorization here to see if the current user can actually save this user with the info being requested var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, null, null, null, userSave.UserGroups); if (canSaveUser == false) { - throw new HttpResponseException(HttpStatusCode.Unauthorized, canSaveUser.Result); + return Unauthorized(canSaveUser.Result); } //we want to create the user with the UserManager, this ensures the 'empty' (special) password @@ -373,7 +375,7 @@ namespace Umbraco.Web.BackOffice.Controllers var created = await _userManager.CreateAsync(identityUser); if (created.Succeeded == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse(created.Errors.ToErrorMessage()); + return ValidationErrorResult.CreateNotificationValidationErrorResult(created.Errors.ToErrorMessage()); } string resetPassword; @@ -382,7 +384,7 @@ namespace Umbraco.Web.BackOffice.Controllers var result = await _userManager.AddPasswordAsync(identityUser, password); if (result.Succeeded == false) { - throw HttpResponseException.CreateNotificationValidationErrorResponse(created.Errors.ToErrorMessage()); + return ValidationErrorResult.CreateNotificationValidationErrorResult(created.Errors.ToErrorMessage()); } resetPassword = password; @@ -418,11 +420,6 @@ namespace Umbraco.Web.BackOffice.Controllers if (userSave.Message.IsNullOrWhiteSpace()) ModelState.AddModelError("Message", "Message cannot be empty"); - if (ModelState.IsValid == false) - { - return new ValidationErrorResult(ModelState); - } - IUser user; if (_securitySettings.UsernameIsEmail) { @@ -432,10 +429,21 @@ namespace Umbraco.Web.BackOffice.Controllers else { //first validate the username if we're showing it - user = CheckUniqueUsername(userSave.Username, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue); + var userResult = CheckUniqueUsername(userSave.Username, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue); + if (!(userResult.Result is null)) + { + return userResult.Result; + } + + user = userResult.Value; } user = CheckUniqueEmail(userSave.Email, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue); + if (ModelState.IsValid == false) + { + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); + } + if (!EmailSender.CanSendRequiredEmail(_globalSettings) && !_userManager.HasSendingUserInviteEventHandler) { return new ValidationErrorResult("No Email server is configured"); @@ -519,12 +527,11 @@ namespace Umbraco.Web.BackOffice.Controllers if (user != null && (extraCheck == null || extraCheck(user))) { ModelState.AddModelError("Email", "A user with the email already exists"); - throw new HttpResponseException(HttpStatusCode.BadRequest, ModelState); } return user; } - private IUser CheckUniqueUsername(string username, Func extraCheck) + private ActionResult CheckUniqueUsername(string username, Func extraCheck) { var user = _userService.GetByUsername(username); if (user != null && (extraCheck == null || extraCheck(user))) @@ -532,9 +539,10 @@ namespace Umbraco.Web.BackOffice.Controllers ModelState.AddModelError( _securitySettings.UsernameIsEmail ? "Email" : "Username", "A user with the username already exists"); - throw new HttpResponseException(HttpStatusCode.BadRequest, ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } - return user; + + return new ActionResult(user); } private async Task SendUserInviteEmailAsync(UserBasic userDisplay, string from, string fromEmail, IUser to, string message) @@ -548,9 +556,12 @@ namespace Umbraco.Web.BackOffice.Controllers token.ToUrlBase64()); // Get an mvc helper to get the URL - var action = _linkGenerator.GetPathByAction("VerifyInvite", "BackOffice", new + var action = _linkGenerator.GetPathByAction( + nameof(BackOfficeController.VerifyInvite), + ControllerExtensions.GetControllerName(), + new { - area = _globalSettings.GetUmbracoMvcArea(_hostingEnvironment), + area = Constants.Web.Mvc.BackOfficeArea, invite = inviteToken }); @@ -577,28 +588,29 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// [OutgoingEditorModelEvent] - public UserDisplay PostSaveUser(UserSave userSave) + public ActionResult PostSaveUser(UserSave userSave) { if (userSave == null) throw new ArgumentNullException(nameof(userSave)); if (ModelState.IsValid == false) { - throw new HttpResponseException(HttpStatusCode.BadRequest, ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } var intId = userSave.Id.TryConvertTo(); if (intId.Success == false) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); + var found = _userService.GetUserById(intId.Result); if (found == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); //Perform authorization here to see if the current user can actually save this user with the info being requested var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, found, userSave.StartContentIds, userSave.StartMediaIds, userSave.UserGroups); if (canSaveUser == false) { - throw new HttpResponseException(HttpStatusCode.Unauthorized, canSaveUser.Result); + return Unauthorized(canSaveUser.Result); } var hasErrors = false; @@ -645,7 +657,7 @@ namespace Umbraco.Web.BackOffice.Controllers } if (hasErrors) - throw new HttpResponseException(HttpStatusCode.BadRequest, ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); //merge the save data onto the user var user = _umbracoMapper.Map(userSave, found); @@ -654,7 +666,16 @@ namespace Umbraco.Web.BackOffice.Controllers var display = _umbracoMapper.Map(user); - display.AddSuccessNotification(_localizedTextService.Localize("speechBubbles/operationSavedHeader"), _localizedTextService.Localize("speechBubbles/editUserSaved")); + // determine if the user has changed their own language; + var currentUser = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; + var userHasChangedOwnLanguage = + user.Id == currentUser.Id && currentUser.Language != user.Language; + + var textToLocalise = userHasChangedOwnLanguage ? "speechBubbles/operationSavedHeaderReloadUser" : "speechBubbles/operationSavedHeader"; + var culture = userHasChangedOwnLanguage + ? CultureInfo.GetCultureInfo(user.Language) + : Thread.CurrentThread.CurrentUICulture; + display.AddSuccessNotification(_localizedTextService.Localize(textToLocalise, culture), _localizedTextService.Localize("speechBubbles/editUserSaved", culture)); return display; } @@ -663,25 +684,25 @@ namespace Umbraco.Web.BackOffice.Controllers /// /// /// - public async Task> PostChangePassword(ChangingPasswordModel changingPasswordModel) + public async Task>> PostChangePassword(ChangingPasswordModel changingPasswordModel) { changingPasswordModel = changingPasswordModel ?? throw new ArgumentNullException(nameof(changingPasswordModel)); if (ModelState.IsValid == false) { - throw new HttpResponseException(HttpStatusCode.BadRequest, ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } var intId = changingPasswordModel.Id.TryConvertTo(); if (intId.Success == false) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var found = _userService.GetUserById(intId.Result); if (found == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } // TODO: Why don't we inject this? Then we can just inject a logger @@ -700,7 +721,7 @@ namespace Umbraco.Web.BackOffice.Controllers ModelState.AddModelError(memberName, passwordChangeResult.Result.ChangeError.ErrorMessage); } - throw HttpResponseException.CreateValidationErrorResponse(ModelState); + return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary())); } @@ -714,7 +735,7 @@ namespace Umbraco.Web.BackOffice.Controllers var tryGetCurrentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId(); if (tryGetCurrentUserId && userIds.Contains(tryGetCurrentUserId.Result)) { - throw HttpResponseException.CreateNotificationValidationErrorResponse("The current user cannot disable itself"); + return ValidationErrorResult.CreateNotificationValidationErrorResult("The current user cannot disable itself"); } var users = _userService.GetUsersById(userIds).ToArray(); @@ -781,8 +802,8 @@ namespace Umbraco.Web.BackOffice.Controllers var unlockResult = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.Now); if (unlockResult.Succeeded == false) { - throw HttpResponseException.CreateValidationErrorResponse( - string.Format("Could not unlock for user {0} - error {1}", u, unlockResult.Errors.ToErrorMessage())); + return new ValidationErrorResult( + $"Could not unlock for user {u} - error {unlockResult.Errors.ToErrorMessage()}"); } if (userIds.Length == 1) diff --git a/src/Umbraco.Web.BackOffice/DependencyInjection/UmbracoBuilderExtensions.cs b/src/Umbraco.Web.BackOffice/DependencyInjection/UmbracoBuilderExtensions.cs index 739a90b7c4..6587f3c6e4 100644 --- a/src/Umbraco.Web.BackOffice/DependencyInjection/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Web.BackOffice/DependencyInjection/UmbracoBuilderExtensions.cs @@ -40,7 +40,7 @@ namespace Umbraco.Web.BackOffice.DependencyInjection .AddBackOfficeAuthentication() .AddBackOfficeIdentity() .AddBackOfficeAuthorizationPolicies() - .AddMiniProfiler() + .AddUmbracoProfiler() .AddMvcAndRazor() .AddWebServer() .AddPreviewSupport() diff --git a/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs index 04adab4a27..c33d416cc7 100644 --- a/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; using Umbraco.Core; using Umbraco.Core.Security; -using Umbraco.Web.Security; namespace Umbraco.Web.BackOffice.Filters { @@ -44,8 +43,8 @@ namespace Umbraco.Web.BackOffice.Filters throw new InvalidOperationException($"No argument found for the current action with the name: {_userIdParameter}"); } - var backofficeSecurity = context.HttpContext.RequestServices.GetService(); - var user = backofficeSecurity.CurrentUser; + var backofficeSecurityAccessor = context.HttpContext.RequestServices.GetService(); + var user = backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (user == null) { return; diff --git a/src/Umbraco.Web.BackOffice/Filters/DataTypeValidateAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/DataTypeValidateAttribute.cs index b67cd17afc..26c3b419ba 100644 --- a/src/Umbraco.Web.BackOffice/Filters/DataTypeValidateAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/DataTypeValidateAttribute.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net; using Microsoft.AspNetCore.Mvc; @@ -10,7 +10,6 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Extensions; using Umbraco.Web.Common.ActionsResults; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.BackOffice.Filters @@ -106,7 +105,7 @@ namespace Umbraco.Web.BackOffice.Filters if (context.ModelState.IsValid == false) { // if it is not valid, do not continue and return the model state - throw HttpResponseException.CreateValidationErrorResponse(context.ModelState); + context.Result = new ValidationErrorResult(context.ModelState); } } } diff --git a/src/Umbraco.Web.BackOffice/Filters/UserGroupValidateAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/UserGroupValidateAttribute.cs index 8c6e85a44c..f6647ea1d7 100644 --- a/src/Umbraco.Web.BackOffice/Filters/UserGroupValidateAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/UserGroupValidateAttribute.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; @@ -7,7 +7,7 @@ using Umbraco.Core.Mapping; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; using Umbraco.Web.BackOffice.ActionResults; -using Umbraco.Web.Common.Exceptions; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.BackOffice.Filters @@ -86,7 +86,7 @@ namespace Umbraco.Web.BackOffice.Filters if (context.ModelState.IsValid == false) { //if it is not valid, do not continue and return the model state - throw HttpResponseException.CreateValidationErrorResponse(context.ModelState); + context.Result = new ValidationErrorResult(context.ModelState); } } diff --git a/src/Umbraco.Web.BackOffice/ModelBinders/ContentModelBinderHelper.cs b/src/Umbraco.Web.BackOffice/ModelBinders/ContentModelBinderHelper.cs index adea4dcc3c..0ed360214b 100644 --- a/src/Umbraco.Web.BackOffice/ModelBinders/ContentModelBinderHelper.cs +++ b/src/Umbraco.Web.BackOffice/ModelBinders/ContentModelBinderHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Net; using System.Threading.Tasks; @@ -60,7 +60,7 @@ namespace Umbraco.Web.BackOffice.ModelBinders if (parts.Length < 2) { bindingContext.HttpContext.SetReasonPhrase( "The request was not formatted correctly the file name's must be underscore delimited"); - throw new HttpResponseException(HttpStatusCode.BadRequest); + return null; } var propAlias = parts[1]; diff --git a/src/Umbraco.Web.BackOffice/Trees/ApplicationTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/ApplicationTreeController.cs index 000740e27e..22667f0c30 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ApplicationTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ApplicationTreeController.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net; -using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -15,13 +13,11 @@ using Umbraco.Core.Services; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Controllers; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Common.Filters; using Umbraco.Web.Common.ModelBinders; using Umbraco.Web.Models.Trees; using Umbraco.Web.Services; using Umbraco.Web.Trees; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Trees { @@ -62,16 +58,16 @@ namespace Umbraco.Web.BackOffice.Trees /// /// Tree use. /// - public async Task GetApplicationTrees(string application, string tree, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormCollection queryStrings, TreeUse use = TreeUse.Main) + public async Task> GetApplicationTrees(string application, string tree, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormCollection queryStrings, TreeUse use = TreeUse.Main) { application = application.CleanForXss(); if (string.IsNullOrEmpty(application)) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var section = _sectionService.GetByAlias(application); if (section == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); //find all tree definitions that have the current application alias var groupedTrees = _treeService.GetBySectionGrouped(application, use); @@ -93,13 +89,16 @@ namespace Umbraco.Web.BackOffice.Trees : allTrees.FirstOrDefault(x => x.TreeAlias == tree); if (t == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); var treeRootNode = await GetTreeRootNode(t, Constants.System.Root, queryStrings); - if (treeRootNode != null) - return treeRootNode; - throw new HttpResponseException(HttpStatusCode.NotFound); + if (treeRootNode != null) + { + return treeRootNode; + } + + return NotFound(); } // handle requests for all trees @@ -109,7 +108,12 @@ namespace Umbraco.Web.BackOffice.Trees var nodes = new TreeNodeCollection(); foreach (var t in allTrees) { - var node = await TryGetRootNode(t, queryStrings); + var nodeResult = await TryGetRootNode(t, queryStrings); + if (!(nodeResult.Result is null)) + { + return nodeResult.Result; + } + var node = nodeResult.Value; if (node != null) nodes.Add(node); } @@ -135,7 +139,13 @@ namespace Umbraco.Web.BackOffice.Trees var nodes = new TreeNodeCollection(); foreach (var t in trees) { - var node = await TryGetRootNode(t, queryStrings); + var nodeResult = await TryGetRootNode(t, queryStrings); + if (!(nodeResult.Result is null)) + { + return nodeResult.Result; + } + var node = nodeResult.Value; + if (node != null) nodes.Add(node); } @@ -160,37 +170,42 @@ namespace Umbraco.Web.BackOffice.Trees /// Tries to get the root node of a tree. /// /// - /// Returns null if the root node could not be obtained due to an HttpResponseException, - /// which probably indicates that the user isn't authorized to view that tree. + /// Returns null if the root node could not be obtained due to that + /// the user isn't authorized to view that tree. In this case since we are + /// loading multiple trees we will just return null so that it's not added + /// to the list /// - private async Task TryGetRootNode(Tree tree, FormCollection querystring) + private async Task> TryGetRootNode(Tree tree, FormCollection querystring) { if (tree == null) throw new ArgumentNullException(nameof(tree)); - try - { - return await GetRootNode(tree, querystring); - } - catch (HttpResponseException) - { - // if this occurs its because the user isn't authorized to view that tree, - // in this case since we are loading multiple trees we will just return - // null so that it's not added to the list. - return null; - } + return await GetRootNode(tree, querystring); } /// /// Get the tree root node of a tree. /// - private async Task GetTreeRootNode(Tree tree, int id, FormCollection querystring) + private async Task> GetTreeRootNode(Tree tree, int id, FormCollection querystring) { if (tree == null) throw new ArgumentNullException(nameof(tree)); - var children = await GetChildren(tree, id, querystring); - var rootNode = await GetRootNode(tree, querystring); + var childrenResult = await GetChildren(tree, id, querystring); + if (!(childrenResult.Result is null)) + { + return new ActionResult(childrenResult.Result); + } + + var children = childrenResult.Value; + var rootNodeResult = await GetRootNode(tree, querystring); + if (!(rootNodeResult.Result is null)) + { + return rootNodeResult.Result; + } + + var rootNode = rootNodeResult.Value; + var sectionRoot = TreeRootNode.CreateSingleTreeRoot( Constants.System.RootString, @@ -214,13 +229,28 @@ namespace Umbraco.Web.BackOffice.Trees /// /// Gets the root node of a tree. /// - private async Task GetRootNode(Tree tree, FormCollection querystring) + private async Task> GetRootNode(Tree tree, FormCollection querystring) { if (tree == null) throw new ArgumentNullException(nameof(tree)); - var controller = (TreeControllerBase)await GetApiControllerProxy(tree.TreeControllerType, "GetRootNode", querystring); - var rootNode = controller.GetRootNode(querystring); + var result = await GetApiControllerProxy(tree.TreeControllerType, "GetRootNode", querystring); + + // return null if the user isn't authorized to view that tree + if (!((ForbidResult)result.Result is null)) + { + return null; + } + + var controller = (TreeControllerBase)result.Value; + var rootNodeResult = controller.GetRootNode(querystring); + if (!(rootNodeResult.Result is null)) + { + return rootNodeResult.Result; + } + + var rootNode = rootNodeResult.Value; + if (rootNode == null) throw new InvalidOperationException($"Failed to get root node for tree \"{tree.TreeAlias}\"."); return rootNode; @@ -229,7 +259,7 @@ namespace Umbraco.Web.BackOffice.Trees /// /// Get the child nodes of a tree node. /// - private async Task GetChildren(Tree tree, int id, FormCollection querystring) + private async Task> GetChildren(Tree tree, int id, FormCollection querystring) { if (tree == null) throw new ArgumentNullException(nameof(tree)); @@ -241,7 +271,13 @@ namespace Umbraco.Web.BackOffice.Trees d["id"] = StringValues.Empty; var proxyQuerystring = new FormCollection(d); - var controller = (TreeControllerBase)await GetApiControllerProxy(tree.TreeControllerType, "GetNodes", proxyQuerystring); + var controllerResult = await GetApiControllerProxy(tree.TreeControllerType, "GetNodes", proxyQuerystring); + if (!(controllerResult.Result is null)) + { + return new ActionResult(controllerResult.Result); + } + + var controller = (TreeControllerBase)controllerResult.Value; return controller.GetNodes(id.ToInvariantString(), querystring); } @@ -257,7 +293,7 @@ namespace Umbraco.Web.BackOffice.Trees /// and context etc. so it can execute the specified . Runs the authorization /// filters for that action, to ensure that the user has permission to execute it. /// - private async Task GetApiControllerProxy(Type controllerType, string action, FormCollection querystring) + private async Task> GetApiControllerProxy(Type controllerType, string action, FormCollection querystring) { // note: this is all required in order to execute the auth-filters for the sub request, we // need to "trick" mvc into thinking that it is actually executing the proxied controller. @@ -289,11 +325,9 @@ namespace Umbraco.Web.BackOffice.Trees var isAllowed = await controller.ControllerContext.InvokeAuthorizationFiltersForRequest(actionContext); if (!isAllowed) - throw new HttpResponseException(HttpStatusCode.Forbidden); + return Forbid(); return controller; } - - } } diff --git a/src/Umbraco.Web.BackOffice/Trees/ContentBlueprintTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/ContentBlueprintTreeController.cs index e232bf03b9..c0396b68e6 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ContentBlueprintTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ContentBlueprintTreeController.cs @@ -1,19 +1,18 @@ -using System; +using System; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Services; using Umbraco.Web.Actions; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Trees { @@ -49,9 +48,14 @@ namespace Umbraco.Web.BackOffice.Trees _entityService = entityService ?? throw new ArgumentNullException(nameof(entityService)); } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; //this will load in a custom UI instead of the dashboard for the root node root.RoutePath = $"{Constants.Applications.Settings}/{Constants.Trees.ContentBlueprints}/intro"; @@ -61,7 +65,7 @@ namespace Umbraco.Web.BackOffice.Trees return root; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); @@ -112,7 +116,7 @@ namespace Umbraco.Web.BackOffice.Trees return nodes; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs index 404ebfdb3a..4c139847f0 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs @@ -1,28 +1,26 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; -using System.Net; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; -using Umbraco.Core.Services; -using Umbraco.Web.Actions; -using Umbraco.Web.Models.Trees; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Search; using Umbraco.Core.Security; -using Constants = Umbraco.Core.Constants; -using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.WebApi; -using Umbraco.Core.Configuration.Models; -using Microsoft.Extensions.Options; -using Umbraco.Web.Trees; -using Microsoft.AspNetCore.Authorization; -using Umbraco.Web.Common.Authorization; +using Umbraco.Core.Services; using Umbraco.Core.Trees; +using Umbraco.Web.Actions; +using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.Authorization; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; +using Umbraco.Web.Search; +using Umbraco.Web.Trees; +using Umbraco.Web.WebApi; namespace Umbraco.Web.BackOffice.Trees { @@ -142,7 +140,7 @@ namespace Umbraco.Web.BackOffice.Trees return null; } - protected override MenuItemCollection PerformGetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult PerformGetMenuForNode(string id, FormCollection queryStrings) { if (id == Constants.System.RootString) { @@ -186,12 +184,12 @@ namespace Umbraco.Web.BackOffice.Trees int iid; if (int.TryParse(id, out iid) == false) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var item = _entityService.Get(iid, UmbracoObjectTypes.Document); if (item == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } //if the user has no path access for this node, all they can do is refresh @@ -236,16 +234,22 @@ namespace Umbraco.Web.BackOffice.Trees return HasPathAccess(entity, queryStrings); } - protected override IEnumerable GetChildEntities(string id, FormCollection queryStrings) + protected override ActionResult> GetChildEntities(string id, FormCollection queryStrings) { var result = base.GetChildEntities(id, queryStrings); + + if (!(result.Result is null)) + { + return result.Result; + } + var culture = queryStrings["culture"].TryConvertTo(); //if this is null we'll set it to the default. var cultureVal = (culture.Success ? culture.Result : null) ?? _localizationService.GetDefaultLanguageIsoCode(); // set names according to variations - foreach (var entity in result) + foreach (var entity in result.Value) { EnsureName(entity, cultureVal); } diff --git a/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs b/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs index 53a6f02a79..212b4dd890 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs @@ -1,22 +1,19 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Net; -using Microsoft.Extensions.Logging; -using Umbraco.Core; -using Umbraco.Core.Services; -using Umbraco.Core.Models; -using Umbraco.Web.Models.Trees; -using Umbraco.Core.Models.Entities; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Umbraco.Web.Actions; +using Microsoft.Extensions.Logging; +using Umbraco.Core; +using Umbraco.Core.Models; +using Umbraco.Core.Models.Entities; using Umbraco.Core.Security; +using Umbraco.Core.Services; using Umbraco.Extensions; -using Umbraco.Web.Common.Exceptions; +using Umbraco.Web.Actions; using Umbraco.Web.Common.ModelBinders; -using Umbraco.Web.Security; +using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; @@ -98,9 +95,14 @@ namespace Umbraco.Web.BackOffice.Trees /// /// /// - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var node = base.CreateRootNode(queryStrings); + var nodeResult = base.CreateRootNode(queryStrings); + if ((nodeResult.Result is null)) + { + return nodeResult; + } + var node = nodeResult.Value; if (IsDialog(queryStrings) && UserStartNodes.Contains(Constants.System.Root) == false && IgnoreUserStartNodes(queryStrings) == false) { @@ -174,7 +176,7 @@ namespace Umbraco.Web.BackOffice.Trees /// protected abstract int[] UserStartNodes { get; } - protected virtual TreeNodeCollection PerformGetTreeNodes(string id, FormCollection queryStrings) + protected virtual ActionResult PerformGetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); @@ -211,7 +213,13 @@ namespace Umbraco.Web.BackOffice.Trees // get child entities - if id is root, but user's start nodes do not contain the // root node, this returns the start nodes instead of root's children - var entities = GetChildEntities(id, queryStrings).ToList(); + var entitiesResult = GetChildEntities(id, queryStrings); + if (!(entitiesResult.Result is null)) + { + return entitiesResult.Result; + } + + var entities = entitiesResult.Value.ToList(); //get the current user start node/paths GetUserStartNodes(out var userStartNodes, out var userStartNodePaths); @@ -253,11 +261,11 @@ namespace Umbraco.Web.BackOffice.Trees return parts.Length >= 2 && int.TryParse(parts[1], out id) ? id : 0; } - protected abstract MenuItemCollection PerformGetMenuForNode(string id, FormCollection queryStrings); + protected abstract ActionResult PerformGetMenuForNode(string id, FormCollection queryStrings); protected abstract UmbracoObjectTypes UmbracoObjectType { get; } - protected virtual IEnumerable GetChildEntities(string id, FormCollection queryStrings) + protected virtual ActionResult> GetChildEntities(string id, FormCollection queryStrings) { // try to parse id as an integer else use GetEntityFromId // which will grok Guids, Udis, etc and let use obtain the id @@ -265,7 +273,7 @@ namespace Umbraco.Web.BackOffice.Trees { var entity = GetEntityFromId(id); if (entity == null) - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); entityId = entity.Id; } @@ -325,7 +333,7 @@ namespace Umbraco.Web.BackOffice.Trees /// /// This method is overwritten strictly to render the recycle bin, it should serve no other purpose /// - protected sealed override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected sealed override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { //check if we're rendering the root if (id == Constants.System.RootString && UserStartNodes.Contains(Constants.System.Root)) @@ -341,7 +349,13 @@ namespace Umbraco.Web.BackOffice.Trees id = altStartId; } - var nodes = GetTreeNodesInternal(id, queryStrings); + var nodesResult = GetTreeNodesInternal(id, queryStrings); + if (!(nodesResult.Result is null)) + { + return nodesResult.Result; + } + + var nodes = nodesResult.Value; //only render the recycle bin if we are not in dialog and the start id is still the root //we need to check for the "application" key in the queryString because its value is required here, @@ -410,7 +424,7 @@ namespace Umbraco.Web.BackOffice.Trees /// /// Currently this just checks if it is a container type, if it is we cannot render children. In the future this might check for other things. /// - private TreeNodeCollection GetTreeNodesInternal(string id, FormCollection queryStrings) + private ActionResult GetTreeNodesInternal(string id, FormCollection queryStrings) { var current = GetEntityFromId(id); @@ -432,7 +446,7 @@ namespace Umbraco.Web.BackOffice.Trees /// /// /// - protected sealed override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected sealed override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { if (RecycleBinId.ToInvariantString() == id) { diff --git a/src/Umbraco.Web.BackOffice/Trees/ContentTypeTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/ContentTypeTreeController.cs index 25c48b94bd..f115e3e923 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ContentTypeTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ContentTypeTreeController.cs @@ -1,14 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Core.Trees; using Umbraco.Web.Actions; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.ContentEditing; @@ -38,15 +38,20 @@ namespace Umbraco.Web.BackOffice.Trees _entityService = entityService; } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; //check if there are any types root.HasChildren = _contentTypeService.GetAll().Any(); return root; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var intId = id.TryConvertTo(); if (intId == false) throw new InvalidOperationException("Id must be an integer"); @@ -97,7 +102,7 @@ namespace Umbraco.Web.BackOffice.Trees return nodes; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/DataTypeTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/DataTypeTreeController.cs index 30389fb1be..79cfee1ce7 100644 --- a/src/Umbraco.Web.BackOffice/Trees/DataTypeTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/DataTypeTreeController.cs @@ -1,22 +1,21 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; -using Umbraco.Web.Models.Trees; using Umbraco.Core.Services; +using Umbraco.Core.Trees; using Umbraco.Web.Actions; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Search; -using Constants = Umbraco.Core.Constants; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.Authorization; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; +using Umbraco.Web.Search; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Microsoft.AspNetCore.Authorization; -using Umbraco.Web.Common.Authorization; -using Umbraco.Core.Trees; namespace Umbraco.Web.BackOffice.Trees { @@ -40,7 +39,7 @@ namespace Umbraco.Web.BackOffice.Trees _dataTypeService = dataTypeService; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var intId = id.TryConvertTo(); if (intId == false) throw new InvalidOperationException("Id must be an integer"); @@ -119,7 +118,7 @@ namespace Umbraco.Web.BackOffice.Trees }; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/DictionaryTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/DictionaryTreeController.cs index 2dd145c654..87f7a1508f 100644 --- a/src/Umbraco.Web.BackOffice/Trees/DictionaryTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/DictionaryTreeController.cs @@ -1,7 +1,8 @@ -using System; +using System; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; @@ -32,9 +33,14 @@ namespace Umbraco.Web.BackOffice.Trees _localizationService = localizationService; } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; // the default section is settings, falling back to this if we can't // figure out where we are from the querystring parameters @@ -59,7 +65,7 @@ namespace Umbraco.Web.BackOffice.Trees /// We are allowing an arbitrary number of query strings to be passed in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var intId = id.TryConvertTo(); if (intId == false) @@ -109,7 +115,7 @@ namespace Umbraco.Web.BackOffice.Trees /// All of the query string parameters passed from jsTree /// /// - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs index 74d2ee90f8..ab77e00067 100644 --- a/src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs @@ -1,8 +1,9 @@ -using System; +using System; using System.IO; using System.Linq; using System.Net; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Services; @@ -45,7 +46,7 @@ namespace Umbraco.Web.BackOffice.Trees treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);"; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var path = string.IsNullOrEmpty(id) == false && id != Constants.System.RootString ? WebUtility.UrlDecode(id).TrimStart("/") @@ -92,11 +93,22 @@ namespace Umbraco.Web.BackOffice.Trees return nodes; } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; + //check if there are any children - root.HasChildren = GetTreeNodes(Constants.System.RootString, queryStrings).Any(); + var treeNodesResult = GetTreeNodes(Constants.System.RootString, queryStrings); + if (!(treeNodesResult.Result is null)) + { + return treeNodesResult.Result; + } + root.HasChildren = treeNodesResult.Value.Any(); return root; } @@ -148,7 +160,7 @@ namespace Umbraco.Web.BackOffice.Trees return menu; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { //if root node no need to visit the filesystem so lets just create the menu and return it if (id == Constants.System.RootString) diff --git a/src/Umbraco.Web.BackOffice/Trees/LanguageTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/LanguageTreeController.cs index ecd1c954ac..3dcbbc9da8 100644 --- a/src/Umbraco.Web.BackOffice/Trees/LanguageTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/LanguageTreeController.cs @@ -1,13 +1,13 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Umbraco.Core; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Trees { @@ -24,13 +24,13 @@ namespace Umbraco.Web.BackOffice.Trees : base(textService, umbracoApiControllerTypeCollection) { } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { //We don't have any child nodes & only use the root node to load a custom UI return new TreeNodeCollection(); } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { //We don't have any menu item options (such as create/delete/reload) & only use the root node to load a custom UI return null; @@ -40,9 +40,14 @@ namespace Umbraco.Web.BackOffice.Trees /// Helper method to create a root model for a tree /// /// - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; //this will load in a custom UI instead of the dashboard for the root node root.RoutePath = $"{Constants.Applications.Settings}/{Constants.Trees.Languages}/overview"; diff --git a/src/Umbraco.Web.BackOffice/Trees/LogViewerTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/LogViewerTreeController.cs index b03b2d9926..91b89cee69 100644 --- a/src/Umbraco.Web.BackOffice/Trees/LogViewerTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/LogViewerTreeController.cs @@ -1,13 +1,13 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Umbraco.Core; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Trees { @@ -24,13 +24,13 @@ namespace Umbraco.Web.BackOffice.Trees { } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { //We don't have any child nodes & only use the root node to load a custom UI return new TreeNodeCollection(); } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { //We don't have any menu item options (such as create/delete/reload) & only use the root node to load a custom UI return null; @@ -40,9 +40,14 @@ namespace Umbraco.Web.BackOffice.Trees /// Helper method to create a root model for a tree /// /// - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; //this will load in a custom UI instead of the dashboard for the root node root.RoutePath = string.Format("{0}/{1}/{2}", Constants.Applications.Settings, Constants.Trees.LogViewer, "overview"); diff --git a/src/Umbraco.Web.BackOffice/Trees/MacrosTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MacrosTreeController.cs index 518c1b5495..d59c5c8d3a 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MacrosTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MacrosTreeController.cs @@ -1,15 +1,15 @@ -using System.Linq; +using System.Linq; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Umbraco.Core; using Umbraco.Core.Services; -using Umbraco.Web.Models.Trees; using Umbraco.Web.Actions; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.Authorization; +using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Constants = Umbraco.Core.Constants; -using Microsoft.AspNetCore.Authorization; -using Umbraco.Web.Common.Authorization; namespace Umbraco.Web.BackOffice.Trees { @@ -28,15 +28,21 @@ namespace Umbraco.Web.BackOffice.Trees _macroService = macroService; } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; + //check if there are any macros root.HasChildren = _macroService.GetAll().Any(); return root; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); @@ -57,7 +63,7 @@ namespace Umbraco.Web.BackOffice.Trees return nodes; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs index d284624999..1354fc3d7c 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; @@ -21,6 +21,7 @@ using Umbraco.Web.Security; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; using Umbraco.Web.Common.Authorization; using Umbraco.Core.Trees; @@ -97,7 +98,7 @@ namespace Umbraco.Web.BackOffice.Trees return node; } - protected override MenuItemCollection PerformGetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult PerformGetMenuForNode(string id, FormCollection queryStrings) { var menu = MenuItemCollectionFactory.Create(); @@ -122,12 +123,12 @@ namespace Umbraco.Web.BackOffice.Trees if (int.TryParse(id, out var iid) == false) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } var item = _entityService.Get(iid, UmbracoObjectTypes.Media); if (item == null) { - throw new HttpResponseException(HttpStatusCode.NotFound); + return NotFound(); } //if the user has no path access for this node, all they can do is refresh diff --git a/src/Umbraco.Web.BackOffice/Trees/MediaTypeTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MediaTypeTreeController.cs index 424a0b2451..ff53a82219 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MediaTypeTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MediaTypeTreeController.cs @@ -1,21 +1,21 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; -using Umbraco.Web.Models.Trees; using Umbraco.Core.Services; +using Umbraco.Core.Trees; using Umbraco.Web.Actions; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Search; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.Authorization; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; +using Umbraco.Web.Search; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Microsoft.AspNetCore.Authorization; -using Umbraco.Web.Common.Authorization; -using Umbraco.Core.Trees; namespace Umbraco.Web.BackOffice.Trees { @@ -38,7 +38,7 @@ namespace Umbraco.Web.BackOffice.Trees _entityService = entityService; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var intId = id.TryConvertTo(); if (intId == false) throw new InvalidOperationException("Id must be an integer"); @@ -81,7 +81,7 @@ namespace Umbraco.Web.BackOffice.Trees return nodes; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/MemberGroupTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MemberGroupTreeController.cs index 817b32f301..5184325db8 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MemberGroupTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MemberGroupTreeController.cs @@ -2,9 +2,9 @@ using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.Trees; @@ -38,9 +38,15 @@ namespace Umbraco.Web.BackOffice.Trees .Select(dt => CreateTreeNode(dt.Id.ToString(), id, queryStrings, dt.Name, Constants.Icons.MemberGroup, false)); } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; + //check if there are any groups root.HasChildren = _memberGroupService.GetAll().Any(); return root; diff --git a/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs index 378a90da83..0a68c36e08 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs @@ -1,28 +1,24 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Security; using Umbraco.Core.Services; +using Umbraco.Core.Trees; using Umbraco.Extensions; using Umbraco.Web.Actions; -using Umbraco.Web.BackOffice.Filters; -using Umbraco.Web.BackOffice.Trees; using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.Authorization; using Umbraco.Web.Common.ModelBinders; -using Umbraco.Web.Models.Trees; using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; using Umbraco.Web.Search; -using Constants = Umbraco.Core.Constants; -using Umbraco.Web.Security; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Microsoft.AspNetCore.Authorization; -using Umbraco.Web.Common.Authorization; -using Umbraco.Core.Trees; namespace Umbraco.Web.BackOffice.Trees { @@ -101,7 +97,7 @@ namespace Umbraco.Web.BackOffice.Trees return node; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); @@ -125,7 +121,7 @@ namespace Umbraco.Web.BackOffice.Trees return nodes; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/MemberTypeAndGroupTreeControllerBase.cs b/src/Umbraco.Web.BackOffice/Trees/MemberTypeAndGroupTreeControllerBase.cs index d758d8b7f9..0804e78c8a 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MemberTypeAndGroupTreeControllerBase.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MemberTypeAndGroupTreeControllerBase.cs @@ -1,5 +1,6 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Services; using Umbraco.Web.Actions; @@ -25,14 +26,14 @@ namespace Umbraco.Web.BackOffice.Trees MenuItemCollectionFactory = menuItemCollectionFactory; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); nodes.AddRange(GetTreeNodesFromService(id, queryStrings)); return nodes; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = MenuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/MemberTypeTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MemberTypeTreeController.cs index 8a8fe7b11e..5d44d7c832 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MemberTypeTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MemberTypeTreeController.cs @@ -2,12 +2,11 @@ using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Core.Trees; -using Umbraco.Web.BackOffice.Filters; -using Umbraco.Web.BackOffice.Trees; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.ContentEditing; @@ -40,9 +39,15 @@ namespace Umbraco.Web.BackOffice.Trees } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; + //check if there are any member types root.HasChildren = _memberTypeService.GetAll().Any(); return root; diff --git a/src/Umbraco.Web.BackOffice/Trees/PackagesTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/PackagesTreeController.cs index 5c96bb4d64..9b80782725 100644 --- a/src/Umbraco.Web.BackOffice/Trees/PackagesTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/PackagesTreeController.cs @@ -1,13 +1,13 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Umbraco.Core; using Umbraco.Core.Services; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Trees { @@ -33,9 +33,15 @@ namespace Umbraco.Web.BackOffice.Trees /// Helper method to create a root model for a tree /// /// - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; + //this will load in a custom UI instead of the dashboard for the root node root.RoutePath = $"{Constants.Applications.Packages}/{Constants.Trees.Packages}/repo"; @@ -46,13 +52,13 @@ namespace Umbraco.Web.BackOffice.Trees } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { //full screen app without tree nodes return TreeNodeCollection.Empty; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { //doesn't have a menu, this is a full screen app without tree nodes return _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/RelationTypeTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/RelationTypeTreeController.cs index a36c2f36a9..2e200e8b0a 100644 --- a/src/Umbraco.Web.BackOffice/Trees/RelationTypeTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/RelationTypeTreeController.cs @@ -1,16 +1,16 @@ -using System.Linq; +using System.Linq; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; -using Umbraco.Web.Models.Trees; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Web.Actions; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; +using Umbraco.Web.Common.Authorization; +using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Microsoft.AspNetCore.Authorization; -using Umbraco.Web.Common.Authorization; namespace Umbraco.Web.BackOffice.Trees { @@ -34,7 +34,7 @@ namespace Umbraco.Web.BackOffice.Trees _relationService = relationService; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); @@ -60,7 +60,7 @@ namespace Umbraco.Web.BackOffice.Trees return menu; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); diff --git a/src/Umbraco.Web.BackOffice/Trees/TemplatesTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/TemplatesTreeController.cs index eb08dbe629..a8ebc71581 100644 --- a/src/Umbraco.Web.BackOffice/Trees/TemplatesTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/TemplatesTreeController.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; @@ -10,7 +11,6 @@ using Umbraco.Core.Services; using Umbraco.Core.Trees; using Umbraco.Extensions; using Umbraco.Web.Actions; -using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.ContentEditing; @@ -18,7 +18,6 @@ using Umbraco.Web.Models.Trees; using Umbraco.Web.Search; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Trees { @@ -45,9 +44,15 @@ namespace Umbraco.Web.BackOffice.Trees _fileService = fileService; } - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; + //check if there are any templates root.HasChildren = _fileService.GetTemplates(-1).Any(); return root; @@ -64,7 +69,7 @@ namespace Umbraco.Web.BackOffice.Trees /// We are allowing an arbitrary number of query strings to be pased in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); @@ -93,7 +98,7 @@ namespace Umbraco.Web.BackOffice.Trees /// /// /// - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { var menu = _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.BackOffice/Trees/TreeControllerBase.cs b/src/Umbraco.Web.BackOffice/Trees/TreeControllerBase.cs index ad4266e5e5..5c6f8a7fe8 100644 --- a/src/Umbraco.Web.BackOffice/Trees/TreeControllerBase.cs +++ b/src/Umbraco.Web.BackOffice/Trees/TreeControllerBase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -6,7 +6,6 @@ using Umbraco.Core; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; -using Umbraco.Core.Persistence; using Umbraco.Core.Trees; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Controllers; @@ -47,7 +46,7 @@ namespace Umbraco.Web.BackOffice.Trees /// We are allowing an arbitrary number of query strings to be passed in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// - protected abstract TreeNodeCollection GetTreeNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings); + protected abstract ActionResult GetTreeNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings); /// /// Returns the menu structure for the node @@ -55,7 +54,7 @@ namespace Umbraco.Web.BackOffice.Trees /// /// /// - protected abstract MenuItemCollection GetMenuForNode(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings); + protected abstract ActionResult GetMenuForNode(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings); /// /// The name to display on the root node @@ -88,10 +87,16 @@ namespace Umbraco.Web.BackOffice.Trees /// /// /// - public TreeNode GetRootNode([ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) + public ActionResult GetRootNode([ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) { if (queryStrings == null) queryStrings = FormCollection.Empty; - var node = CreateRootNode(queryStrings); + var nodeResult = CreateRootNode(queryStrings); + if (!(nodeResult.Result is null)) + { + return nodeResult.Result; + } + + var node = nodeResult.Value; //add the tree alias to the root node.AdditionalData["treeAlias"] = TreeAlias; @@ -123,10 +128,17 @@ namespace Umbraco.Web.BackOffice.Trees /// We are allowing an arbitrary number of query strings to be passed in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// - public TreeNodeCollection GetNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) + public ActionResult GetNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) { if (queryStrings == null) queryStrings = FormCollection.Empty; - var nodes = GetTreeNodes(id, queryStrings); + var nodesResult = GetTreeNodes(id, queryStrings); + + if (!(nodesResult.Result is null)) + { + return nodesResult.Result; + } + + var nodes = nodesResult.Value; foreach (var node in nodes) AddQueryStringsToAdditionalData(node, queryStrings); @@ -148,10 +160,16 @@ namespace Umbraco.Web.BackOffice.Trees /// /// /// - public MenuItemCollection GetMenu(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) + public ActionResult GetMenu(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))]FormCollection queryStrings) { if (queryStrings == null) queryStrings = FormCollection.Empty; - var menu = GetMenuForNode(id, queryStrings); + var menuResult = GetMenuForNode(id, queryStrings); + if (!(menuResult.Result is null)) + { + return menuResult.Result; + } + + var menu = menuResult.Value; //raise the event OnMenuRendering(this, new MenuRenderingEventArgs(id, menu, queryStrings)); return menu; @@ -161,7 +179,7 @@ namespace Umbraco.Web.BackOffice.Trees /// Helper method to create a root model for a tree /// /// - protected virtual TreeNode CreateRootNode(FormCollection queryStrings) + protected virtual ActionResult CreateRootNode(FormCollection queryStrings) { var rootNodeAsString = Constants.System.RootString; queryStrings.TryGetValue(TreeQueryStringParameters.Application, out var currApp); diff --git a/src/Umbraco.Web.BackOffice/Trees/UserTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/UserTreeController.cs index 960ed76ac5..f43247c09c 100644 --- a/src/Umbraco.Web.BackOffice/Trees/UserTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/UserTreeController.cs @@ -1,12 +1,13 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Umbraco.Core; using Umbraco.Core.Services; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Trees { @@ -31,9 +32,14 @@ namespace Umbraco.Web.BackOffice.Trees /// Helper method to create a root model for a tree /// /// - protected override TreeNode CreateRootNode(FormCollection queryStrings) + protected override ActionResult CreateRootNode(FormCollection queryStrings) { - var root = base.CreateRootNode(queryStrings); + var rootResult = base.CreateRootNode(queryStrings); + if (!(rootResult.Result is null)) + { + return rootResult; + } + var root = rootResult.Value; //this will load in a custom UI instead of the dashboard for the root node root.RoutePath = $"{Constants.Applications.Users}/{Constants.Trees.Users}/users"; @@ -43,13 +49,13 @@ namespace Umbraco.Web.BackOffice.Trees return root; } - protected override TreeNodeCollection GetTreeNodes(string id, FormCollection queryStrings) + protected override ActionResult GetTreeNodes(string id, FormCollection queryStrings) { //full screen app without tree nodes return TreeNodeCollection.Empty; } - protected override MenuItemCollection GetMenuForNode(string id, FormCollection queryStrings) + protected override ActionResult GetMenuForNode(string id, FormCollection queryStrings) { //doesn't have a menu, this is a full screen app without tree nodes return _menuItemCollectionFactory.Create(); diff --git a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreUmbracoApplicationLifetime.cs b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreUmbracoApplicationLifetime.cs index cdba8273a0..3854f92f8c 100644 --- a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreUmbracoApplicationLifetime.cs +++ b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreUmbracoApplicationLifetime.cs @@ -1,11 +1,9 @@ -using System; -using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; using Umbraco.Core.Hosting; namespace Umbraco.Web.Common.AspNetCore { - public class AspNetCoreUmbracoApplicationLifetime : IUmbracoApplicationLifetime, IUmbracoApplicationLifetimeManager + public class AspNetCoreUmbracoApplicationLifetime : IUmbracoApplicationLifetime { private readonly IHostApplicationLifetime _hostApplicationLifetime; @@ -21,13 +19,5 @@ namespace Umbraco.Web.Common.AspNetCore IsRestarting = true; _hostApplicationLifetime.StopApplication(); } - - public void InvokeApplicationInit() - { - ApplicationInit?.Invoke(this, EventArgs.Empty); - } - - // TODO: Should be killed and replaced with UmbracoApplicationStarting notifications - public event EventHandler ApplicationInit; } } diff --git a/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs b/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs index 3a0b929d52..4fe3b268c0 100644 --- a/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs +++ b/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs @@ -1,6 +1,4 @@ using System; -using System.Text; -using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; @@ -8,6 +6,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Umbraco.Core; @@ -69,6 +68,11 @@ namespace Umbraco.Web.Common.AspNetCore { WriteLiteral(htmlEncodedString.ToHtmlString()); } + else if (value is TagHelperOutput tagHelperOutput) + { + WriteUmbracoContent(tagHelperOutput); + base.Write(value); + } else { base.Write(value); @@ -76,18 +80,16 @@ namespace Umbraco.Web.Common.AspNetCore } /// - public override void WriteLiteral(object value) + public void WriteUmbracoContent(TagHelperOutput tagHelperOutput) { // filter / add preview banner // ASP.NET default value is text/html - if (Context.Response.ContentType.InvariantEquals("text/html")) + if (Context.Response.ContentType.InvariantContains("text/html")) { if (UmbracoContext.IsDebug || UmbracoContext.InPreviewMode) { - var text = value.ToString(); - var pos = text.IndexOf("", StringComparison.InvariantCultureIgnoreCase); - if (pos > -1) + if (tagHelperOutput.TagName.Equals("body", StringComparison.InvariantCultureIgnoreCase)) { string markupToInject; @@ -107,16 +109,10 @@ namespace Umbraco.Web.Common.AspNetCore markupToInject = ProfilerHtml.Render(); } - var sb = new StringBuilder(text); - sb.Insert(pos, markupToInject); - - WriteLiteral(sb.ToString()); - return; + tagHelperOutput.Content.AppendHtml(markupToInject); } } } - - base.WriteLiteral(value); } /// diff --git a/src/Umbraco.Web.Common/Controllers/UmbracoApiControllerBase.cs b/src/Umbraco.Web.Common/Controllers/UmbracoApiControllerBase.cs index 9f9e2b19be..364c3c1211 100644 --- a/src/Umbraco.Web.Common/Controllers/UmbracoApiControllerBase.cs +++ b/src/Umbraco.Web.Common/Controllers/UmbracoApiControllerBase.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Authorization; @@ -15,7 +15,6 @@ namespace Umbraco.Web.Common.Controllers /// The base class is which are netcore API controllers without any view support /// [Authorize(Policy = AuthorizationPolicies.UmbracoFeatureEnabled)] // TODO: This could be part of our conventions - [TypeFilter(typeof(HttpResponseExceptionFilter))] // TODO: This could be part of our conventions [UmbracoApiController] public abstract class UmbracoApiControllerBase : ControllerBase, IUmbracoFeature { diff --git a/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs b/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs index 0751eb582c..faa838673f 100644 --- a/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs @@ -22,8 +22,10 @@ using Umbraco.Core.Composing; using Umbraco.Core.Configuration.Models; using Umbraco.Core.DependencyInjection; using Umbraco.Core.Diagnostics; +using Umbraco.Core.Events; using Umbraco.Core.Hosting; using Umbraco.Core.Logging; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Security; @@ -124,7 +126,7 @@ namespace Umbraco.Web.Common.DependencyInjection // Add supported databases builder.AddUmbracoSqlServerSupport(); builder.AddUmbracoSqlCeSupport(); - + builder.Services.AddUnique(); // Must be added here because DbProviderFactories is netstandard 2.1 so cannot exist in Infra for now builder.Services.AddSingleton(factory => new DbProviderFactoryCreator( @@ -137,7 +139,7 @@ namespace Umbraco.Web.Common.DependencyInjection builder.AddCoreInitialServices(); // aspnet app lifetime mgmt - builder.Services.AddMultipleUnique(); + builder.Services.AddUnique(); builder.Services.AddUnique(); return builder; @@ -166,15 +168,18 @@ namespace Umbraco.Web.Common.DependencyInjection } /// - /// Adds mini profiler services for Umbraco + /// Adds the Umbraco request profiler /// - public static IUmbracoBuilder AddMiniProfiler(this IUmbracoBuilder builder) + public static IUmbracoBuilder AddUmbracoProfiler(this IUmbracoBuilder builder) { + builder.Services.AddUnique(); + builder.Services.AddMiniProfiler(options => // WebProfiler determine and start profiling. We should not use the MiniProfilerMiddleware to also profile options.ShouldProfile = request => false); + builder.AddNotificationHandler(); return builder; } diff --git a/src/Umbraco.Web.Common/Exceptions/HttpResponseException.cs b/src/Umbraco.Web.Common/Exceptions/HttpResponseException.cs deleted file mode 100644 index cb14a5a546..0000000000 --- a/src/Umbraco.Web.Common/Exceptions/HttpResponseException.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Runtime.Serialization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Umbraco.Web.Models.ContentEditing; - -namespace Umbraco.Web.Common.Exceptions -{ - [Serializable] - public class HttpResponseException : Exception - { - public HttpResponseException(HttpStatusCode status = HttpStatusCode.InternalServerError, object value = null) - { - Status = status; - Value = value; - } - - public HttpResponseException(ActionResult actionResult) - { - - Status = actionResult switch - { - IStatusCodeActionResult x => (HttpStatusCode)x.StatusCode.GetValueOrDefault((int)HttpStatusCode.InternalServerError), - _ => HttpStatusCode.InternalServerError - }; - - Value = actionResult switch - { - ObjectResult x => x.Value, - _ => null - }; - } - - public HttpStatusCode Status { get; set; } - public object Value { get; set; } - - public IDictionary AdditionalHeaders { get; } = new Dictionary(); - - - /// - /// When overridden in a derived class, sets the with information about the exception. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// info - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - info.AddValue(nameof(Status), Enum.GetName(typeof(HttpStatusCode), Status)); - info.AddValue(nameof(Value), Value); - info.AddValue(nameof(AdditionalHeaders), AdditionalHeaders); - - base.GetObjectData(info, context); - } - - public static HttpResponseException CreateValidationErrorResponse(object model) - { - return new HttpResponseException(HttpStatusCode.BadRequest, model) - { - AdditionalHeaders = - { - ["X-Status-Reason"] = "Validation failed" - } - }; - } - - public static HttpResponseException CreateNotificationValidationErrorResponse(string errorMessage) - { - var notificationModel = new SimpleNotificationModel - { - Message = errorMessage - }; - notificationModel.AddErrorNotification(errorMessage, string.Empty); - return CreateValidationErrorResponse(notificationModel); - } - - } -} diff --git a/src/Umbraco.Web.Common/Extensions/ApplicationBuilderExtensions.cs b/src/Umbraco.Web.Common/Extensions/ApplicationBuilderExtensions.cs index 73682ca6c5..eb33451e0b 100644 --- a/src/Umbraco.Web.Common/Extensions/ApplicationBuilderExtensions.cs +++ b/src/Umbraco.Web.Common/Extensions/ApplicationBuilderExtensions.cs @@ -60,6 +60,7 @@ namespace Umbraco.Extensions app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); + // This must come after auth because the culture is based on the auth'd user app.UseRequestLocalization(); diff --git a/src/Umbraco.Web.Common/Filters/HttpResponseExceptionFilter.cs b/src/Umbraco.Web.Common/Filters/HttpResponseExceptionFilter.cs deleted file mode 100644 index 6a5f6eaa47..0000000000 --- a/src/Umbraco.Web.Common/Filters/HttpResponseExceptionFilter.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Umbraco.Web.Common.Exceptions; - -namespace Umbraco.Web.Common.Filters -{ - public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter - { - public int Order { get; set; } = int.MaxValue - 10; - - public void OnActionExecuting(ActionExecutingContext context) { } - - public void OnActionExecuted(ActionExecutedContext context) - { - if (context.Exception is HttpResponseException exception) - { - context.Result = new ObjectResult(exception.Value) - { - StatusCode = (int)exception.Status, - }; - - foreach (var (key,value) in exception.AdditionalHeaders) - { - context.HttpContext.Response.Headers[key] = value; - } - - context.ExceptionHandled = true; - } - } - } -} diff --git a/src/Umbraco.Web.Common/Install/InstallApiController.cs b/src/Umbraco.Web.Common/Install/InstallApiController.cs index 6deecc2ce5..ab96707f94 100644 --- a/src/Umbraco.Web.Common/Install/InstallApiController.cs +++ b/src/Umbraco.Web.Common/Install/InstallApiController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -10,19 +10,15 @@ using Umbraco.Core; using Umbraco.Core.Hosting; using Umbraco.Core.Logging; using Umbraco.Core.Migrations.Install; +using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Common.Filters; -using Umbraco.Web.Common.Security; using Umbraco.Web.Install; using Umbraco.Web.Install.Models; namespace Umbraco.Web.Common.Install { - using Constants = Umbraco.Core.Constants; - [UmbracoApiController] - [TypeFilter(typeof(HttpResponseExceptionFilter))] [AngularJsonOnlyConfiguration] [InstallAuthorize] [Area(Umbraco.Core.Constants.Web.Mvc.InstallArea)] @@ -96,7 +92,7 @@ namespace Umbraco.Web.Common.Install /// /// Installs. /// - public async Task PostPerformInstall(InstallInstructions installModel) + public async Task> PostPerformInstall(InstallInstructions installModel) { if (installModel == null) throw new ArgumentNullException(nameof(installModel)); @@ -157,7 +153,7 @@ namespace Umbraco.Web.Common.Install var installException = ex as InstallException; if (installException != null) { - throw HttpResponseException.CreateValidationErrorResponse(new + return new ValidationErrorResult(new { view = installException.View, model = installException.ViewModel, @@ -165,7 +161,7 @@ namespace Umbraco.Web.Common.Install }); } - throw HttpResponseException.CreateValidationErrorResponse(new + return new ValidationErrorResult(new { step = step.Name, view = "error", diff --git a/src/Umbraco.Web.Common/Profiler/InitializeWebProfiling.cs b/src/Umbraco.Web.Common/Profiler/InitializeWebProfiling.cs new file mode 100644 index 0000000000..fede88e14f --- /dev/null +++ b/src/Umbraco.Web.Common/Profiler/InitializeWebProfiling.cs @@ -0,0 +1,64 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Umbraco.Core.Events; +using Umbraco.Core.Logging; +using Umbraco.Web.Common.Lifetime; + +namespace Umbraco.Web.Common.Profiler +{ + /// + /// Initialized the web profiling. Ensures the boot process profiling is stopped. + /// + public class InitializeWebProfiling : INotificationHandler + { + private readonly bool _profile; + private readonly WebProfiler _profiler; + private readonly IUmbracoRequestLifetime _umbracoRequestLifetime; + + /// + /// Initializes a new instance of the class. + /// + public InitializeWebProfiling(IProfiler profiler, IUmbracoRequestLifetime umbracoRequestLifetime, ILogger logger) + { + _umbracoRequestLifetime = umbracoRequestLifetime; + _profile = true; + + // although registered in UmbracoBuilderExtensions.AddUmbraco, ensure that we have not + // been replaced by another component, and we are still "the" profiler + _profiler = profiler as WebProfiler; + if (_profiler != null) + { + return; + } + + // if VoidProfiler was registered, let it be known + if (profiler is NoopProfiler) + { + logger.LogInformation( + "Profiler is VoidProfiler, not profiling (must run debug mode to profile)."); + } + + _profile = false; + } + + /// + public Task HandleAsync(UmbracoApplicationStarting notification, CancellationToken cancellationToken) + { + if (_profile) + { + _umbracoRequestLifetime.RequestStart += (sender, context) => _profiler.UmbracoApplicationBeginRequest(context); + + _umbracoRequestLifetime.RequestEnd += (sender, context) => _profiler.UmbracoApplicationEndRequest(context); + + // Stop the profiling of the booting process + _profiler.StopBoot(); + } + + return Task.CompletedTask; + } + } +} diff --git a/src/Umbraco.Web.Common/Profiler/WebProfilerComponent.cs b/src/Umbraco.Web.Common/Profiler/WebProfilerComponent.cs deleted file mode 100644 index 498b550c1a..0000000000 --- a/src/Umbraco.Web.Common/Profiler/WebProfilerComponent.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; -using Umbraco.Web.Common.Lifetime; -using Umbraco.Web.Common.Middleware; -using Umbraco.Core.Hosting; - -namespace Umbraco.Web.Common.Profiler -{ - internal sealed class WebProfilerComponent : IComponent - { - private readonly bool _profile; - private readonly WebProfiler _profiler; - private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime; - private readonly IUmbracoRequestLifetime _umbracoRequestLifetime; - private readonly List _terminate = new List(); - - public WebProfilerComponent(IProfiler profiler, ILogger logger, IUmbracoRequestLifetime umbracoRequestLifetime, - IUmbracoApplicationLifetime umbracoApplicationLifetime) - { - _umbracoRequestLifetime = umbracoRequestLifetime; - _umbracoApplicationLifetime = umbracoApplicationLifetime; - _profile = true; - - // although registered in WebRuntime.Compose, ensure that we have not - // been replaced by another component, and we are still "the" profiler - _profiler = profiler as WebProfiler; - if (_profiler != null) return; - - // if VoidProfiler was registered, let it be known - if (profiler is NoopProfiler) - logger.LogInformation( - "Profiler is VoidProfiler, not profiling (must run debug mode to profile)."); - _profile = false; - } - - public void Initialize() - { - if (!_profile) return; - - // bind to ApplicationInit - ie execute the application initialization for *each* application - // it would be a mistake to try and bind to the current application events - _umbracoApplicationLifetime.ApplicationInit += InitializeApplication; - } - - public void Terminate() - { - _umbracoApplicationLifetime.ApplicationInit -= InitializeApplication; - foreach (var t in _terminate) t(); - } - - private void InitializeApplication(object sender, EventArgs args) - { - void requestStart(object sender, HttpContext context) => _profiler.UmbracoApplicationBeginRequest(context); - _umbracoRequestLifetime.RequestStart += requestStart; - _terminate.Add(() => _umbracoRequestLifetime.RequestStart -= requestStart); - - void requestEnd(object sender, HttpContext context) => _profiler.UmbracoApplicationEndRequest(context); - _umbracoRequestLifetime.RequestEnd += requestEnd; - _terminate.Add(() => _umbracoRequestLifetime.RequestEnd -= requestEnd); - - // Stop the profiling of the booting process - _profiler.StopBoot(); - } - } -} diff --git a/src/Umbraco.Web.Common/Profiler/WebProfilerComposer.cs b/src/Umbraco.Web.Common/Profiler/WebProfilerComposer.cs deleted file mode 100644 index eac3e058c2..0000000000 --- a/src/Umbraco.Web.Common/Profiler/WebProfilerComposer.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Umbraco.Core.DependencyInjection; -using Umbraco.Core.Composing; - -namespace Umbraco.Web.Common.Profiler -{ - internal class WebProfilerComposer : ComponentComposer, ICoreComposer - { - public override void Compose(IUmbracoBuilder builder) - { - base.Compose(builder); - - builder.Services.AddUnique(); - } - } -} diff --git a/src/Umbraco.Web.Common/Runtime/AspNetCoreComponent.cs b/src/Umbraco.Web.Common/Runtime/AspNetCoreComponent.cs deleted file mode 100644 index 5c7e47cf3f..0000000000 --- a/src/Umbraco.Web.Common/Runtime/AspNetCoreComponent.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Hosting; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Hosting; -using Umbraco.Web.Common.Lifetime; - -namespace Umbraco.Web.Common.Runtime -{ - public sealed class AspNetCoreComponent : IComponent - { - private readonly IHostApplicationLifetime _hostApplicationLifetime; - private readonly IUmbracoApplicationLifetimeManager _umbracoApplicationLifetimeManager; - - public AspNetCoreComponent( - IHostApplicationLifetime hostApplicationLifetime, - IUmbracoApplicationLifetimeManager umbracoApplicationLifetimeManager) - { - _hostApplicationLifetime = hostApplicationLifetime; - _umbracoApplicationLifetimeManager = umbracoApplicationLifetimeManager; - } - - public void Initialize() - { - _hostApplicationLifetime.ApplicationStarted.Register(() => { - _umbracoApplicationLifetimeManager.InvokeApplicationInit(); - }); - } - - - - public void Terminate() - { - } - } -} diff --git a/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs b/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs deleted file mode 100644 index 1eda1cc23a..0000000000 --- a/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Umbraco.Core.Composing; -namespace Umbraco.Web.Common.Runtime -{ - - /// - /// Adds/replaces AspNetCore specific services - /// - [ComposeBefore(typeof(ICoreComposer))] - public class AspNetCoreComposer : ComponentComposer, IComposer - { - } -} diff --git a/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs b/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs index 1ea44b1596..9d8fdd9174 100644 --- a/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs +++ b/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs @@ -1,10 +1,5 @@ -using System; -using System.Security; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Options; +using Microsoft.AspNetCore.Http; using Umbraco.Core; -using Umbraco.Core.Configuration.Models; -using Umbraco.Core.Hosting; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Security; @@ -18,34 +13,39 @@ namespace Umbraco.Web.Common.Security public class BackOfficeSecurity : IBackOfficeSecurity { private readonly IUserService _userService; - private readonly GlobalSettings _globalSettings; - private readonly IHostingEnvironment _hostingEnvironment; private readonly IHttpContextAccessor _httpContextAccessor; + private object _currentUserLock = new object(); + private IUser _currentUser; + public BackOfficeSecurity( IUserService userService, - IOptions globalSettings, - IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor) { _userService = userService; - _globalSettings = globalSettings.Value; - _hostingEnvironment = hostingEnvironment; _httpContextAccessor = httpContextAccessor; } - private IUser _currentUser; + /// public IUser CurrentUser { get { + //only load it once per instance! (but make sure groups are loaded) if (_currentUser == null) { - var id = GetUserId(); - _currentUser = id ? _userService.GetUserById(id.Result) : null; + lock (_currentUserLock) + { + //Check again + if (_currentUser == null) + { + var id = GetUserId(); + _currentUser = id ? _userService.GetUserById(id.Result) : null; + } + } } return _currentUser; diff --git a/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs b/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs index d212f5a1e3..528f2f564c 100644 --- a/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs +++ b/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs @@ -1,9 +1,5 @@ using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.Models; -using Umbraco.Core.Hosting; using Umbraco.Core.Security; using Umbraco.Core.Services; @@ -15,21 +11,15 @@ namespace Umbraco.Web.Common.Security { private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor; private readonly IUserService _userService; - private readonly IOptions _globalSettings; - private readonly IHostingEnvironment _hostingEnvironment; private readonly IHttpContextAccessor _httpContextAccessor; public BackOfficeSecurityFactory( IBackOfficeSecurityAccessor backofficeSecurityAccessor, IUserService userService, - IOptions globalSettings, - IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor) { _backOfficeSecurityAccessor = backofficeSecurityAccessor; _userService = userService; - _globalSettings = globalSettings; - _hostingEnvironment = hostingEnvironment; _httpContextAccessor = httpContextAccessor; } @@ -37,7 +27,7 @@ namespace Umbraco.Web.Common.Security { if (_backOfficeSecurityAccessor.BackOfficeSecurity is null) { - _backOfficeSecurityAccessor.BackOfficeSecurity = new BackOfficeSecurity(_userService, _globalSettings, _hostingEnvironment, _httpContextAccessor); + _backOfficeSecurityAccessor.BackOfficeSecurity = new BackOfficeSecurity(_userService, _httpContextAccessor); } } diff --git a/src/Umbraco.Web.UI.Client/gulp/tasks/dependencies.js b/src/Umbraco.Web.UI.Client/gulp/tasks/dependencies.js index 179faeb843..e8336b2177 100644 --- a/src/Umbraco.Web.UI.Client/gulp/tasks/dependencies.js +++ b/src/Umbraco.Web.UI.Client/gulp/tasks/dependencies.js @@ -30,14 +30,17 @@ function dependencies() { "./node_modules/ace-builds/src-min-noconflict/snippets/javascript.js", "./node_modules/ace-builds/src-min-noconflict/snippets/css.js", "./node_modules/ace-builds/src-min-noconflict/snippets/json.js", + "./node_modules/ace-builds/src-min-noconflict/snippets/xml.js", "./node_modules/ace-builds/src-min-noconflict/theme-chrome.js", "./node_modules/ace-builds/src-min-noconflict/mode-razor.js", "./node_modules/ace-builds/src-min-noconflict/mode-javascript.js", "./node_modules/ace-builds/src-min-noconflict/mode-css.js", + "./node_modules/ace-builds/src-min-noconflict/mode-json.js", + "./node_modules/ace-builds/src-min-noconflict/mode-xml.js", "./node_modules/ace-builds/src-min-noconflict/worker-javascript.js", "./node_modules/ace-builds/src-min-noconflict/worker-css.js", - "./node_modules/ace-builds/src-min-noconflict/mode-json.js", - "./node_modules/ace-builds/src-min-noconflict/worker-json.js" + "./node_modules/ace-builds/src-min-noconflict/worker-json.js", + "./node_modules/ace-builds/src-min-noconflict/worker-xml.js" ], "base": "./node_modules/ace-builds" }, diff --git a/src/Umbraco.Web.UI.Client/package-lock.json b/src/Umbraco.Web.UI.Client/package-lock.json index dfbdbc34d4..dea27a0d69 100644 --- a/src/Umbraco.Web.UI.Client/package-lock.json +++ b/src/Umbraco.Web.UI.Client/package-lock.json @@ -948,7 +948,7 @@ "@sindresorhus/is": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.7.0.tgz", - "integrity": "sha512-ONhaKPIufzzrlNbqtWFFd+jlnemX6lJAgq9ZeiZtS7I1PIf/la7CW4m83rTXRnVnsMbW2k56pGYu7AUFJD9Pow==", + "integrity": "sha1-mgb08TfuhNffBGDB/bETX/psUP0=", "dev": true, "optional": true }, @@ -970,7 +970,7 @@ "@types/minimatch": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", - "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "integrity": "sha1-PcoOPzOyAPx9ETnAzZbBJoyt/Z0=", "dev": true }, "@types/node": { @@ -1593,7 +1593,7 @@ "array-union": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "integrity": "sha1-t5hCCtvrHego2ErNii4j0+/oXo0=", "dev": true }, "array-uniq": { @@ -1877,7 +1877,7 @@ "bin-build": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/bin-build/-/bin-build-3.0.0.tgz", - "integrity": "sha512-jcUOof71/TNAI2uM5uoUaDq2ePcVBQ3R/qhxAz1rX7UfvduAL/RXD3jXzvn8cVcDJdGVkiR1shal3OH0ImpuhA==", + "integrity": "sha1-xXgKJaip+WbYJEIX5sH1CCoUOGE=", "dev": true, "optional": true, "requires": { @@ -1928,7 +1928,7 @@ "bin-check": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/bin-check/-/bin-check-4.1.0.tgz", - "integrity": "sha512-b6weQyEUKsDGFlACWSIOfveEnImkJyK/FGW6FAG42loyoquvjdtOIqO6yBFzHyqyVVhNgNkQxxx09SFLK28YnA==", + "integrity": "sha1-/ElZcL3Ii7HVo1/BfmXEoUn8Skk=", "dev": true, "optional": true, "requires": { @@ -1976,7 +1976,7 @@ "bin-version": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bin-version/-/bin-version-3.1.0.tgz", - "integrity": "sha512-Mkfm4iE1VFt4xd4vH+gx+0/71esbfus2LsnCGe8Pi4mndSPyT+NGES/Eg99jx8/lUGWfu3z2yuB/bt5UB+iVbQ==", + "integrity": "sha1-WwnrKAdSsb0o8MnbP5by9DtsCDk=", "dev": true, "optional": true, "requires": { @@ -1987,7 +1987,7 @@ "bin-version-check": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/bin-version-check/-/bin-version-check-4.0.0.tgz", - "integrity": "sha512-sR631OrhC+1f8Cvs8WyVWOA33Y8tgwjETNPyyD/myRBXLkfS/vl74FmH/lFcRl9KY3zwGh7jFhvyk9vV3/3ilQ==", + "integrity": "sha1-fYGcYklpkfgNiT5uAqMDI2Fgj3E=", "dev": true, "optional": true, "requires": { @@ -1999,7 +1999,7 @@ "bin-wrapper": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/bin-wrapper/-/bin-wrapper-4.1.0.tgz", - "integrity": "sha512-hfRmo7hWIXPkbpi0ZltboCMVrU+0ClXR/JgbCKKjlDjQf6igXa7OwdqNcFWQZPZTgiY7ZpzE3+LjjkLiTN2T7Q==", + "integrity": "sha1-mTSPLPhQMePvfvzn5TAK6q6WBgU=", "dev": true, "optional": true, "requires": { @@ -2014,7 +2014,7 @@ "download": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/download/-/download-7.1.0.tgz", - "integrity": "sha512-xqnBTVd/E+GxJVrX5/eUJiLYjCGPwMpdL+jGhGU57BvtcA7wwhtHVbXBeUk51kOpW3S7Jn3BQbN9Q1R1Km2qDQ==", + "integrity": "sha1-kFmqnXC1A+52oTKJe+beyOVYcjM=", "dev": true, "optional": true, "requires": { @@ -2044,7 +2044,7 @@ "file-type": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/file-type/-/file-type-8.1.0.tgz", - "integrity": "sha512-qyQ0pzAy78gVoJsmYeNgl8uH8yKhr1lVhW7JbzJmnlRi0I4R2eEDEJZVKG8agpDnLpacwNbDhLNG/LMdxHD2YQ==", + "integrity": "sha1-JE87fvZBu+DMoZbHJ25LMyOZ9ow=", "dev": true, "optional": true }, @@ -2058,7 +2058,7 @@ "got": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/got/-/got-8.3.2.tgz", - "integrity": "sha512-qjUJ5U/hawxosMryILofZCkm3C84PLJS/0grRIpjAwu+Lkxxj5cxeCU25BG0/3mDSpXKTyZr8oh8wIgLaH0QCw==", + "integrity": "sha1-HSP2Q5Dpf3dsrFLluTbl9RTS6Tc=", "dev": true, "optional": true, "requires": { @@ -2093,7 +2093,7 @@ "make-dir": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", - "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "integrity": "sha1-ecEDO4BRW9bSTsmTPoYMp17ifww=", "dev": true, "optional": true, "requires": { @@ -2112,14 +2112,14 @@ "p-cancelable": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-0.4.1.tgz", - "integrity": "sha512-HNa1A8LvB1kie7cERyy21VNeHb2CWJJYqyyC2o3klWFfMGlFmWv2Z7sFgZH8ZiaYL95ydToKTFVXgMV/Os0bBQ==", + "integrity": "sha1-NfNj1n1SCByNlYXje8zrfgu8sqA=", "dev": true, "optional": true }, "p-event": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/p-event/-/p-event-2.3.1.tgz", - "integrity": "sha512-NQCqOFhbpVTMX4qMe8PF8lbGtzZ+LCiN7pcNrb/413Na7+TRoe1xkKUzuWa/YEJdGQ0FvKtj35EEbDoVPO2kbA==", + "integrity": "sha1-WWJ57xaassPgyuiMHPuwgHmZPvY=", "dev": true, "optional": true, "requires": { @@ -2129,7 +2129,7 @@ "p-timeout": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-2.0.1.tgz", - "integrity": "sha512-88em58dDVB/KzPEx1X0N3LwFfYZPyDc4B6eF38M1rk9VTZMbxXXgjugz8mmwpS9Ox4BDZ+t6t3QP5+/gazweIA==", + "integrity": "sha1-2N0ZeVldLcATnh/ka4tkbLPN8Dg=", "dev": true, "optional": true, "requires": { @@ -2139,7 +2139,7 @@ "pify": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", - "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "integrity": "sha1-SyzSXFDVmHNcUCkiJP2MbfQeMjE=", "dev": true, "optional": true }, @@ -2204,7 +2204,7 @@ }, "string_decoder": { "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "optional": true, @@ -2460,7 +2460,7 @@ "normalize-url": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-2.0.1.tgz", - "integrity": "sha512-D6MUW4K/VzoJ4rJ01JFKxDrtY1v9wrgzCX5f2qj/lzH1m/lW6MhUZFKerVsnyjOhOsYzI9Kqqak+10l4LvLpMw==", + "integrity": "sha1-g1qdoVUfom9w6SMpBpojqmV01+Y=", "dev": true, "optional": true, "requires": { @@ -2570,7 +2570,7 @@ "caw": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/caw/-/caw-2.0.1.tgz", - "integrity": "sha512-Cg8/ZSBEa8ZVY9HspcGUYaK63d/bN7rqS3CYCzEGUxuYv6UlmcjzDUz2fCFFHyTvUW5Pk0I+3hkA3iXlIj6guA==", + "integrity": "sha1-bDygcfwZRyCIPC3F2psHS/x+npU=", "dev": true, "optional": true, "requires": { @@ -3095,7 +3095,7 @@ "config-chain": { "version": "1.1.12", "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.12.tgz", - "integrity": "sha512-a1eOIcu8+7lUInge4Rpf/n4Krkf3Dd9lqhljRzII1/Zno/kRtUWnznPO3jOKBmTEktkt3fkxisUcivoj0ebzoA==", + "integrity": "sha1-D96NCRIA616AjK8l/mGMAvSOTvo=", "dev": true, "optional": true, "requires": { @@ -3151,7 +3151,7 @@ "content-disposition": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", - "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "integrity": "sha1-4TDK9+cnkIfFYWwgB9BIVpiYT70=", "dev": true, "optional": true, "requires": { @@ -3610,7 +3610,7 @@ "make-dir": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", - "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "integrity": "sha1-ecEDO4BRW9bSTsmTPoYMp17ifww=", "dev": true, "optional": true, "requires": { @@ -3641,7 +3641,7 @@ "decompress-tar": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/decompress-tar/-/decompress-tar-4.1.1.tgz", - "integrity": "sha512-JdJMaCrGpB5fESVyxwpCx4Jdj2AagLmv3y58Qy4GE6HMVjWz1FeVQk1Ct4Kye7PftcdOo/7U7UKzYBJgqnGeUQ==", + "integrity": "sha1-cYy9P8sWIJcW5womuE57pFkuWvE=", "dev": true, "optional": true, "requires": { @@ -3662,7 +3662,7 @@ "decompress-tarbz2": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/decompress-tarbz2/-/decompress-tarbz2-4.1.1.tgz", - "integrity": "sha512-s88xLzf1r81ICXLAVQVzaN6ZmX4A6U4z2nMbOwobxkLoIIfjVMBg7TeguTUXkKeXni795B6y5rnvDw7rxhAq9A==", + "integrity": "sha1-MIKluIDqQEOBY0nzeLVsUWvho5s=", "dev": true, "optional": true, "requires": { @@ -3676,7 +3676,7 @@ "file-type": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/file-type/-/file-type-6.2.0.tgz", - "integrity": "sha512-YPcTBDV+2Tm0VqjybVd32MHdlEGAtuxS3VAYsumFokDSMG+ROT5wawGlnHDoz7bfMcMDt9hxuXvXwoKUx2fkOg==", + "integrity": "sha1-5QzXXTVv/tTjBtxPW89Sp5kDqRk=", "dev": true, "optional": true } @@ -3685,7 +3685,7 @@ "decompress-targz": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/decompress-targz/-/decompress-targz-4.1.1.tgz", - "integrity": "sha512-4z81Znfr6chWnRDNfFNqLwPvm4db3WuZkqV+UgXQzSngG3CEKdBkw5jrv3axjjL96glyiiKjsxJG3X6WBZwX3w==", + "integrity": "sha1-wJvDXE0R894J8tLaU+neI+fOHu4=", "dev": true, "optional": true, "requires": { @@ -3875,7 +3875,7 @@ "dir-glob": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "integrity": "sha1-Vtv3PZkqSpO6FYT0U0Bj/S5BcX8=", "dev": true, "requires": { "path-type": "^4.0.0" @@ -3884,7 +3884,7 @@ "path-type": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "integrity": "sha1-hO0BwKe6OAr+CdkKjBgNzZ0DBDs=", "dev": true } } @@ -3982,7 +3982,7 @@ "download": { "version": "6.2.5", "resolved": "https://registry.npmjs.org/download/-/download-6.2.5.tgz", - "integrity": "sha512-DpO9K1sXAST8Cpzb7kmEhogJxymyVUd5qz/vCOSyvwtp2Klj2XcDt5YUuasgxka44SxF0q5RriKIwJmQHG2AuA==", + "integrity": "sha1-rNalQuTNC7Qspwz8mMnkOwcDlxQ=", "dev": true, "optional": true, "requires": { @@ -4016,7 +4016,7 @@ "make-dir": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", - "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "integrity": "sha1-ecEDO4BRW9bSTsmTPoYMp17ifww=", "dev": true, "optional": true, "requires": { @@ -4631,7 +4631,7 @@ "exec-buffer": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/exec-buffer/-/exec-buffer-3.2.0.tgz", - "integrity": "sha512-wsiD+2Tp6BWHoVv3B+5Dcx6E7u5zky+hUwOHjuH2hKSLR3dvRmX8fk8UD8uqQixHs4Wk6eDmiegVrMPjKj7wpA==", + "integrity": "sha1-sWhtvZBMfPmC5lLB9aebHlVzCCs=", "dev": true, "optional": true, "requires": { @@ -4705,7 +4705,7 @@ "executable": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/executable/-/executable-4.1.1.tgz", - "integrity": "sha512-8iA79xD3uAch729dUG8xaaBBFGaEa0wdD2VkYLFHwlqosEj/jT66AzcreRDSgV7ehnNLBW2WR5jIXwGKjVdTLg==", + "integrity": "sha1-QVMr/zYdPlevTXY7cFgtsY9dEzw=", "dev": true, "optional": true, "requires": { @@ -4831,7 +4831,7 @@ "ext-list": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/ext-list/-/ext-list-2.2.2.tgz", - "integrity": "sha512-u+SQgsubraE6zItfVA0tBuCBhfU9ogSRnsvygI7wht9TS510oLkBRXBsqopeUG/GBOIQyKZO9wjTqIu/sf5zFA==", + "integrity": "sha1-C5jmTtgvWs8PKTG6v2khLvUt3Tc=", "dev": true, "optional": true, "requires": { @@ -4841,7 +4841,7 @@ "ext-name": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/ext-name/-/ext-name-5.0.0.tgz", - "integrity": "sha512-yblEwXAbGv1VQDmow7s38W77hzAgJAO50ztBLMcUyUBfxv1HC+LGwtiEN+Co6LtlqT/5uwVOxsD4TNIilWhwdQ==", + "integrity": "sha1-cHgZgdGD7hXROZPIgiBFxQbI8KY=", "dev": true, "optional": true, "requires": { @@ -4990,7 +4990,7 @@ "braces": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "integrity": "sha1-NFThpGLujVmeI23zNs2epPiv4Qc=", "dev": true, "requires": { "fill-range": "^7.0.1" @@ -4999,7 +4999,7 @@ "fill-range": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "integrity": "sha1-GRmmp8df44ssfHflGYU12prN2kA=", "dev": true, "requires": { "to-regex-range": "^5.0.1" @@ -5026,13 +5026,13 @@ "is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "integrity": "sha1-dTU0W4lnNNX4DE0GxQlVUnoU8Ss=", "dev": true }, "micromatch": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", - "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", + "integrity": "sha1-T8sJmb+fvC/L3SEvbWKbmlbDklk=", "dev": true, "requires": { "braces": "^3.0.1", @@ -5048,7 +5048,7 @@ "to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "integrity": "sha1-FkjESq58jZiKMmAY7XL1tN0DkuQ=", "dev": true, "requires": { "is-number": "^7.0.0" @@ -5126,7 +5126,7 @@ "filenamify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/filenamify/-/filenamify-2.1.0.tgz", - "integrity": "sha512-ICw7NTT6RsDp2rnYKVd8Fu4cr6ITzGy3+u4vUujPkabyaz+03F24NWEX7fs5fp+kBonlaqPH8fAO2NM+SXt/JA==", + "integrity": "sha1-iPr0lfsbR6v9YSMAACoWIoxnfuk=", "dev": true, "optional": true, "requires": { @@ -5476,7 +5476,7 @@ "fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "integrity": "sha1-a+Dem+mYzhavivwkSXue6bfM2a0=", "dev": true, "optional": true }, @@ -6074,7 +6074,7 @@ "get-proxy": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/get-proxy/-/get-proxy-2.1.0.tgz", - "integrity": "sha512-zmZIaQTWnNQb4R4fJUEp/FC51eZsc6EkErspy3xtIYStaq8EB/hDIWipxsal+E8rz0qD7f2sL/NA9Xee4RInJw==", + "integrity": "sha1-NJ8rTZHUTE1NTpy6KtkBQ/rF75M=", "dev": true, "optional": true, "requires": { @@ -6222,7 +6222,7 @@ "pump": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "integrity": "sha1-tKIRaBW94vTh6mAjVOjHVWUQemQ=", "dev": true, "optional": true, "requires": { @@ -6475,7 +6475,7 @@ "got": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/got/-/got-7.1.0.tgz", - "integrity": "sha512-Y5WMo7xKKq1muPsxD+KmrR8DH5auG7fBdDVueZwETwV6VytKyU9OX/ddpq2/1hp1vIPvVb4T81dKQz3BivkNLw==", + "integrity": "sha1-BUUP2ECU5rvqVvRRpDqcKJFmOFo=", "dev": true, "optional": true, "requires": { @@ -7321,7 +7321,7 @@ "has-symbol-support-x": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/has-symbol-support-x/-/has-symbol-support-x-1.4.2.tgz", - "integrity": "sha512-3ToOva++HaW+eCpgqZrCfN51IPB+7bJNVT6CUATzueB5Heb8o6Nam0V3HG5dlDvZU1Gn5QLcbahiKw/XVk5JJw==", + "integrity": "sha1-FAn5i8ACR9pF2mfO4KNvKC/yZFU=", "dev": true, "optional": true }, @@ -7334,7 +7334,7 @@ "has-to-string-tag-x": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/has-to-string-tag-x/-/has-to-string-tag-x-1.4.1.tgz", - "integrity": "sha512-vdbKfmw+3LoOYVr+mtxHaX5a96+0f3DljYd8JOqvOLsf5mw2Otda2qCDT9qRqLAhrjyQ0h7ual5nOiASpsGNFw==", + "integrity": "sha1-oEWrOD17SyASoAFIqwql8pAETU0=", "dev": true, "optional": true, "requires": { @@ -7476,7 +7476,7 @@ "http-cache-semantics": { "version": "3.8.1", "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-3.8.1.tgz", - "integrity": "sha512-5ai2iksyV8ZXmnZhHH4rWPoxxistEexSi5936zIQ1bnNTW5VnA85B6P/VpXiRM017IgRvb2kKo1a//y+0wSp3w==", + "integrity": "sha1-ObDhat2bYFvwqe89nar0hDtMrNI=", "dev": true, "optional": true }, @@ -7608,7 +7608,7 @@ "imagemin-optipng": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/imagemin-optipng/-/imagemin-optipng-7.1.0.tgz", - "integrity": "sha512-JNORTZ6j6untH7e5gF4aWdhDCxe3ODsSLKs/f7Grewy3ebZpl1ZsU+VUTPY4rzeHgaFA8GSWOoA8V2M3OixWZQ==", + "integrity": "sha1-IiXILDXlwpt/qY1Pns7hFhpo6Ig=", "dev": true, "optional": true, "requires": { @@ -7741,7 +7741,7 @@ "import-lazy": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-3.1.0.tgz", - "integrity": "sha512-8/gvXvX2JMn0F+CDlSC4l6kOmVaLOO3XLkksI7CI3Ud95KDYJuYur2b9P/PUt/i/pDAMd/DulQsNbbbmRRsDIQ==", + "integrity": "sha1-iRJ5ICyKIoD9vWZ029jaGh38Z8w=", "dev": true, "optional": true }, @@ -7915,7 +7915,7 @@ "irregular-plurals": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-2.0.0.tgz", - "integrity": "sha512-Y75zBYLkh0lJ9qxeHlMjQ7bSbyiSqNW/UOPWDmzC7cXskL1hekSITh1Oc6JV0XCWWZ9DE8VYSB71xocLk3gmGw==", + "integrity": "sha1-OdQPBbAPZW0Lf6RxIw3TtxSvKHI=", "dev": true }, "is": { @@ -8098,7 +8098,7 @@ "is-gif": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-gif/-/is-gif-3.0.0.tgz", - "integrity": "sha512-IqJ/jlbw5WJSNfwQ/lHEDXF8rxhRgF6ythk2oiEvhpG29F704eX9NO6TvPfMiq9DrbwgcEDnETYNcZDPewQoVw==", + "integrity": "sha1-xL5gsmowHWlbuDOyDZtdZsbPg7E=", "dev": true, "optional": true, "requires": { @@ -8108,7 +8108,7 @@ "file-type": { "version": "10.11.0", "resolved": "https://registry.npmjs.org/file-type/-/file-type-10.11.0.tgz", - "integrity": "sha512-uzk64HRpUZyTGZtVuvrjP0FYxzQrBf4rojot6J65YMEbwBLB0CWm0CLojVpwpmFmxcE/lkvYICgfcGozbBq6rw==", + "integrity": "sha1-KWHQnkZ1ufuaPua2npzSP0P9GJA=", "dev": true, "optional": true } @@ -8195,7 +8195,7 @@ "is-png": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-png/-/is-png-2.0.0.tgz", - "integrity": "sha512-4KPGizaVGj2LK7xwJIz8o5B2ubu1D/vcQsgOGFEDlpcvgZHto4gBnyd0ig7Ws+67ixmwKoNmu0hYnpo6AaKb5g==", + "integrity": "sha1-7oy8npsFBCXO3utKb7dKZJsKSo0=", "dev": true, "optional": true }, @@ -8250,7 +8250,7 @@ "is-retry-allowed": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.2.0.tgz", - "integrity": "sha512-RUbUeKwvm3XG2VYamhJL1xFktgjvPzL0Hq8C+6yrWIswDy3BIXGqCxhxkc30N9jqK311gVU137K8Ei55/zVJRg==", + "integrity": "sha1-13hIi9CkZmo76KFIK58rqv7eqLQ=", "dev": true, "optional": true }, @@ -8352,7 +8352,7 @@ "isurl": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isurl/-/isurl-1.0.0.tgz", - "integrity": "sha512-1P/yWsxPlDtn7QeRD+ULKQPaIaN6yF368GZ2vDfv0AL0NwpStafjWCDDdn0k8wgFMWpVAqG7oJhxHnlud42i9w==", + "integrity": "sha1-sn9PSfPNqj6kSgpbfzRi5u3DnWc=", "dev": true, "optional": true, "requires": { @@ -8590,7 +8590,7 @@ "junk": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/junk/-/junk-3.1.0.tgz", - "integrity": "sha512-pBxcB3LFc8QVgdggvZWyeys+hnrNWg4OcZIU/1X59k5jQdLBlCsYGRQaz234SqoRLTCgMH00fY0xRJH+F9METQ==", + "integrity": "sha1-MUmQmNkCt+mMXZucgPQ0V6iKv6E=", "dev": true }, "just-debounce": { @@ -8798,7 +8798,7 @@ "keyv": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.0.0.tgz", - "integrity": "sha512-eguHnq22OE3uVoSYG0LVWNP+4ppamWr9+zWBe1bsNcovIMy6huUJFPgy4mGwCd/rnl3vOLGW1MTlu4c57CT1xA==", + "integrity": "sha1-RJI7o55osSp87H32wyaMAx8u83M=", "dev": true, "optional": true, "requires": { @@ -9249,7 +9249,7 @@ "lowercase-keys": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", - "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", + "integrity": "sha1-b54wtHCE2XGnyCD/FabFFnt0wm8=", "dev": true, "optional": true }, @@ -9297,7 +9297,7 @@ "semver": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "integrity": "sha1-7gpkyK9ejO6mdoexM3YeG+y9HT0=", "dev": true } } @@ -9489,7 +9489,7 @@ "mimic-response": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", - "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", + "integrity": "sha1-SSNTiHju9CBjy4o+OweYeBSHqxs=", "dev": true, "optional": true }, @@ -12836,7 +12836,7 @@ "npm-conf": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/npm-conf/-/npm-conf-1.1.3.tgz", - "integrity": "sha512-Yic4bZHJOt9RCFbRP3GgpqhScOY4HH3V2P8yBj6CeYq118Qr+BLXqT2JvpJ00mryLESpgOxf5XlFv4ZjXxLScw==", + "integrity": "sha1-JWzEe9DiGMJZxOlVC/QTvCGSr/k=", "dev": true, "optional": true, "requires": { @@ -13123,7 +13123,7 @@ "optipng-bin": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/optipng-bin/-/optipng-bin-6.0.0.tgz", - "integrity": "sha512-95bB4y8IaTsa/8x6QH4bLUuyvyOoGBCLDA7wOgDL8UFqJpSUh1Hob8JRJhit+wC1ZLN3tQ7mFt7KuBj0x8F2Wg==", + "integrity": "sha1-N2Eg+nnV5x7uL1JBdu/dOl6r0xY=", "dev": true, "optional": true, "requires": { @@ -13184,7 +13184,7 @@ "os-filter-obj": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/os-filter-obj/-/os-filter-obj-2.0.0.tgz", - "integrity": "sha512-uksVLsqG3pVdzzPvmAHpBK0wKxYItuzZr7SziusRPoz67tGV8rL1szZ6IdeUrbqLjGDwApBtN29eEE3IqGHOjg==", + "integrity": "sha1-HAti1fOiRCdJotE55t3e5ugdjRY=", "dev": true, "optional": true, "requires": { @@ -13209,7 +13209,7 @@ "p-cancelable": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-0.3.0.tgz", - "integrity": "sha512-RVbZPLso8+jFeq1MfNvgXtCRED2raz/dKpacfTNxsx6pLEpEomM7gah6VeHSYV3+vo0OAi4MkArtQcWWXuQoyw==", + "integrity": "sha1-ueEjgAvOu3rBOkeb4ZW1B7mNMPo=", "dev": true, "optional": true }, @@ -13506,7 +13506,7 @@ "plur": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/plur/-/plur-3.1.1.tgz", - "integrity": "sha512-t1Ax8KUvV3FFII8ltczPn2tJdjqbd1sIzu6t4JL7nQ3EyeL/lTrj5PWKb06ic5/6XYDr65rQ4uzQEGN70/6X5w==", + "integrity": "sha1-YCZ5Z4ZqjYEVBP5Y8vqrojdUals=", "dev": true, "requires": { "irregular-plurals": "^2.0.0" @@ -14031,7 +14031,7 @@ "query-string": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/query-string/-/query-string-5.1.1.tgz", - "integrity": "sha512-gjWOsm2SoGlgLEdAGt7a6slVOk9mGiXmPFMqrEhLQ68rhQuBnpfs3+EmlvqKyxnCo9/PPlF+9MtY02S1aFg+Jw==", + "integrity": "sha1-p4wBK3HBfgXy4/ojGd0zBoLvs8s=", "dev": true, "optional": true, "requires": { @@ -14488,7 +14488,7 @@ "reusify": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "integrity": "sha1-kNo4Kx4SbvwCFG6QhFqI2xKSXXY=", "dev": true }, "rfdc": { @@ -14706,7 +14706,7 @@ "semver-regex": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/semver-regex/-/semver-regex-2.0.0.tgz", - "integrity": "sha512-mUdIBBvdn0PLOeP3TEkMH7HHeUP3GjsXCwKarjv/kGmUFOYg1VqEemKhoQpWMu6X2I8kHeuVdGibLGkVK+/5Qw==", + "integrity": "sha1-qTwsWERTmncCMzeRB7OMe0rJ0zg=", "dev": true, "optional": true }, @@ -15411,7 +15411,7 @@ "strip-dirs": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/strip-dirs/-/strip-dirs-2.1.0.tgz", - "integrity": "sha512-JOCxOeKLm2CAS73y/U4ZeZPTkE+gNVCzKt7Eox84Iej1LT/2pTWYpZKJuxwQpvX1LiZb1xokNR7RLfuBAa7T3g==", + "integrity": "sha1-SYdzYmT8NEzyD2w0rKnRPR1O1sU=", "dev": true, "optional": true, "requires": { @@ -15451,7 +15451,7 @@ "strip-outer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/strip-outer/-/strip-outer-1.0.1.tgz", - "integrity": "sha512-k55yxKHwaXnpYGsOzg4Vl8+tDrWylxDEpknGjhTiZB8dFRU5rTo9CAzeycivxV3s+zlTKwrs6WxMxR95n26kwg==", + "integrity": "sha1-sv0qv2YEudHmATBXGV34Nrip1jE=", "dev": true, "optional": true, "requires": { @@ -15577,7 +15577,7 @@ "tar-stream": { "version": "1.6.2", "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-1.6.2.tgz", - "integrity": "sha512-rzS0heiNf8Xn7/mpdSVVSMAWAoy9bfb1WOTYC78Z0UQKeKa/CWS8FOq0lKGNa8DWKAn9gxjCvMLYc5PGXYlK2A==", + "integrity": "sha1-jqVdqzeXIlPZqa+Q/c1VmuQ1xVU=", "dev": true, "optional": true, "requires": { @@ -15706,7 +15706,7 @@ "through2-concurrent": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/through2-concurrent/-/through2-concurrent-2.0.0.tgz", - "integrity": "sha512-R5/jLkfMvdmDD+seLwN7vB+mhbqzWop5fAjx5IX8/yQq7VhBhzDmhXgaHAOnhnWkCpRMM7gToYHycB0CS/pd+A==", + "integrity": "sha1-yd0sFGUE7Jli28hqUWi2PWYmafo=", "dev": true, "requires": { "through2": "^2.0.0" @@ -15789,7 +15789,7 @@ "to-buffer": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.1.1.tgz", - "integrity": "sha512-lx9B5iv7msuFYE3dytT+KE5tap+rNYw+K4jVkb9R/asAb+pbBSM17jtunHplhBe6RRJdZx3Pn2Jph24O32mOVg==", + "integrity": "sha1-STvUj2LXxD/N7TE6A9ytsuEhOoA=", "dev": true, "optional": true }, diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umblogin.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umblogin.directive.js index ea8602214d..392199738b 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umblogin.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umblogin.directive.js @@ -57,6 +57,7 @@ vm.denyLocalLogin = externalLoginInfoService.hasDenyLocalLogin(); vm.externalLoginInfo = externalLoginInfo; vm.resetPasswordCodeInfo = resetPasswordCodeInfo; + vm.logoImage = Umbraco.Sys.ServerVariables.umbracoSettings.loginLogoImage; vm.backgroundImage = Umbraco.Sys.ServerVariables.umbracoSettings.loginBackgroundImage; vm.usernameIsEmail = Umbraco.Sys.ServerVariables.umbracoSettings.usernameIsEmail; diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js index 10fc44c2c6..070ffd4ddd 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js @@ -126,7 +126,7 @@ // Load in ace library assetsService.load(['lib/ace-builds/src-min-noconflict/ace.js', 'lib/ace-builds/src-min-noconflict/ext-language_tools.js'], scope).then(function () { - if (angular.isUndefined(window.ace)) { + if (Utilities.isUndefined(window.ace)) { throw new Error('ui-ace need ace to work... (o rly?)'); } else { // init editor diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorpicker.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorpicker.directive.js index e45fb174b8..b8731c9c51 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorpicker.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorpicker.directive.js @@ -5,7 +5,7 @@ @scope @description -Added in Umbraco v. 8.8: Use this directive to render a color picker. +Added in Umbraco v. 8.10: Use this directive to render a color picker.

Markup example

diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorswatches.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorswatches.directive.js
index 9d7927f59a..d6eda76940 100644
--- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorswatches.directive.js
+++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbcolorswatches.directive.js
@@ -30,15 +30,15 @@ Use this directive to generate color swatches to pick from.
         function link(scope, el, attr, ctrl) {
 
             // Set default to true if not defined
-            if (angular.isUndefined(scope.useColorClass)) {
+            if (Utilities.isUndefined(scope.useColorClass)) {
                 scope.useColorClass = false;
             }
 
             // Set default to "btn" if not defined
-            if (angular.isUndefined(scope.colorClassNamePrefix)) {
+            if (Utilities.isUndefined(scope.colorClassNamePrefix)) {
                 scope.colorClassNamePrefix = "btn";
             }
-            
+
             scope.setColor = function (color, $index, $event) {
                 if (scope.onSelect) {
                     // did the value change?
diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/validation/showvalidationonsubmit.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/validation/showvalidationonsubmit.directive.js
index 78dd00e64b..ad646748b7 100644
--- a/src/Umbraco.Web.UI.Client/src/common/directives/validation/showvalidationonsubmit.directive.js
+++ b/src/Umbraco.Web.UI.Client/src/common/directives/validation/showvalidationonsubmit.directive.js
@@ -11,6 +11,7 @@
             link: function (scope, element, attr, ctrl) {
 
                 var formMgr = ctrl.length > 1 ? ctrl[1] : null;
+                const hiddenClass = 'ng-hide';
 
                 //We can either get the form submitted status by the parent directive valFormManager
                 //or we can check upwards in the DOM for the css class... lets try both :)
@@ -18,17 +19,17 @@
                 //reset the status.
                 var submitted = element.closest(".show-validation").length > 0 || (formMgr && formMgr.showValidation);
                 if (!submitted) {
-                    element.hide();
+                    element[0].classList.add(hiddenClass);
                 }
 
                 var unsubscribe = [];
 
                 unsubscribe.push(scope.$on("formSubmitting", function (ev, args) {
-                    element.show();
+                    element[0].classList.remove(hiddenClass);
                 }));
 
                 unsubscribe.push(scope.$on("formSubmitted", function (ev, args) {
-                    element.hide();
+                    element[0].classList.add(hiddenClass);
                 }));
 
                 //no isolate scope to listen to element destroy
diff --git a/src/Umbraco.Web.UI.Client/src/common/filters/umbCmsJoinArray.filter.js b/src/Umbraco.Web.UI.Client/src/common/filters/umbCmsJoinArray.filter.js
index a519f81054..870e497541 100644
--- a/src/Umbraco.Web.UI.Client/src/common/filters/umbCmsJoinArray.filter.js
+++ b/src/Umbraco.Web.UI.Client/src/common/filters/umbCmsJoinArray.filter.js
@@ -13,7 +13,7 @@
  */
 angular.module("umbraco.filters").filter('umbCmsJoinArray', function () {
     return function join(array, separator, prop) {
-        return (!angular.isUndefined(prop) ? array.map(function (item) {
+        return (!Utilities.isUndefined(prop) ? array.map(function (item) {
             return item[prop];
         }) : array).join(separator || '');
     };
diff --git a/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js b/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js
index 93f0bddc96..bd597b21d0 100644
--- a/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js
+++ b/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js
@@ -17,7 +17,7 @@
                 return collection;
             }
 
-            if (angular.isUndefined(property)) {
+            if (Utilities.isUndefined(property)) {
                 return collection;
             }
 
diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js
index 7dc34c3b5a..78fefc8db5 100644
--- a/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js
+++ b/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js
@@ -12,7 +12,24 @@
 function authResource($q, $http, umbRequestHelper, angularHelper) {
 
   return {
-
+     /**
+     * @ngdoc method
+     * @name umbraco.resources.authResource#get2FAProviders
+     * @methodOf umbraco.resources.authResource
+     *
+     * @description
+     * Logs the Umbraco backoffice user in if the credentials are good
+     *
+     * ##usage
+     * 
+     * authResource.get2FAProviders()
+     *    .then(function(data) {
+     *        //Do stuff ...
+     *    });
+     * 
+ * @returns {Promise} resourcePromise object + * + */ get2FAProviders: function () { return umbRequestHelper.resourcePromise( @@ -23,6 +40,25 @@ function authResource($q, $http, umbRequestHelper, angularHelper) { 'Could not retrive two factor provider info'); }, + /** + * @ngdoc method + * @name umbraco.resources.authResource#get2FAProviders + * @methodOf umbraco.resources.authResource + * + * @description + * Generate the two-factor authentication code for the provider and send it to the user + * + * ##usage + *
+    * authResource.send2FACode(provider)
+    *    .then(function(data) {
+    *        //Do stuff ...
+    *    });
+    * 
+ * @param {string} provider Name of the provider + * @returns {Promise} resourcePromise object + * + */ send2FACode: function (provider) { return umbRequestHelper.resourcePromise( @@ -34,6 +70,26 @@ function authResource($q, $http, umbRequestHelper, angularHelper) { 'Could not send code'); }, + /** + * @ngdoc method + * @name umbraco.resources.authResource#get2FAProviders + * @methodOf umbraco.resources.authResource + * + * @description + * Verify the two-factor authentication code entered by the user against the provider + * + * ##usage + *
+    * authResource.verify2FACode(provider, code)
+    *    .then(function(data) {
+    *        //Do stuff ...
+    *    });
+    * 
+ * @param {string} provider Name of the provider + * @param {string} code The two-factor authentication code + * @returns {Promise} resourcePromise object + * + */ verify2FACode: function (provider, code) { return umbRequestHelper.resourcePromise( diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/contenttype.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/contenttype.resource.js index 4a8c65c322..c5a353d746 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/contenttype.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/contenttype.resource.js @@ -7,6 +7,25 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca return { + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getCount + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Gets the count of content types + * + * ##usage + *
+        * contentTypeResource.getCount()
+        *    .then(function(data) {
+        *        console.log(data);
+        *    });
+        * 
+ * + * @returns {Promise} resourcePromise object. + * + */ getCount: function () { return umbRequestHelper.resourcePromise( $http.get( @@ -16,6 +35,29 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to retrieve count'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getAvailableCompositeContentTypes + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Gets the compositions for a content type + * + * ##usage + *
+        * contentTypeResource.getAvailableCompositeContentTypes()
+        *    .then(function(data) {
+        *        console.log(data);
+        *    });
+        * 
+ * + * @param {Int} contentTypeId id of the content type to retrieve the list of the compositions + * @param {Array} filterContentTypes array of content types to filter out + * @param {Array} filterPropertyTypes array of property aliases to filter out. If specified any content types with the property aliases will be filtered out + * @param {Boolean} isElement whether the composite content types should be applicable for an element type + * @returns {Promise} resourcePromise object. + * + */ getAvailableCompositeContentTypes: function (contentTypeId, filterContentTypes, filterPropertyTypes, isElement) { if (!filterContentTypes) { filterContentTypes = []; @@ -86,6 +128,7 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca * $scope.type = type; * }); *
+ * * @param {Int} contentTypeId id of the content item to retrive allowed child types for * @returns {Promise} resourcePromise object. * @@ -110,6 +153,14 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca * @description * Returns a list of defined property type aliases * + * ##usage + *
+         * contentTypeResource.getAllPropertyTypeAliases()
+         *    .then(function(array) {
+         *       Do stuff...
+         *    });
+         * 
+ * * @returns {Promise} resourcePromise object. * */ @@ -123,6 +174,25 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to retrieve property type aliases'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getAllStandardFields + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Returns a list of standard property type aliases + * + * ##usage + *
+        * contentTypeResource.getAllStandardFields()
+        *    .then(function(array) {
+        *       Do stuff...
+        *    });
+        * 
+ * + * @returns {Promise} resourcePromise object. + * + */ getAllStandardFields: function () { return umbRequestHelper.resourcePromise( @@ -133,6 +203,26 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to retrieve standard fields'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getPropertyTypeScaffold + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Returns the property display for a given datatype id + * + * ##usage + *
+        * contentTypeResource.getPropertyTypeScaffold(1234)
+        *    .then(function(array) {
+        *       Do stuff...
+        *    });
+        * 
+ * + * @param {Int} id the id of the datatype + * @returns {Promise} resourcePromise object. + * + */ getPropertyTypeScaffold: function (id) { return umbRequestHelper.resourcePromise( $http.get( @@ -143,6 +233,26 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to retrieve property type scaffold'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getById + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Get the content type with a given id + * + * ##usage + *
+        * contentTypeResource.getById("64058D0F-4911-4AB7-B3BA-000D89F00A26")
+        *    .then(function(array) {
+        *       Do stuff...
+        *    });
+        * 
+ * + * @param {String} id the guid id of the content type + * @returns {Promise} resourcePromise object. + * + */ getById: function (id) { return umbRequestHelper.resourcePromise( @@ -154,6 +264,26 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to retrieve content type'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#deleteById + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Delete the content type of a given id + * + * ##usage + *
+        * contentTypeResource.deleteById(1234)
+        *    .then(function(array) {
+        *       Do stuff...
+        *    });
+        * 
+ * + * @param {Int} id the id of the content type + * @returns {Promise} resourcePromise object. + * + */ deleteById: function (id) { return umbRequestHelper.resourcePromise( @@ -165,6 +295,26 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to delete content type'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#deleteContainerById + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Delete the content type container of a given id + * + * ##usage + *
+        * contentTypeResource.deleteContainerById(1234)
+        *    .then(function(array) {
+        *       Do stuff...
+        *    });
+        * 
+ * + * @param {Int} id the id of the content type container + * @returns {Promise} resourcePromise object. + * + */ deleteContainerById: function (id) { return umbRequestHelper.resourcePromise( @@ -177,16 +327,16 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca }, /** - * @ngdoc method - * @name umbraco.resources.contentTypeResource#getAll - * @methodOf umbraco.resources.contentTypeResource - * - * @description - * Returns a list of all content types - * - * @returns {Promise} resourcePromise object. - * - */ + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getAll + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Returns a list of all content types + * + * @returns {Promise} resourcePromise object. + * + */ getAll: function () { return umbRequestHelper.resourcePromise( @@ -197,6 +347,26 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to retrieve all content types'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getScaffold + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Returns an empty content type for use as a scaffold when creating a new content type + * + * ##usage + *
+        * contentTypeResource.getScaffold(1234)
+        *    .then(function(array) {
+        *       Do stuff...
+        *    });
+        * 
+ * + * @param {Int} id the parent id + * @returns {Promise} resourcePromise object. + * + */ getScaffold: function (parentId) { return umbRequestHelper.resourcePromise( @@ -240,14 +410,14 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca *
          * contentTypeResource.move({ parentId: 1244, id: 123 })
          *    .then(function() {
-         *        alert("node was moved");
+         *        alert("content type was moved");
          *    }, function(err){
-         *      alert("node didnt move:" + err.data.Message);
+         *      alert("content type didnt move:" + err.data.Message);
          *    });
          * 
* @param {Object} args arguments object - * @param {Int} args.idd the ID of the node to move - * @param {Int} args.parentId the ID of the parent node to move to + * @param {Int} args.id the ID of the content type to move + * @param {Int} args.parentId the ID of the parent content type to move to * @returns {Promise} resourcePromise object. * */ @@ -271,6 +441,29 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to move content'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#copy + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Copied a content type underneath a new parentId + * + * ##usage + *
+         * contentTypeResource.copy({ parentId: 1244, id: 123 })
+         *    .then(function() {
+         *        alert("content type was copied");
+         *    }, function(err){
+         *      alert("content type didnt copy:" + err.data.Message);
+         *    });
+         * 
+ * @param {Object} args arguments object + * @param {Int} args.id the ID of the content type to copy + * @param {Int} args.parentId the ID of the parent content type to copy to + * @returns {Promise} resourcePromise object. + * + */ copy: function (args) { if (!args) { throw "args cannot be null"; @@ -291,6 +484,27 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca 'Failed to copy content'); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#createContainer + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Create a new content type container of a given name underneath a given parent item + * + * ##usage + *
+        * contentTypeResource.createContainer(1244,"testcontainer")
+        *    .then(function() {
+        *       Do stuff..
+        *    });
+        * 
+ * + * @param {Int} parentId the ID of the parent content type underneath which to create the container + * @param {String} name the name of the container + * @returns {Promise} resourcePromise object. + * + */ createContainer: function (parentId, name) { return umbRequestHelper.resourcePromise( @@ -299,6 +513,32 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#createCollection + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Create a collection of a content types + * + * ##usage + *
+        * contentTypeResource.createCollection(1244,"testcollectionname",true,"collectionItemName",true,"icon-name","icon-name")
+        *    .then(function() {
+        *       Do stuff..
+        *    });
+        * 
+ * + * @param {Int} parentId the ID of the parent content type underneath which to create the collection + * @param {String} collectionName the name of the collection + * @param {Boolean} collectionCreateTemplate true/false to specify whether to create a default template for the collection + * @param {String} collectionItemName the name of the collection item + * @param {Boolean} collectionItemCreateTemplate true/false to specify whether to create a default template for the collection item + * @param {String} collectionIcon the icon for the collection + * @param {String} collectionItemIcon the icon for the collection item + * @returns {Promise} resourcePromise object. + * + */ createCollection: function (parentId, collectionName, collectionCreateTemplate, collectionItemName, collectionItemCreateTemplate, collectionIcon, collectionItemIcon) { return umbRequestHelper.resourcePromise( @@ -307,6 +547,27 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#renameContainer + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Rename a container of a given id + * + * ##usage + *
+        * contentTypeResource.renameContainer( 1244,"testcontainer")
+        *    .then(function() {
+        *       Do stuff..
+        *    });
+        * 
+ * + * @param {Int} id the ID of the container to rename + * @param {String} name the new name of the container + * @returns {Promise} resourcePromise object. + * + */ renameContainer: function (id, name) { return umbRequestHelper.resourcePromise( @@ -318,6 +579,27 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#export + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Export a content type of a given id. + * + * ##usage + *
+        * contentTypeResource.export(1234){
+        *    .then(function() {
+        *       Do stuff..
+        *    });
+        * 
+ * + * @param {Int} id the ID of the container to rename + * @param {String} name the new name of the container + * @returns {Promise} resourcePromise object. + * + */ export: function (id) { if (!id) { throw "id cannot be null"; @@ -336,6 +618,26 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca }); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#import + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Import a content type from a file + * + * ##usage + *
+        * contentTypeResource.import("path to file"){
+        *    .then(function() {
+        *       Do stuff..
+        *    });
+        * 
+ * + * @param {String} file path of the file to import + * @returns {Promise} resourcePromise object. + * + */ import: function (file) { if (!file) { throw "file cannot be null"; @@ -347,12 +649,52 @@ function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter, loca ); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#createDefaultTemplate + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Create a default template for a content type with a given id + * + * ##usage + *
+        * contentTypeResource.createDefaultTemplate(1234){
+        *    .then(function() {
+        *       Do stuff..
+        *    });
+        * 
+ * + * @param {Int} id the id of the content type for which to create the default template + * @returns {Promise} resourcePromise object. + * + */ createDefaultTemplate: function (id) { return umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("contentTypeApiBaseUrl", "PostCreateDefaultTemplate", { id: id })), 'Failed to create default template for content type with id ' + id); }, + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#hasContentNodes + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Returns whether a content type has content nodes + * + * ##usage + *
+        * contentTypeResource.hasContentNodes(1234){
+        *    .then(function() {
+        *       Do stuff..
+        *    });
+        * 
+ * + * @param {Int} id the id of the content type + * @returns {Promise} resourcePromise object. + * + */ hasContentNodes: function (id) { return umbRequestHelper.resourcePromise( $http.get( diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/elementtype.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/elementtype.resource.js index acc0a94485..b097a65447 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/elementtype.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/elementtype.resource.js @@ -7,6 +7,25 @@ function elementTypeResource($q, $http, umbRequestHelper) { return { + /** + * @ngdoc method + * @name umbraco.resources.elementTypeResource#getAll + * @methodOf umbraco.resources.elementTypeResource + * + * @description + * Gets a list of all element types + * + * ##usage + *
+        * elementTypeResource.getAll()
+        *    .then(function() {
+        *        alert('Found it!');
+        *    });
+        * 
+ * + * @returns {Promise} resourcePromise object. + * + **/ getAll: function () { return umbRequestHelper.resourcePromise( diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/modelsbuildermanagement.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/modelsbuildermanagement.resource.js index ee3cd80c71..8352ca07e6 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/modelsbuildermanagement.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/modelsbuildermanagement.resource.js @@ -1,18 +1,82 @@ + +/** +* @ngdoc service +* @name umbraco.resources.modelsBuilderManagementResource +* @description Resources to get information on modelsbuilder status and build models +**/ function modelsBuilderManagementResource($q, $http, umbRequestHelper) { return { + + /** + * @ngdoc method + * @name umbraco.resources.modelsBuilderManagementResource#getModelsOutOfDateStatus + * @methodOf umbraco.resources.modelsBuilderManagementResource + * + * @description + * Gets the status of modelsbuilder + * + * ##usage + *
+        * modelsBuilderManagementResource.getModelsOutOfDateStatus()
+        *  .then(function() {
+        *        Do stuff...*
+        * });
+        * 
+ * + * @returns {Promise} resourcePromise object. + * + */ getModelsOutOfDateStatus: function () { return umbRequestHelper.resourcePromise( $http.get(umbRequestHelper.getApiUrl("modelsBuilderBaseUrl", "GetModelsOutOfDateStatus")), "Failed to get models out-of-date status"); }, + /** + * @ngdoc method + * @name umbraco.resources.modelsBuilderManagementResource#buildModels + * @methodOf umbraco.resources.modelsBuilderManagementResource + * + * @description + * Builds the models + * + * ##usage + *
+        * modelsBuilderManagementResource.buildModels()
+        *  .then(function() {
+        *        Do stuff...*
+        * });
+        * 
+ * + * @returns {Promise} resourcePromise object. + * + */ buildModels: function () { return umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("modelsBuilderBaseUrl", "BuildModels")), "Failed to build models"); }, + /** + * @ngdoc method + * @name umbraco.resources.modelsBuilderManagementResource#getDashboard + * @methodOf umbraco.resources.modelsBuilderManagementResource + * + * @description + * Gets the modelsbuilder dashboard + * + * ##usage + *
+        * modelsBuilderManagementResource.getDashboard()
+        *  .then(function() {
+        *        Do stuff...*
+        * });
+        * 
+ * + * @returns {Promise} resourcePromise object. + * + */ getDashboard: function () { return umbRequestHelper.resourcePromise( $http.get(umbRequestHelper.getApiUrl("modelsBuilderBaseUrl", "GetDashboard")), diff --git a/src/Umbraco.Web.UI.Client/src/install.loader.js b/src/Umbraco.Web.UI.Client/src/install.loader.js index 997c8cbe84..8c17b8cd64 100644 --- a/src/Umbraco.Web.UI.Client/src/install.loader.js +++ b/src/Umbraco.Web.UI.Client/src/install.loader.js @@ -1,6 +1,6 @@ LazyLoad.js([ 'lib/jquery/jquery.min.js', - + 'lib/angular/angular.js', 'lib/angular-cookies/angular-cookies.js', 'lib/angular-touch/angular-touch.js', @@ -8,10 +8,14 @@ LazyLoad.js([ 'lib/angular-messages/angular-messages.js', 'lib/angular-aria/angular-aria.min.js', 'lib/underscore/underscore-min.js', - 'lib/angular-ui-sortable/sortable.js', + 'lib/angular-ui-sortable/sortable.js', + + 'js/utilities.js', + 'js/installer.app.js', 'js/umbraco.directives.js', 'js/umbraco.installer.js' + ], function () { jQuery(document).ready(function () { angular.bootstrap(document, ['umbraco']); diff --git a/src/Umbraco.Web.UI.Client/src/installer/steps/database.controller.js b/src/Umbraco.Web.UI.Client/src/installer/steps/database.controller.js index ae2fc63293..d236d45568 100644 --- a/src/Umbraco.Web.UI.Client/src/installer/steps/database.controller.js +++ b/src/Umbraco.Web.UI.Client/src/installer/steps/database.controller.js @@ -1,28 +1,28 @@ angular.module("umbraco.install").controller("Umbraco.Installer.DataBaseController", function($scope, $http, installerService){ - + $scope.checking = false; $scope.invalidDbDns = false; - + $scope.dbs = $scope.installer.current.model.databases; if (angular.isUndefined(installerService.status.current.model.dbType) || installerService.status.current.model.dbType === null) { installerService.status.current.model.dbType = $scope.dbs[0].id; } - + $scope.validateAndForward = function() { if (!$scope.checking && this.myForm.$valid) { $scope.checking = true; $scope.invalidDbDns = false; - + var model = installerService.status.current.model; $http.post( Umbraco.Sys.ServerVariables.installApiBaseUrl + "PostValidateDatabaseConnection", model).then(function(response) { - + if (response.data === true) { - installerService.forward(); + installerService.forward(); } else { $scope.invalidDbDns = true; diff --git a/src/Umbraco.Web.UI.Client/src/less/application/grid.less b/src/Umbraco.Web.UI.Client/src/less/application/grid.less index 9e91da4792..68160923c8 100644 --- a/src/Umbraco.Web.UI.Client/src/less/application/grid.less +++ b/src/Umbraco.Web.UI.Client/src/less/application/grid.less @@ -171,13 +171,13 @@ body.umb-drawer-is-visible #mainwrapper{ } @media (min-width: 1101px) { - #contentwrapper, #speechbubble {left: 360px;} - .emptySection #contentwrapper {left:0px;} + #contentwrapper, #speechbubble { left: 360px; } + .emptySection #contentwrapper { left: 0 !important; } } //empty section modification -.emptySection #speechbubble {left: 0;} -.emptySection #navigation {display: none} +.emptySection #speechbubble { left: 0; } +.emptySection #navigation { display: none } .login-only #speechbubble { z-index: 10000; diff --git a/src/Umbraco.Web.UI.Client/src/less/components/buttons/umb-button.less b/src/Umbraco.Web.UI.Client/src/less/components/buttons/umb-button.less index d523b24141..b6800aba65 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/buttons/umb-button.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/buttons/umb-button.less @@ -63,6 +63,11 @@ border-left-color: @white; } +.umb-button__progress.-black { + border-color: rgba(255, 255, 255, 0.4); + border-left-color: @black; +} + .umb-button__success, .umb-button__error { position: absolute; diff --git a/src/Umbraco.Web.UI.Client/src/less/components/html/umb-expansion-panel.less b/src/Umbraco.Web.UI.Client/src/less/components/html/umb-expansion-panel.less index 2a8137e5f9..ea08794c23 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/html/umb-expansion-panel.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/html/umb-expansion-panel.less @@ -10,11 +10,12 @@ font-weight: bold; display: flex; align-items: center; - cursor: pointer; justify-content: space-between; color: @black; + width: 100%; - &:hover .umb-expansion-panel__expand { + &:hover .umb-expansion-panel__expand, + &:focus .umb-expansion-panel__expand { color: @gray-6; } } diff --git a/src/Umbraco.Web.UI.Client/src/less/components/umb-checkbox-list.less b/src/Umbraco.Web.UI.Client/src/less/components/umb-checkbox-list.less index 11194eeb43..c9f47a66df 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/umb-checkbox-list.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/umb-checkbox-list.less @@ -37,6 +37,7 @@ align-items: center; flex: 0 0 30px; margin-right: 5px; + position: relative; } .umb-checkbox-list__item-icon { @@ -44,6 +45,17 @@ font-size: 16px; } +.umb-checkbox-list__item-icon-wrapper { + position: relative; + + .umb-button__progress { + width: 10px; + height: 10px; + margin-left: -10px; + margin-top: -8px; + } +} + .umb-checkbox-list__item-text { font-size: 14px; margin-bottom: 0; diff --git a/src/Umbraco.Web.UI.Client/src/less/components/umb-grid.less b/src/Umbraco.Web.UI.Client/src/less/components/umb-grid.less index 784598e84a..e1fc5573e5 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/umb-grid.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/umb-grid.less @@ -392,7 +392,7 @@ // EDITOR PLACEHOLDER // ------------------------- .umb-grid .umb-editor-placeholder { - min-height: 65px; + min-height: 110px; padding: 20px; padding-bottom: 30px; position: relative; @@ -400,7 +400,7 @@ border: 4px dashed @gray-8; text-align: center; text-align: -moz-center; - cursor: pointer; + width: 100%; } .umb-grid .umb-editor-placeholder i { @@ -413,6 +413,7 @@ .umb-grid .umb-editor-preview { position: relative; + width: 100%; .umb-editor-preview-overlay { cursor: pointer; diff --git a/src/Umbraco.Web.UI.Client/src/less/components/umb-nested-content.less b/src/Umbraco.Web.UI.Client/src/less/components/umb-nested-content.less index 05824ba425..834a1a69e9 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/umb-nested-content.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/umb-nested-content.less @@ -4,6 +4,7 @@ .umb-nested-content-property-container { position: relative; + &:not(:last-child){ margin-bottom: 12px; } @@ -54,19 +55,19 @@ visibility: visible !important; } -.umb-nested-content__item--single > .umb-nested-content__content { +.umb-nested-content__item--single { border: 0; -} -.umb-nested-content__item--single > .umb-nested-content__content > .umb-pane { - margin: 0; + > .umb-nested-content__content { + > .umb-pane { + margin: 0; + } + } } .umb-nested-content__header-bar { - cursor: pointer; background-color: @white; - -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; @@ -78,21 +79,19 @@ padding-right: 60px; } } - } .umb-nested-content__heading { + display: flex; + padding: 15px; line-height: 20px; - position: relative; - padding: 15px 5px; - color:@ui-option-type; + color: @ui-option-type; &:hover { - color:@ui-option-type-hover; + color: @ui-option-type-hover; } .umb-nested-content__item-icon { - position: absolute; margin-top: -3px; font-size: 22px; } @@ -106,10 +105,9 @@ padding-left: 5px; &.--has-icon { - padding-left: 30px; + padding-left: 10px; } } - } .umb-nested-content__icons { @@ -125,13 +123,16 @@ .umb-nested-content__item--active > .umb-nested-content__header-bar { .umb-nested-content__heading { background-color: @ui-active; + &:hover { - color:@ui-option-type; + color: @ui-option-type; } + .umb-nested-content__item-name { padding-right: 60px; } } + .umb-nested-content__icons { background-color: @ui-active; &:before { @@ -140,8 +141,6 @@ } } - - .umb-nested-content__header-bar:hover .umb-nested-content__icons, .umb-nested-content__header-bar:focus .umb-nested-content__icons, .umb-nested-content__header-bar:focus-within .umb-nested-content__icons, @@ -149,8 +148,6 @@ opacity: 1; } - - .umb-nested-content__icon { background: transparent; border: 0 none; @@ -180,9 +177,6 @@ } } - - - .umb-nested-content__footer-bar { margin-top: 20px; } @@ -212,7 +206,6 @@ cursor: not-allowed; } - .umb-nested-content__content { border-top: 1px solid transparent; border-bottom: 1px solid transparent; @@ -240,17 +233,17 @@ } .umb-nested-content__doctypepicker table td.icon-navigation, -.umb-nested-content__doctypepicker i.umb-nested-content__help-icon { +.umb-nested-content__doctypepicker .umb-nested-content__help-icon { vertical-align: middle; color: @gray-7; } .umb-nested-content__doctypepicker table td.icon-navigation:hover, -.umb-nested-content__doctypepicker i.umb-nested-content__help-icon:hover { +.umb-nested-content__doctypepicker .umb-nested-content__help-icon:hover { color: @gray-2; } -.umb-nested-content__doctypepicker i.umb-nested-content__help-icon { +.umb-nested-content__doctypepicker .umb-nested-content__help-action { margin-left: 10px; } diff --git a/src/Umbraco.Web.UI.Client/src/less/navs.less b/src/Umbraco.Web.UI.Client/src/less/navs.less index e45a4d46bb..6dab771c94 100644 --- a/src/Umbraco.Web.UI.Client/src/less/navs.less +++ b/src/Umbraco.Web.UI.Client/src/less/navs.less @@ -12,7 +12,10 @@ padding-right: 7px; } -.icon.handle{color: @gray-8;} +.umb-icon.handle, +.icon.handle { + color: @gray-8; +} // BASE CLASS diff --git a/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js b/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js index 44ff1d1cdf..aa17b4a7c2 100644 --- a/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js @@ -117,6 +117,13 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi } } + function fixExternalLinks(iframe) { + // Make sure external links don't open inside the iframe + Array.from(iframe.contentDocument.getElementsByTagName("a")) + .filter(a => a.hostname !== location.hostname && !a.target) + .forEach(a => a.target = "_top"); + } + var isInit = getParameterByName("init"); if (isInit === "true") { //do not continue, this is the first load of this new window, if this is passed in it means it's been @@ -443,6 +450,7 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi $scope.frameLoaded = true; configureSignalR(iframe); + fixExternalLinks(iframe); $scope.currentCultureIso = $location.search().culture || null; }; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/drawers/help/help.html b/src/Umbraco.Web.UI.Client/src/views/common/drawers/help/help.html index 04b5501846..4f6b283fd8 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/drawers/help/help.html +++ b/src/Umbraco.Web.UI.Client/src/views/common/drawers/help/help.html @@ -97,7 +97,7 @@ - + - +
- +
Visit umbraco.tv @@ -138,7 +138,7 @@ - +
diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js index ab8c133211..526d2d4dfa 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js @@ -7,7 +7,7 @@ var oldModel = null; vm.showConfirmSubmit = false; - vm.loading = false; + vm.loadingAlias = null; vm.isSelected = isSelected; vm.openContentType = openContentType; @@ -57,31 +57,13 @@ $location.path(url); } - function selectCompositeContentType(compositeContentType) { - - vm.loading = true; + function selectCompositeContentType(compositeContentType) { + vm.loadingAlias = compositeContentType.contentType.alias var contentType = compositeContentType.contentType; $scope.model.selectCompositeContentType(contentType).then(function (response) { - - Utilities.forEach(vm.availableGroups, function (group) { - - Utilities.forEach(group.compositeContentTypes, function (obj) { - if (obj.allowed === false) { - obj.selected = false; - } - }); - }); - - $timeout(function () { - vm.loading = false; - }, 500); - - }, function () { - $timeout(function () { - vm.loading = false; - }, 500); + vm.loadingAlias = null; }); // Check if the template is already selected. diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.html b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.html index 8060605b87..98db2b0336 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.html +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.html @@ -42,10 +42,6 @@ -
- -
-

@@ -68,18 +64,21 @@
  • + ng-class="{'-disabled': (compositeContentType.allowed === false && !compositeContentType.selected) || compositeContentType.inherited, '-selected': compositeContentType.selected}">
    + disabled="(compositeContentType.allowed === false && !compositeContentType.selected) || compositeContentType.inherited || vm.loadingAlias">
    -
  • diff --git a/src/Umbraco.Web.UI.Client/src/views/dictionary/dictionary.edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/dictionary/dictionary.edit.controller.js index 7619c7abfc..416d2c3a65 100644 --- a/src/Umbraco.Web.UI.Client/src/views/dictionary/dictionary.edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/dictionary/dictionary.edit.controller.js @@ -24,9 +24,11 @@ function DictionaryEditController($scope, $routeParams, $location, dictionaryRes vm.page.menu.currentNode = null; vm.description = ""; vm.showBackButton = true; + vm.maxlength = 1000; vm.save = saveDictionary; vm.back = back; + vm.change = change; function loadDictionary() { @@ -56,6 +58,7 @@ function DictionaryEditController($scope, $routeParams, $location, dictionaryRes // create data for umb-property displaying for (var i = 0; i < data.translations.length; i++) { data.translations[i].property = createTranslationProperty(data.translations[i]); + change(data.translations[i]); } contentEditingHelper.handleSuccessfulSave({ @@ -111,6 +114,13 @@ function DictionaryEditController($scope, $routeParams, $location, dictionaryRes $location.path(vm.page.menu.currentSection + "/dictionary/list"); } + function change(translation) { + if (translation.translation) { + var charsCount = translation.translation.length; + translation.nearMaxLimit = charsCount > Math.max(vm.maxlength * .8, vm.maxlength - 50); + } + } + $scope.$watch("vm.content.name", function (newVal, oldVal) { //when the value changes, we need to set the name dirty if (newVal && (newVal !== oldVal) && typeof(oldVal) !== "undefined") { diff --git a/src/Umbraco.Web.UI.Client/src/views/dictionary/edit.html b/src/Umbraco.Web.UI.Client/src/views/dictionary/edit.html index cad99edbdd..1577af43de 100644 --- a/src/Umbraco.Web.UI.Client/src/views/dictionary/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/dictionary/edit.html @@ -23,7 +23,18 @@

    - + +
    +

    + {{ translation.displayName }} + %0% characters left. +

    +
    diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.controller.js index 7d4df17277..6fe8c303a0 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.controller.js @@ -36,8 +36,7 @@ } function submit() { - console.log("model", $scope.model); - + if ($scope.model && $scope.model.submit && formHelper.submitForm({scope: $scope})) { $scope.model.submit($scope.model); } diff --git a/src/Umbraco.Web.UI.Client/src/views/media/edit.html b/src/Umbraco.Web.UI.Client/src/views/media/edit.html index d22c55ae65..d2782a2a21 100644 --- a/src/Umbraco.Web.UI.Client/src/views/media/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/media/edit.html @@ -59,7 +59,7 @@ -
    -
    Package Properties
    -   -
    +
    @@ -103,10 +103,10 @@
    -
    -
    Package Content
    -   -
    +
    @@ -231,15 +231,13 @@
    -
    -
    Package Files
    -   -
    +
    - + @@ -288,19 +286,22 @@
    -
    -
    Package Actions
    -   -
    +
    diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/created.html b/src/Umbraco.Web.UI.Client/src/views/packages/views/created.html index e3743674f9..88a2b21795 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/created.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/created.html @@ -5,7 +5,7 @@ @@ -20,7 +20,7 @@
    - +
    {{ createdPackage.name }}
    diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.html b/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.html index a499a12558..42b538f9ad 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.html @@ -294,7 +294,7 @@
    External sources
    - + {{ externalSource.name }} @@ -335,7 +335,7 @@
    @@ -345,7 +345,7 @@
    @@ -357,7 +357,7 @@
    - I accept terms of use + I accept terms of use
    - + +
    @@ -167,7 +171,11 @@
    - + +
    diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js index bd80cdc42c..0f012810ba 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js @@ -15,7 +15,7 @@ * @param {any} editorService * @param {any} userService */ -function contentPickerController($scope, $q, $routeParams, $location, entityResource, editorState, iconHelper, angularHelper, navigationService, localizationService, editorService, userService) { +function contentPickerController($scope, $q, $routeParams, $location, entityResource, editorState, iconHelper, angularHelper, navigationService, localizationService, editorService, userService, overlayService) { var vm = { labels: { @@ -116,6 +116,14 @@ function contentPickerController($scope, $q, $routeParams, $location, entityReso } }; + var removeAllEntriesAction = { + labelKey: 'clipboard_labelForRemoveAllEntries', + labelTokens: [], + icon: 'trash', + method: removeAllEntries, + isDisabled: true + }; + if ($scope.model.config) { //special case, if the `startNode` is falsy on the server config delete it entirely so the default value is merged in if (!$scope.model.config.startNode) { @@ -129,6 +137,14 @@ function contentPickerController($scope, $q, $routeParams, $location, entityReso if ($scope.model.validation && $scope.model.validation.mandatory && !$scope.model.config.minNumber) { $scope.model.config.minNumber = 1; } + + if ($scope.model.config.multiPicker === true && $scope.umbProperty) { + var propertyActions = [ + removeAllEntriesAction + ]; + + $scope.umbProperty.setPropertyActions(propertyActions); + } } //Umbraco persists boolean for prevalues as "0" or "1" so we need to convert that! @@ -275,6 +291,8 @@ function contentPickerController($scope, $q, $routeParams, $location, entityReso angularHelper.getCurrentForm($scope).$setDirty(); $scope.model.value = currIds.join(); } + + removeAllEntriesAction.isDisabled = currIds.length === 0; }; $scope.showNode = function (index) { @@ -301,10 +319,13 @@ function contentPickerController($scope, $q, $routeParams, $location, entityReso currIds.push(itemId); $scope.model.value = currIds.join(); } + + removeAllEntriesAction.isDisabled = false; }; $scope.clear = function () { $scope.model.value = null; + removeAllEntriesAction.isDisabled = true; }; $scope.openEditor = function (item) { @@ -362,6 +383,8 @@ function contentPickerController($scope, $q, $routeParams, $location, entityReso //sync the sortable model $scope.sortableModel = valueIds; + removeAllEntriesAction.isDisabled = valueIds.length === 0; + //load current data if anything selected if (valueIds.length > 0) { @@ -507,6 +530,22 @@ function contentPickerController($scope, $q, $routeParams, $location, entityReso } } + function removeAllEntries() { + localizationService.localizeMany(["content_nestedContentDeleteAllItems", "general_delete"]).then(function (data) { + overlayService.confirmDelete({ + title: data[1], + content: data[0], + close: function () { + overlayService.close(); + }, + submit: function () { + $scope.clear(); + overlayService.close(); + } + }); + }); + } + function init() { userService.getCurrentUser().then(function (user) { diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.html index de80b05760..14741d6ca6 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.html @@ -1,13 +1,13 @@
    -
    +
    + Click to embed + -
    -
    -
    -
    +
    diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/macro.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/macro.html index cc581698fc..c07d29d89c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/macro.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/macro.html @@ -1,16 +1,13 @@
    -
    -
    +
    -
    -
    -
    -
    -
    - + {{title}} + + + + +
    diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html index fa32821917..2ab42807fd 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.html @@ -1,16 +1,19 @@
    - -
    +
    + + Click to insert image + +
    - - + + +
    diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.doctypepicker.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.doctypepicker.html index f62894e043..fa146f12f0 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.doctypepicker.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.doctypepicker.html @@ -3,7 +3,7 @@ - @@ -13,20 +13,20 @@ -
    + Element Type Template +
    - + {{ph = placeholder(config);""}} -
    +
    +
    @@ -49,17 +49,19 @@ - +

    - Group:
    + Group:
    Select the group whose properties should be displayed. If left blank, the first group on the element type will be used.

    - Template:
    + Template:
    Enter an angular expression to evaluate against each item for its name. Use {{$index}} to display the item index diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.html index 221e7666f7..abd0c6bc81 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.html @@ -22,16 +22,16 @@

    -
    \ No newline at end of file +
    diff --git a/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js b/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js index a65f82f525..684ce6d2f0 100644 --- a/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js @@ -94,7 +94,7 @@ vm.changePasswordModel.config = data; //the user has a password if they are not states: Invited, NoCredentials - vm.changePasswordModel.config.hasPassword = vm.user.userState !== 3 && vm.user.userState !== 4; + vm.changePasswordModel.config.hasPassword = vm.user.userState !== "Invited" && vm.user.userState !== "Inactive"; vm.changePasswordModel.config.disableToggle = true; @@ -207,7 +207,7 @@ vm.changePasswordModel.value = {}; //the user has a password if they are not states: Invited, NoCredentials - vm.changePasswordModel.config.hasPassword = vm.user.userState !== 3 && vm.user.userState !== 4; + vm.changePasswordModel.config.hasPassword = vm.user.userState !== "Invited" && vm.user.userState !== "Inactive"; }, err => { contentEditingHelper.handleSaveError({ err: err, @@ -363,7 +363,7 @@ function disableUser() { vm.disableUserButtonState = "busy"; usersResource.disableUsers([vm.user.id]).then(function (data) { - vm.user.userState = 1; + vm.user.userState = "Disabled"; setUserDisplayState(); vm.disableUserButtonState = "success"; @@ -376,7 +376,7 @@ function enableUser() { vm.enableUserButtonState = "busy"; usersResource.enableUsers([vm.user.id]).then(function (data) { - vm.user.userState = 0; + vm.user.userState = "Active"; setUserDisplayState(); vm.enableUserButtonState = "success"; }, function (error) { @@ -387,7 +387,7 @@ function unlockUser() { vm.unlockUserButtonState = "busy"; usersResource.unlockUsers([vm.user.id]).then(function (data) { - vm.user.userState = 0; + vm.user.userState = "Active"; vm.user.failedPasswordAttempts = 0; setUserDisplayState(); vm.unlockUserButtonState = "success"; @@ -540,7 +540,7 @@ } function setUserDisplayState() { - vm.user.userDisplayState = usersHelper.getUserStateFromValue(vm.user.userState); + vm.user.userDisplayState = usersHelper.getUserStateByKey(vm.user.userState); } function formatDatesToLocal(user) { diff --git a/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js b/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js index 70102c9418..d62ed4507f 100644 --- a/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js @@ -104,7 +104,7 @@ vm.defaultButton = getCreateUserButton(); } - + vm.toggleFilter = toggleFilter; vm.setUsersViewState = setUsersViewState; @@ -319,7 +319,7 @@ vm.selection.forEach(function (userId) { var user = getUserFromArrayById(userId, vm.users); if (user) { - user.userState = 1; + user.userState = "Disabled"; } }); // show the correct badges @@ -340,7 +340,7 @@ vm.selection.forEach(function (userId) { var user = getUserFromArrayById(userId, vm.users); if (user) { - user.userState = 0; + user.userState = "Active"; } }); // show the correct badges @@ -359,7 +359,7 @@ vm.selection.forEach(function (userId) { var user = getUserFromArrayById(userId, vm.users); if (user) { - user.userState = 0; + user.userState = "Active"; } }); // show the correct badges @@ -452,7 +452,7 @@ } function areAllSelected() { - // we need to check if the current user is part of the selection and + // we need to check if the current user is part of the selection and // subtract the user from the total selection to find out if all users are selected var includesCurrentUser = vm.users.some(function (user) { return user.isCurrentUser === true; }); @@ -727,7 +727,7 @@ function setUserDisplayState(users) { users.forEach(function (user) { - user.userDisplayState = usersHelper.getUserStateFromValue(user.userState); + user.userDisplayState = usersHelper.getUserStateByKey(user.userState); }); } diff --git a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js index 31310e1c46..9760a91c7c 100644 --- a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js +++ b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js @@ -1377,13 +1377,13 @@ function MockHttpExpectation(method, url, data, headers) { }; this.matchHeaders = function (h) { - if (angular.isUndefined(headers)) return true; + if (Utilities.isUndefined(headers)) return true; if (angular.isFunction(headers)) return headers(h); return angular.equals(headers, h); }; this.matchData = function (d) { - if (angular.isUndefined(data)) return true; + if (Utilities.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); if (data && !Utilities.isString(data)) return angular.toJson(data) == d; return data == d; diff --git a/src/Umbraco.Web.UI.NetCore/appsettings.Development.json b/src/Umbraco.Web.UI.NetCore/appsettings.Development.json index 72ff9076e9..983b157ef1 100644 --- a/src/Umbraco.Web.UI.NetCore/appsettings.Development.json +++ b/src/Umbraco.Web.UI.NetCore/appsettings.Development.json @@ -20,9 +20,9 @@ "CMS": { "Global": { "Smtp": { - // "From": "your@email.here", - // "Host": "localhost", - // "Port": "25" +// "From": "your@email.here", +// "Host": "localhost", +// "Port": "25" } }, "Hosting": { diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/cs.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/cs.xml index 0c7b938d41..eda9c33fd3 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/cs.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/cs.xml @@ -1,883 +1,882 @@ - - Umbraco komunita - https://our.umbraco.com/documentation/Extending-Umbraco/Language-Files - - - Kultura a názvy hostitelů - Historie změn - Prohlížet uzel - Změnit typ dokumentu - Kopírovat - Vytvořit - Exportovat - Vytvořit balíček - Vytvořit skupinu - Odstranit - Deaktivovat - Vyprázdnit koš - Aktivovat - Exportovat typ dokumentu - Importovat typ dokumentu - Importovat balíček - Editovat na stránce - Odhlásit - Přesunout - Upozornění - Veřejný přístup - Publikovat - Nepublikovat - Znovu načíst uzly - Znovu publikovat celý web - Práva - Přejmenovat - Obnovit - Nastavit oprávnění pro stránku %0% - Kam zkopírovat - Kam přesunout - do struktury stromu pod - Choose where to copy the selected item(s) - Choose where to move the selected item(s) - bylo přesunuto - bylo zkopírováno - bylo smazáno - Vrátit starší verzi - Odeslat k publikování - Odeslat k překladu - Nastavit skupinu - Seřadit - Přeložit - Aktualizovat - Nastavit oprávnění - Odemknout - Vytvořit šablonu obsahu - Přeposlat pozvánku - - - Obsah - Administrace - Struktura - Ostatní - - - Povolit přístup k přiřazování kultury a názvů hostitelů - Povolit přístup k zobrazení protokolu historie uzlu - Povolit přístup k zobrazení uzlu - Povolit přístup ke změně typu dokumentu daného uzlu - Povolit přístup ke kopírování uzlu - Povolit přístup k vytváření uzlů - Povolit přístup k mazání uzlů - Povolit přístup k přesunutí uzlu - Povolit přístup k nastavení a změně veřejného přístupu k uzlu - Povolit přístup k publikování uzlu - Povolit přístup k zrušení publikování uzlu - Povolit přístup ke změně oprávnění pro uzel - Povolit přístup k vrácení uzlu do předchozího stavu - Povolit přístup k odeslání uzlu ke schválení před publikováním - Povolit přístup k odeslání uzlu k překladu - Povolit přístup ke změně pořadí uzlů - Povolit přístup k překladu uzlu - Povolit přístup k uložení uzlu - Povolit přístup k vytvoření šablony obsahu - - - Obsah - Info - - - Přístup zakázán. - Přidat novou doménu - Odebrat - Neplatný uzel. - Neplatný tvar domény. - Doména už byla přiřazena. - Doména - Jazyk - Nová doména '%0%' byla vytvořena - Doména '%0%' je odstraněna - Doména '%0%' už byla přiřazena - Doména '%0%' byla aktualizována - Editace aktuálních domén - - + Umbraco komunita + https://our.umbraco.com/documentation/Extending-Umbraco/Language-Files + + + Kultura a názvy hostitelů + Historie změn + Prohlížet uzel + Změnit typ dokumentu + Kopírovat + Vytvořit + Exportovat + Vytvořit balíček + Vytvořit skupinu + Odstranit + Deaktivovat + Vyprázdnit koš + Aktivovat + Exportovat typ dokumentu + Importovat typ dokumentu + Importovat balíček + Editovat na stránce + Odhlásit + Přesunout + Upozornění + Veřejný přístup + Publikovat + Nepublikovat + Znovu načíst uzly + Znovu publikovat celý web + Práva + Přejmenovat + Obnovit + Nastavit oprávnění pro stránku %0% + Kam zkopírovat + Kam přesunout + do struktury stromu pod + Choose where to copy the selected item(s) + Choose where to move the selected item(s) + bylo přesunuto + bylo zkopírováno + bylo smazáno + Vrátit starší verzi + Odeslat k publikování + Odeslat k překladu + Nastavit skupinu + Seřadit + Přeložit + Aktualizovat + Nastavit oprávnění + Odemknout + Vytvořit šablonu obsahu + Přeposlat pozvánku + + + Obsah + Administrace + Struktura + Ostatní + + + Povolit přístup k přiřazování kultury a názvů hostitelů + Povolit přístup k zobrazení protokolu historie uzlu + Povolit přístup k zobrazení uzlu + Povolit přístup ke změně typu dokumentu daného uzlu + Povolit přístup ke kopírování uzlu + Povolit přístup k vytváření uzlů + Povolit přístup k mazání uzlů + Povolit přístup k přesunutí uzlu + Povolit přístup k nastavení a změně veřejného přístupu k uzlu + Povolit přístup k publikování uzlu + Povolit přístup k zrušení publikování uzlu + Povolit přístup ke změně oprávnění pro uzel + Povolit přístup k vrácení uzlu do předchozího stavu + Povolit přístup k odeslání uzlu ke schválení před publikováním + Povolit přístup k odeslání uzlu k překladu + Povolit přístup ke změně pořadí uzlů + Povolit přístup k překladu uzlu + Povolit přístup k uložení uzlu + Povolit přístup k vytvoření šablony obsahu + + + Obsah + Info + + + Přístup zakázán. + Přidat novou doménu + Odebrat + Neplatný uzel. + Neplatný tvar domény. + Doména už byla přiřazena. + Doména + Jazyk + Nová doména '%0%' byla vytvořena + Doména '%0%' je odstraněna + Doména '%0%' už byla přiřazena + Doména '%0%' byla aktualizována + Editace aktuálních domén + + - Dědit - Kultura - nebo dědění kultury po nadřazeném uzlu. Vztahuje se také
    + Dědit + Kultura + nebo dědění kultury po nadřazeném uzlu. Vztahuje se také
    na aktivní uzel.]]>
    - Domény - - - Zrušit výběr - Vybrat - Dělat něco jiného - Tučně - Zrušit odsazení odstavce - Vložit formulářové pole - Vložit grafický nadpis - Editovat Html - Odsadit odstavec - Kurzíva - Zarovnat na střed - Zarovnat na levo - Zarovnat na pravo - Vložit odkaz - Vložit místní odkaz (kotvu) - Neuspořádaný seznam - Číslovaný seznam - Vložit makro - Vložit obrázek - Publikovat a zavřít - Publikovat s potomky - Editovat vztahy - Zpět na seznam - Uložit - Uložit a zavřít - Uložit a publikovat - Uložit a naplánovat - Uložit a odeslat ke schválení - Náhled - Uložit zobrazení seznamu - Naplánovat - Náhled - Náhled je deaktivován, protože není přiřazena žádná šablona - Vybrat styl - Zobrazit styly - Vložit tabulku - Generovat modely a zavřít - Uložit a generovat modely - Zpět - Znovu - Obnovit - Smazat štítek - Zrušit - Potvrdit - Další možnosti publikování - - - Zobrazení pro - Obsah smazán - Obsah nepublikován - Obsah nepublikován pro jazyky: %0% - Obsah publikován - Obsah publikován pro jazyky: %0% - Obsah uložen - Obsah uložen pro jazyky: %0% - Obsah přesunut - Obsah zkopírován - Obsah vrácen zpět - Obsah odeslán k publikování - Obsah odeslán k publikování pro jazyky: %0% - Seřadit podřízené položky prováděné uživatelem - Kopírovat - Publikovat - Publikovat - Přesunout - Uložit - Uložit - Smazat - Nepublikovat - Nepublikovat - Vrátit zpět - Odeslat k publikování - Odeslat k publikování - Seřadit - Historie (všechny jazyky) - - - Abyste změnili typ dokumentu pro zvolený obsah, nejprve jej vyberte ze seznamu typů platných pro tohle umístění. - Pak potvrďte a/nebo pozměňte mapování vlastností z aktuálního typu na nový a dejte Uložit. - Obsah byl znovu publikován. - Aktuální vlastnost - Aktuální typ - Typ dokumentu nemůže být změněn, neboť neexistují alternativy platné pro toto umístění. - Typ dokumentu byl změněn - Mapování vlastností - Mapování na vlastnost - Nová šablona - Nový typ - nic - Obsah - Vybrat nový typ dokumentu - Typ dokumentu pro zvolený obsah byl úspěšně změněný na [new type] a následující vlastnosti byly namapovány: - na - Nelze dokončit mapování vlastností, neboť nejméně jedna z vlastností má definováno více než jedno mapování. - Jsou zobrazeny pouze alternativní typy platné pro aktuální umístění. - - - Nepodařilo se vytvořit složku pod rodičem s ID %0% - Nepodařilo se vytvořit složku pod rodičem s názvem %0% - Název složky nesmí obsahovat nepovolené znaky. - Odstranění položky se nezdařilo: %0% - - - Is Published - O této stránce - Alias - (jak byste popsali obrázek přes telefon) - Alternativní adresy URL - Klikněte pro editaci položky - Vytvořeno uživatelem - Původní autor - Aktualizováno uživatelem - Vytvořeno - Datum/čas vytvoření tohoto dokumentu - Typ dokumentu - Editování - Datum odebrání - Tato položko byla změněna po publikování - Tato položka není publikována - Naposledy publikováno - There are no items to show - There are no items to show in the list. - No child items have been added - No members have been added - Typ média - Odkaz na položky medií - Skupina členů - Role - Typ člena - No changes have been made - Nevybráno žádné datum - Titulek stránky - This media item has no link - No content can be added for this item - Vlastnosti - Tento dokument je publikován, ale není viditelný, protože jeho rodič '%0%' publikován není - Tato jazyková verze je publikována, ale není viditelná, protože její rodič '%0%' publikován není - Jejda: tento dokument je publikován, ale není v mezipaměti (vnitřní chyba) - Could not get the URL - This document is published but its URL would collide with content %0% - This document is published but its URL cannot be routed - Publikovat - Published - Published (pending changes) - Stav publikování - Publish with descendants to publish %0% and all content items underneath and thereby making their content publicly available.]]> - Publish with descendants to publish the selected languages and the same languages of content items underneath and thereby making their content publicly available.]]> - Datum publikování - Datum ukončení publikování - Datum odebrání - Set date - Třídění je aktualizováno - Abyste uzly setřídili, jednoduše je přetáhněte anebo klikněte na jednu z hlaviček sloupce. Podržením "shift" nebo "control" při výběru můžete označit uzlů více. - Statistika - Titulek (volitelně) - Alternative text (optional) - Typ - Nepublikovat - Draft - Not created - Naposledy změněno - Datum/čas poslední změny dokumentu - Odebrat soubor(y) - Click here to remove the image from the media item - Click here to remove the file from the media item - URL adresa dokumentu - Člen skupin(y) - Není člen skupin(y) - Podřízené položky - Cíl - This translates to the following time on the server: - What does this mean?]]> - Are you sure you want to delete this item? - Are you sure you want to delete all items? - Property %0% uses editor %1% which is not supported by Nested Content. - No content types are configured for this property. - Add element type - Select element type - Select the group whose properties should be displayed. If left blank, the first group on the element type will be used. - Enter an angular expression to evaluate against each item for its name. Use - to display the item index - Add another text box - Remove this text box - Content root - Include drafts: also publish unpublished content items. - This value is hidden. If you need access to view this value please contact your website administrator. - This value is hidden. - What languages would you like to publish? All languages with content are saved! - What languages would you like to publish? - What languages would you like to save? - All languages with content are saved on creation! - What languages would you like to send for approval? - What languages would you like to schedule? - Select the languages to unpublish. Unpublishing a mandatory language will unpublish all languages. - Published Languages - Unpublished Languages - Unmodified Languages - These languages haven't been created - Ready to Publish? - Ready to Save? - Send for approval - Select the date and time to publish and/or unpublish the content item. - Create new - Paste from clipboard - This item is in the Recycle Bin - - - Vytvořit novou šablonu obsahu z '%0%' - Prázdná - Vybrat obsahovou šablonu - Šablona obsahu byla vytvořena - Šablona obsahu byla vytvořena z '%0%' - Již existuje jiná šablona obsahu se stejným názvem - Šablona obsahu je předdefinovaný obsah, který si editor může vybrat jako základ pro vytváření nového obsahu - - - Klikněte pro nahrání - nebo kliknutím sem vyberte soubory - Sem můžete přetáhnout a nahrát soubory. - Tento soubor nelze nahrát, nemá povolený typ souboru - Maximální velikost souboru je - Nejvyšší složka médií - Nepodařilo se přesunout média - Nadřazené a cílové složky nemohou být stejné - Médium se nepodařilo zkopírovat - Nepodařilo se vytvořit složku pod nadřazeným id %0% - Nepodařilo se přejmenovat složku s id %0% - Přetáhněte své soubory do oblasti - - - Vytvořit nového člena - Všichni členové - Členské skupiny nemají žádné další vlastnosti pro úpravy. - - - Kde chcete vytvořit nový %0% - Vytvořit položku pod - Vyberte typ dokumentu, pro který chcete vytvořit šablonu obsahu - Zadejte název složky - Vyberte typ a titulek - "typy dokumentů".]]> - Typy dokumentů v části Nastavení.]]> - Vybraná stránka ve stromu obsahu neumožňuje vytváření žádných stránek pod ní. - Oprávnění k úpravám pro tento typ dokumentu - Vytvořit nový typ dokumentu - Typy dokumentů v části Nastavení změnou možnosti Povolit jako root v části Oprávnění.]]> - "typy medií".]]> - Vybraná média ve stromu neumožňuje vytváření pod nimi žádná další média. - Upravit oprávnění pro tento typ média - Typ dokumentu bez šablony - Nová složka - Nový datový typ - Nový skript JavaScript - Nová prázdná částečná šablona - Nové makro pro částečnou šablonu - Nová částečná šablona ze snippetu - Nové makro částečné šablony ze snippetu - Nové makro pro částečnou šablonu (bez makra) - Nový soubor stylů - stylopis - Nový soubor stylů Rich Text editoru - - - Prohlédnout svůj web - - Skrýt - Jestli se umbraco neotevírá, možná budete muset povolit na tomto webu vyskakovací okna - byl otevřený v novém okně - Restart - Navštívit - Vítejte - - - Zůstat zde - Zahodit změny - Máte neuložené změny - Opravdu chcete opustit tuto stránku? Máte neuložené změny. - Publikování zviditelní vybrané položky na webu. - Zrušení publikování odstraní vybrané položky a všechny jejich potomky z webu. - Zrušení publikování odstraní tuto stránku a všechny její potomky z webu. - Máte neuložené změny. Provedením změn typu dokumentu změny zahodíte. - - - Hotovo - Smazána %0% položka - Smazáno %0% položek - Smazána %0% z %1% položek - Smazáno %0% z %1% položek - Publikována %0% položka - Publikováno %0% položek - Publikována %0% z %1% položek - Publikováno %0% z %1% položek - Zrušeno publikování %0% položky - Zrušeno publikování %0% položek - Zrušeno publikování %0% z %1% položek - Zrušeno publikování %0% z %1% položek - Přesunuta %0% položka - Přesunuto %0% položek - Přesunuta %0% z %1% položek - Přesunuto %0% z %1% položek - Zkopírována %0% položka - Zkopírováno %0% položek - Zkopírována %0% z %1% položek - Zkopírováno %0% z %1% položek - - - Titulek odkazu - Odkaz - Kotva / dotaz - Název - Spravovat názvy hostitelů - Zavřít toto okno - Jste si jistí. že chcete odstranit - Jste si jistí, že chcete deaktivovat - Jste si jistí? - Jste si jistí? - Vyjmout - Editovat položku slovníku - Editovat jazyk - Edit selected media - Vložit místní odkaz - Vložit znak - Vložit grafický titulek - Vložit obrázek - Vložit odkaz - Kliknout pro přidání makra - Vložit tabulku - Tím se odstraní jazyk - Změna kultury jazyka může být náročná operace a bude mít za následek opětovné sestavení mezipaměti obsahu a indexů - Naposledy editováno - Odkaz - Místní odkaz: - Při používání místních odkazů vložte znak "#" před odkaz - Otevřít v novém okně? - Nastavení makra - Toto makro nemá žádné vlastnosti, které by bylo možno editovat - Vložit - Editovat oprávnění pro - Nastavit oprávnění pro - Nastavit oprávnění pro %0% pro skupinu %1% - Vyberte skupiny uživatelů, pro které chcete nastavit oprávnění - Položky koše jsou nyní mazány. Nezavírejte, prosím, toto okno, dokud operace probíhá - Koš je nyní prázdný - Odebrání položek z koše způsobí jejich trvalé odstranění - regexlib.com má v tuto chvíli nějaké problémy, které jsou mimo naší kontrolu. Omlouváme se za vzniklé nepříjemnosti.]]> - Vyhledat regulární výraz pro přidání validace formulářového prvku. Například: 'email, 'PSČ' 'url' - Odstranit makro - Pole je vyžadování - Web je přeindexován - Mezipaměť webu byla obnovena. Všechen publikovaný obsah je nyní aktuální, zatímco nepublikovaný obsah zůstal nepublikovaný. - Mezipaměť webu bude obnovena. Všechen publikovaný obsah bude aktualizován, zatímco nepublikovaný obsah zůstane nepublikovaný. - Počet sloupců - Počet řádků - Klikněte na obrázek pro zobrazení v plné velikosti - Vybrat položku - Zobrazit položku mezipaměti - Navázat na originál - Včetně potomků - Nejpřátelštější komunita - Odkaz na stránku - Otevře propojený dokument v novém okně nebo na kartě - Odkaz na média - Vybrat počáteční uzel obsahu - Vybrat média - Vybrat typ média - Vybrat ikonu - Vybrat položku - Vybrat odkaz - Vybrat makro - Vybrat obsah - Vybrat typ obsahu - Vybrat počáteční uzel média - Vybrat člena - Vybrat skupinu členů - Vybrat typ člena - Vybrat uzel - Vybrat sekce - Vybrat uživatele - Nebyly nalezeny žádné ikony - Pro toto makro neexistují žádné parametry - K dispozici nejsou žádná makra - Externí poskytovatelé přihlášení - Podrobnosti o výjimce - Stacktrace - Vnitřní výjimka - Propojit se - Odpojit se - účet - Vybrat editora - Vybrat snippet - Tímto odstraníte uzel a všechny jeho jazyky. Pokud chcete smazat pouze jeden jazyk, měli byste zrušit publikování uzlu v tomto jazyce. - - - Nejsou žádné položky ve slovníku. - - - Domény + + + Zrušit výběr + Vybrat + Dělat něco jiného + Tučně + Zrušit odsazení odstavce + Vložit formulářové pole + Vložit grafický nadpis + Editovat Html + Odsadit odstavec + Kurzíva + Zarovnat na střed + Zarovnat na levo + Zarovnat na pravo + Vložit odkaz + Vložit místní odkaz (kotvu) + Neuspořádaný seznam + Číslovaný seznam + Vložit makro + Vložit obrázek + Publikovat a zavřít + Publikovat s potomky + Editovat vztahy + Zpět na seznam + Uložit + Uložit a zavřít + Uložit a publikovat + Uložit a naplánovat + Uložit a odeslat ke schválení + Náhled + Uložit zobrazení seznamu + Naplánovat + Náhled + Náhled je deaktivován, protože není přiřazena žádná šablona + Vybrat styl + Zobrazit styly + Vložit tabulku + Generovat modely a zavřít + Uložit a generovat modely + Zpět + Znovu + Obnovit + Smazat štítek + Zrušit + Potvrdit + Další možnosti publikování + + + Zobrazení pro + Obsah smazán + Obsah nepublikován + Obsah nepublikován pro jazyky: %0% + Obsah publikován + Obsah publikován pro jazyky: %0% + Obsah uložen + Obsah uložen pro jazyky: %0% + Obsah přesunut + Obsah zkopírován + Obsah vrácen zpět + Obsah odeslán k publikování + Obsah odeslán k publikování pro jazyky: %0% + Seřadit podřízené položky prováděné uživatelem + Kopírovat + Publikovat + Publikovat + Přesunout + Uložit + Uložit + Smazat + Nepublikovat + Nepublikovat + Vrátit zpět + Odeslat k publikování + Odeslat k publikování + Seřadit + Historie (všechny jazyky) + + + Abyste změnili typ dokumentu pro zvolený obsah, nejprve jej vyberte ze seznamu typů platných pro tohle umístění. + Pak potvrďte a/nebo pozměňte mapování vlastností z aktuálního typu na nový a dejte Uložit. + Obsah byl znovu publikován. + Aktuální vlastnost + Aktuální typ + Typ dokumentu nemůže být změněn, neboť neexistují alternativy platné pro toto umístění. + Typ dokumentu byl změněn + Mapování vlastností + Mapování na vlastnost + Nová šablona + Nový typ + nic + Obsah + Vybrat nový typ dokumentu + Typ dokumentu pro zvolený obsah byl úspěšně změněný na [new type] a následující vlastnosti byly namapovány: + na + Nelze dokončit mapování vlastností, neboť nejméně jedna z vlastností má definováno více než jedno mapování. + Jsou zobrazeny pouze alternativní typy platné pro aktuální umístění. + + + Nepodařilo se vytvořit složku pod rodičem s ID %0% + Nepodařilo se vytvořit složku pod rodičem s názvem %0% + Název složky nesmí obsahovat nepovolené znaky. + Odstranění položky se nezdařilo: %0% + + + Is Published + O této stránce + Alias + (jak byste popsali obrázek přes telefon) + Alternativní adresy URL + Klikněte pro editaci položky + Vytvořeno uživatelem + Původní autor + Aktualizováno uživatelem + Vytvořeno + Datum/čas vytvoření tohoto dokumentu + Typ dokumentu + Editování + Datum odebrání + Tato položko byla změněna po publikování + Tato položka není publikována + Naposledy publikováno + There are no items to show + There are no items to show in the list. + No child items have been added + No members have been added + Typ média + Odkaz na položky medií + Skupina členů + Role + Typ člena + No changes have been made + Nevybráno žádné datum + Titulek stránky + This media item has no link + No content can be added for this item + Vlastnosti + Tento dokument je publikován, ale není viditelný, protože jeho rodič '%0%' publikován není + Tato jazyková verze je publikována, ale není viditelná, protože její rodič '%0%' publikován není + Jejda: tento dokument je publikován, ale není v mezipaměti (vnitřní chyba) + Could not get the URL + This document is published but its URL would collide with content %0% + This document is published but its URL cannot be routed + Publikovat + Published + Published (pending changes) + Stav publikování + Publish with descendants to publish %0% and all content items underneath and thereby making their content publicly available.]]> + Publish with descendants to publish the selected languages and the same languages of content items underneath and thereby making their content publicly available.]]> + Datum publikování + Datum ukončení publikování + Datum odebrání + Set date + Třídění je aktualizováno + Abyste uzly setřídili, jednoduše je přetáhněte anebo klikněte na jednu z hlaviček sloupce. Podržením "shift" nebo "control" při výběru můžete označit uzlů více. + Statistika + Titulek (volitelně) + Alternative text (optional) + Typ + Nepublikovat + Draft + Not created + Naposledy změněno + Datum/čas poslední změny dokumentu + Odebrat soubor(y) + Click here to remove the image from the media item + Click here to remove the file from the media item + URL adresa dokumentu + Člen skupin(y) + Není člen skupin(y) + Podřízené položky + Cíl + This translates to the following time on the server: + What does this mean?]]> + Are you sure you want to delete this item? + Are you sure you want to delete all items? + Property %0% uses editor %1% which is not supported by Nested Content. + No content types are configured for this property. + Add element type + Select element type + Select the group whose properties should be displayed. If left blank, the first group on the element type will be used. + Enter an angular expression to evaluate against each item for its name. Use + to display the item index + Add another text box + Remove this text box + Content root + Include drafts: also publish unpublished content items. + This value is hidden. If you need access to view this value please contact your website administrator. + This value is hidden. + What languages would you like to publish? All languages with content are saved! + What languages would you like to publish? + What languages would you like to save? + All languages with content are saved on creation! + What languages would you like to send for approval? + What languages would you like to schedule? + Select the languages to unpublish. Unpublishing a mandatory language will unpublish all languages. + Published Languages + Unpublished Languages + Unmodified Languages + These languages haven't been created + Ready to Publish? + Ready to Save? + Send for approval + Select the date and time to publish and/or unpublish the content item. + Create new + Paste from clipboard + This item is in the Recycle Bin + + + Vytvořit novou šablonu obsahu z '%0%' + Prázdná + Vybrat obsahovou šablonu + Šablona obsahu byla vytvořena + Šablona obsahu byla vytvořena z '%0%' + Již existuje jiná šablona obsahu se stejným názvem + Šablona obsahu je předdefinovaný obsah, který si editor může vybrat jako základ pro vytváření nového obsahu + + + Klikněte pro nahrání + nebo kliknutím sem vyberte soubory + Sem můžete přetáhnout a nahrát soubory. + Tento soubor nelze nahrát, nemá povolený typ souboru + Maximální velikost souboru je + Nejvyšší složka médií + Nepodařilo se přesunout média + Nadřazené a cílové složky nemohou být stejné + Médium se nepodařilo zkopírovat + Nepodařilo se vytvořit složku pod nadřazeným id %0% + Nepodařilo se přejmenovat složku s id %0% + Přetáhněte své soubory do oblasti + + + Vytvořit nového člena + Všichni členové + Členské skupiny nemají žádné další vlastnosti pro úpravy. + + + Kde chcete vytvořit nový %0% + Vytvořit položku pod + Vyberte typ dokumentu, pro který chcete vytvořit šablonu obsahu + Zadejte název složky + Vyberte typ a titulek + "typy dokumentů".]]> + Typy dokumentů v části Nastavení.]]> + Vybraná stránka ve stromu obsahu neumožňuje vytváření žádných stránek pod ní. + Oprávnění k úpravám pro tento typ dokumentu + Vytvořit nový typ dokumentu + Typy dokumentů v části Nastavení změnou možnosti Povolit jako root v části Oprávnění.]]> + "typy medií".]]> + Vybraná média ve stromu neumožňuje vytváření pod nimi žádná další média. + Upravit oprávnění pro tento typ média + Typ dokumentu bez šablony + Nová složka + Nový datový typ + Nový skript JavaScript + Nová prázdná částečná šablona + Nové makro pro částečnou šablonu + Nová částečná šablona ze snippetu + Nové makro částečné šablony ze snippetu + Nové makro pro částečnou šablonu (bez makra) + Nový soubor stylů - stylopis + Nový soubor stylů Rich Text editoru + + + Prohlédnout svůj web + - Skrýt + Jestli se umbraco neotevírá, možná budete muset povolit na tomto webu vyskakovací okna + byl otevřený v novém okně + Restart + Navštívit + Vítejte + + + Zůstat zde + Zahodit změny + Máte neuložené změny + Opravdu chcete opustit tuto stránku? Máte neuložené změny. + Publikování zviditelní vybrané položky na webu. + Zrušení publikování odstraní vybrané položky a všechny jejich potomky z webu. + Zrušení publikování odstraní tuto stránku a všechny její potomky z webu. + Máte neuložené změny. Provedením změn typu dokumentu změny zahodíte. + + + Hotovo + Smazána %0% položka + Smazáno %0% položek + Smazána %0% z %1% položek + Smazáno %0% z %1% položek + Publikována %0% položka + Publikováno %0% položek + Publikována %0% z %1% položek + Publikováno %0% z %1% položek + Zrušeno publikování %0% položky + Zrušeno publikování %0% položek + Zrušeno publikování %0% z %1% položek + Zrušeno publikování %0% z %1% položek + Přesunuta %0% položka + Přesunuto %0% položek + Přesunuta %0% z %1% položek + Přesunuto %0% z %1% položek + Zkopírována %0% položka + Zkopírováno %0% položek + Zkopírována %0% z %1% položek + Zkopírováno %0% z %1% položek + + + Titulek odkazu + Odkaz + Kotva / dotaz + Název + Spravovat názvy hostitelů + Zavřít toto okno + Jste si jistí. že chcete odstranit + Jste si jistí, že chcete deaktivovat + Jste si jistí? + Jste si jistí? + Vyjmout + Editovat položku slovníku + Editovat jazyk + Edit selected media + Vložit místní odkaz + Vložit znak + Vložit grafický titulek + Vložit obrázek + Vložit odkaz + Kliknout pro přidání makra + Vložit tabulku + Tím se odstraní jazyk + Změna kultury jazyka může být náročná operace a bude mít za následek opětovné sestavení mezipaměti obsahu a indexů + Naposledy editováno + Odkaz + Místní odkaz: + Při používání místních odkazů vložte znak "#" před odkaz + Otevřít v novém okně? + Nastavení makra + Toto makro nemá žádné vlastnosti, které by bylo možno editovat + Vložit + Editovat oprávnění pro + Nastavit oprávnění pro + Nastavit oprávnění pro %0% pro skupinu %1% + Vyberte skupiny uživatelů, pro které chcete nastavit oprávnění + Položky koše jsou nyní mazány. Nezavírejte, prosím, toto okno, dokud operace probíhá + Koš je nyní prázdný + Odebrání položek z koše způsobí jejich trvalé odstranění + regexlib.com má v tuto chvíli nějaké problémy, které jsou mimo naší kontrolu. Omlouváme se za vzniklé nepříjemnosti.]]> + Vyhledat regulární výraz pro přidání validace formulářového prvku. Například: 'email, 'PSČ' 'URL' + Odstranit makro + Pole je vyžadování + Web je přeindexován + Mezipaměť webu byla obnovena. Všechen publikovaný obsah je nyní aktuální, zatímco nepublikovaný obsah zůstal nepublikovaný. + Mezipaměť webu bude obnovena. Všechen publikovaný obsah bude aktualizován, zatímco nepublikovaný obsah zůstane nepublikovaný. + Počet sloupců + Počet řádků + Klikněte na obrázek pro zobrazení v plné velikosti + Vybrat položku + Zobrazit položku mezipaměti + Navázat na originál + Včetně potomků + Nejpřátelštější komunita + Odkaz na stránku + Otevře propojený dokument v novém okně nebo na kartě + Odkaz na média + Vybrat počáteční uzel obsahu + Vybrat média + Vybrat typ média + Vybrat ikonu + Vybrat položku + Vybrat odkaz + Vybrat makro + Vybrat obsah + Vybrat typ obsahu + Vybrat počáteční uzel média + Vybrat člena + Vybrat skupinu členů + Vybrat typ člena + Vybrat uzel + Vybrat sekce + Vybrat uživatele + Nebyly nalezeny žádné ikony + Pro toto makro neexistují žádné parametry + K dispozici nejsou žádná makra + Externí poskytovatelé přihlášení + Podrobnosti o výjimce + Stacktrace + Vnitřní výjimka + Propojit se + Odpojit se + účet + Vybrat editora + Vybrat snippet + Tímto odstraníte uzel a všechny jeho jazyky. Pokud chcete smazat pouze jeden jazyk, měli byste zrušit publikování uzlu v tomto jazyce. + + + Nejsou žádné položky ve slovníku. + + + %0%' níže.
    Můžete přidat další jazyky v nabídce 'jazyky' nalevo.]]>
    - Název jazyka - Název jazyka + - Přehled slovníku - - - Konfigurovaní vyhledávače - Zobrazuje vlastnosti a nástroje pro libovolný konfigurovaný vyhledávač (např. pro víceindexový vyhledávač) - Hodnoty pole - Stav - Stav indexu a jeho čitelnost - Indexery - Informace o indexu - Uvádí vlastnosti indexu - Spravovat indexy Examine - Umožňuje zobrazit podrobnosti každého indexu a poskytuje některé nástroje pro správu indexů - Znovu vytvořit index - Přehled slovníku + + + Konfigurovaní vyhledávače + Zobrazuje vlastnosti a nástroje pro libovolný konfigurovaný vyhledávač (např. pro víceindexový vyhledávač) + Hodnoty pole + Stav + Stav indexu a jeho čitelnost + Indexery + Informace o indexu + Uvádí vlastnosti indexu + Spravovat indexy Examine + Umožňuje zobrazit podrobnosti každého indexu a poskytuje některé nástroje pro správu indexů + Znovu vytvořit index + V závislosti na tom, kolik obsahu je na vašem webu, může to chvíli trvat.
    Nedoporučuje se znovu vytvářet index v době vysokého provozu na webu nebo při úpravách obsahu editory. ]]> -
    - Vyhledávače - Prohledat index a zobrazit výsledky - Nástroje - Nástroje pro správu indexu - pole - Index nelze číst a bude nutné jej znovu sestavit - Proces trvá déle, než se očekávalo, zkontrolujte Umbraco log a zkontrolujte, zda během této operace nedošlo k chybám - Tento index nelze znovu sestavit, protože nemá přiřazen - IIndexPopulator - - - Zadejte Vaše uživatelské jméno - Zadejte Vaše heslo - Potvrďte heslo - Pojmenujte %0%... - Zadejte jméno... - Zadejte e-mail... - Zadejte uživatelské jméno... - Popisek... - Zadejte popis... - Pište pro vyhledání... - Pište pro filtrování... - Pište pro vložení štítků (po každém stiskněte klávesu Enter)... - Vložte svůj e-mail - Vložte zprávu... - Vaše uživatelské jméno je obvykle váš e-mail - #hodnota or ?klíč=hodnota - Vložte alias... - Generování aliasu... - - - Vytvořit vlastní zobrazení seznamu - Odebrat vlastní zobrazení seznamu - Typ obsahu, typ média nebo typ člena s tímto aliasem již existuje - - - Přejmenováno - Sem zadejte nový název složky - %0% přejmenováno na %1% - - - Přidat předlohu - Databázový datový typ - GUID editoru vlastností - Editor vlastností - Tlačítka - Povolit rozšířené nastavení pro - Povolit kontextové menu - Největší výchozí rozměr pro vložené obrázky - Související stylopisy - Zobrazit jmenovku - Šířka a výška - Všechny typy vlastností a údaje o nich - použití tohoto datového typu bude trvale smazáno, potvrďte, že je chcete odstranit - Ano, smazat - a všechny typy vlastností a data vlastností používající tento typ dat - Vyberte složku, kterou chcete přesunout - do stromové struktury níže - byla přesunuta pod - %0% vymažete vlastnosti a jejich data z následujících položek]]> - Rozumím, že tato akce odstraní vlastnosti a data založená na tomto datovém typu - - - Vaše data byla uložena, ale než budete moci publikovat tuto stránku, je třeba odstranit některé chyby: - Současný MemberShip Provider nepodporuje změnu hesla (EnablePasswordRetrieval musí mít hodnotu true) - %0% již existuje - Vyskytly se chyby: - Vyskytly se chyby: - Heslo musí být nejméně %0% znaků dlouhé a obsahovat nejméně %1% nealfanumerických znaků - %0% musí být celé číslo - Pole %0% na záložce %1% je povinné - %0% je povinné pole - %0% v %1% není ve správném formátu - %0% není ve správném formátu - - - Ze serveru byla přijata chyba - Použití daného typu souboru bylo zakázáno adminitrátorem - UPOZORNĚNÍ! I když CodeMirror je dle konfigurace povolený, je zakázaný v Internet Exploreru, protože není dost stabilní. - Vyplňte, prosím, alias i název nového typu vlastností! - Vyskytl se problém při čtení/zápisu do určeného souboru nebo adresáře - Chyba při načítání skriptu částečné šablony (soubor: %0%) - Uveďte, prosím, titulek - Vyberte, prosím, typ - Chystáte se obrázek zvětšit více, než je jeho původní rozměr. Opravdu chcete pokračovat? - Počáteční uzel je odstraněný, kontaktujte, prosím, administrátora - Před změnou stylu označte, prosím, obsah - Žádne aktivní styly nejsou dostupné - Umístěte, prosím, kurzor nalevo od těch dvou buňek, které chcete sloučit - Nemužete rozdělit buňku, která nebyla sloučená. - Tato vlastnost je neplatná - - - Volby - O... - Akce - Akce - Přidat - Alias - Vše - Jste si jistí? - Zpět - Zpět na přehled - Okraj - o - Zrušit - Okraj buňky - Vybrat - Vyčistit - Zavřít - Zavřít okno - Komentovat - Potvrdit - Omezit - Zachovat proporce - Obsah - Pokračovat - Kopírovat - Vytvořit - Databáze - Datum - Výchozí - Odstranit - Odstraněno - Odstraňování... - Vzhled - Slovník - Rozměry - Dolů - Stáhnout - Editovat - Editováno - Prvky - Email - Chyba - Pole - Najít - První - Focal point - Obecné - Skupiny - Skupina - Výška - Nápověda - Skrýt - Historie - Ikona - Id - Import - Zahrnout podsložky do vyhledávání - Info - Vnitřní okraj - Vložit - Instalovat - Neplatné - Vyrovnat - Popisek - Jazyk - Poslední - Rozvržení - Odkazy - Nahrávání - Zamčeno - Přihlášení - Odhlášení - Odhlášení - Makro - Povinné - Zpráva - Přesunout - Název - Nový - Následující - Ne - z - Vypnuto - OK - Otevřít - Zapnuto - nebo - Seřadit podle - Heslo - Cesta - Moment, prosím... - Předchozí - Vlastnosti - Obnovit - Email pro obdržení formulářových dat - Koš - Váš koš je prázdný - Znovu načíst - Zbývající - Odebrat - Přejmenovat - Obnovit - Povinné - Načíst - Zopakovat - Oprávnění - Plánované publikování - Hledat - Litujeme, ale nemůžeme najít to, co hledáte. - Nebyly přidány žádné položky - Server - Nastavení - Zobrazit - Zobrazit stránku při odeslání - Rozměr - Seřadit - Stav - Potvrdit - Zadejte - Pište pro vyhledávání... - pod - Nahoru - Aktualizovat - Povýšit - Nahrání - Url - Uživatel - Uživatelské jméno - Hodnota - Pohled - Vítejte... - Šířka - Ano - Složka - Výsledky hledání - Přesunout - Skončil jsem s přesouváním - Náhled - Změnit heslo - na - Seznam - Ukládám... - aktuální - Vložené - vybrané - Další - Články - Videa - Vyčistit - Instalování - - - Modrá - - - Přidat skupinu - Přidat vlastnost - Přidat editor - Přidat šablonu - Přidat vnořený uzel - Přidat potomka - Upravit datový typ - Navigace v sekcích - Klávesové zkratky - zobrazit klávesové zkratky - Přepnout zobrazení seznamu - Přepnout povolení jako root - Okomentovat/Odkomentovat řádky - Odebrat řádek - Kopírovat řádky nahoru - Kopírovat řádky dolů - Přesunout řádky nahoru - Přesunout řádky dolů - Obecný - Editor - Přepnout povolení jazykových verzí - - - Barva pozadí - Tučně - Barva písma - Font - Text - - - Stránka - - - Instalátor se nemůže připojit k databázi. - Nelze uložit soubor web.config. Modifikujte, prosím, připojovací řetězec manuálně. - Vyše databáze byla nalezena a je identifikována jako - Nastavení databáze - + Vyhledávače + Prohledat index a zobrazit výsledky + Nástroje + Nástroje pro správu indexu + pole + Index nelze číst a bude nutné jej znovu sestavit + Proces trvá déle, než se očekávalo, zkontrolujte Umbraco log a zkontrolujte, zda během této operace nedošlo k chybám + Tento index nelze znovu sestavit, protože nemá přiřazen + IIndexPopulator + + + Zadejte Vaše uživatelské jméno + Zadejte Vaše heslo + Potvrďte heslo + Pojmenujte %0%... + Zadejte jméno... + Zadejte e-mail... + Zadejte uživatelské jméno... + Popisek... + Zadejte popis... + Pište pro vyhledání... + Pište pro filtrování... + Pište pro vložení štítků (po každém stiskněte klávesu Enter)... + Vložte svůj e-mail + Vložte zprávu... + Vaše uživatelské jméno je obvykle váš e-mail + #hodnota or ?klíč=hodnota + Vložte alias... + Generování aliasu... + + + Vytvořit vlastní zobrazení seznamu + Odebrat vlastní zobrazení seznamu + Typ obsahu, typ média nebo typ člena s tímto aliasem již existuje + + + Přejmenováno + Sem zadejte nový název složky + %0% přejmenováno na %1% + + + Přidat předlohu + Databázový datový typ + GUID editoru vlastností + Editor vlastností + Tlačítka + Povolit rozšířené nastavení pro + Povolit kontextové menu + Největší výchozí rozměr pro vložené obrázky + Související stylopisy + Zobrazit jmenovku + Šířka a výška + Všechny typy vlastností a údaje o nich + použití tohoto datového typu bude trvale smazáno, potvrďte, že je chcete odstranit + Ano, smazat + a všechny typy vlastností a data vlastností používající tento typ dat + Vyberte složku, kterou chcete přesunout + do stromové struktury níže + byla přesunuta pod + %0% vymažete vlastnosti a jejich data z následujících položek]]> + Rozumím, že tato akce odstraní vlastnosti a data založená na tomto datovém typu + + + Vaše data byla uložena, ale než budete moci publikovat tuto stránku, je třeba odstranit některé chyby: + Současný MemberShip Provider nepodporuje změnu hesla (EnablePasswordRetrieval musí mít hodnotu true) + %0% již existuje + Vyskytly se chyby: + Vyskytly se chyby: + Heslo musí být nejméně %0% znaků dlouhé a obsahovat nejméně %1% nealfanumerických znaků + %0% musí být celé číslo + Pole %0% na záložce %1% je povinné + %0% je povinné pole + %0% v %1% není ve správném formátu + %0% není ve správném formátu + + + Ze serveru byla přijata chyba + Použití daného typu souboru bylo zakázáno adminitrátorem + UPOZORNĚNÍ! I když CodeMirror je dle konfigurace povolený, je zakázaný v Internet Exploreru, protože není dost stabilní. + Vyplňte, prosím, alias i název nového typu vlastností! + Vyskytl se problém při čtení/zápisu do určeného souboru nebo adresáře + Chyba při načítání skriptu částečné šablony (soubor: %0%) + Uveďte, prosím, titulek + Vyberte, prosím, typ + Chystáte se obrázek zvětšit více, než je jeho původní rozměr. Opravdu chcete pokračovat? + Počáteční uzel je odstraněný, kontaktujte, prosím, administrátora + Před změnou stylu označte, prosím, obsah + Žádne aktivní styly nejsou dostupné + Umístěte, prosím, kurzor nalevo od těch dvou buňek, které chcete sloučit + Nemužete rozdělit buňku, která nebyla sloučená. + Tato vlastnost je neplatná + + + Volby + O... + Akce + Akce + Přidat + Alias + Vše + Jste si jistí? + Zpět + Zpět na přehled + Okraj + o + Zrušit + Okraj buňky + Vybrat + Vyčistit + Zavřít + Zavřít okno + Komentovat + Potvrdit + Omezit + Zachovat proporce + Obsah + Pokračovat + Kopírovat + Vytvořit + Databáze + Datum + Výchozí + Odstranit + Odstraněno + Odstraňování... + Vzhled + Slovník + Rozměry + Dolů + Stáhnout + Editovat + Editováno + Prvky + Email + Chyba + Pole + Najít + První + Focal point + Obecné + Skupiny + Skupina + Výška + Nápověda + Skrýt + Historie + Ikona + Id + Import + Zahrnout podsložky do vyhledávání + Info + Vnitřní okraj + Vložit + Instalovat + Neplatné + Vyrovnat + Popisek + Jazyk + Poslední + Rozvržení + Odkazy + Nahrávání + Zamčeno + Přihlášení + Odhlášení + Odhlášení + Makro + Povinné + Zpráva + Přesunout + Název + Nový + Následující + Ne + z + Vypnuto + OK + Otevřít + Zapnuto + nebo + Seřadit podle + Heslo + Cesta + Moment, prosím... + Předchozí + Vlastnosti + Obnovit + Email pro obdržení formulářových dat + Koš + Váš koš je prázdný + Znovu načíst + Zbývající + Odebrat + Přejmenovat + Obnovit + Povinné + Načíst + Zopakovat + Oprávnění + Plánované publikování + Hledat + Litujeme, ale nemůžeme najít to, co hledáte. + Nebyly přidány žádné položky + Server + Nastavení + Zobrazit + Zobrazit stránku při odeslání + Rozměr + Seřadit + Stav + Potvrdit + Zadejte + Pište pro vyhledávání... + pod + Nahoru + Aktualizovat + Povýšit + Nahrání + URL + Uživatel + Uživatelské jméno + Hodnota + Pohled + Vítejte... + Šířka + Ano + Složka + Výsledky hledání + Přesunout + Skončil jsem s přesouváním + Náhled + Změnit heslo + na + Seznam + Ukládám... + aktuální + Vložené + vybrané + Další + Články + Videa + Instalování + + + Modrá + + + Přidat skupinu + Přidat vlastnost + Přidat editor + Přidat šablonu + Přidat vnořený uzel + Přidat potomka + Upravit datový typ + Navigace v sekcích + Klávesové zkratky + zobrazit klávesové zkratky + Přepnout zobrazení seznamu + Přepnout povolení jako root + Okomentovat/Odkomentovat řádky + Odebrat řádek + Kopírovat řádky nahoru + Kopírovat řádky dolů + Přesunout řádky nahoru + Přesunout řádky dolů + Obecný + Editor + Přepnout povolení jazykových verzí + + + Barva pozadí + Tučně + Barva písma + Font + Text + + + Stránka + + + Instalátor se nemůže připojit k databázi. + Nelze uložit soubor web.config. Modifikujte, prosím, připojovací řetězec manuálně. + Vyše databáze byla nalezena a je identifikována jako + Nastavení databáze + instalovat, abyste nainstalovali Umbraco %0% databázi ]]> - následující pro pokračování.]]> - Databáze nenalezena! Zkontrolujte, prosím, že informace v "připojovacím řetězci" souboru "web.config" jsou správné.

    + následující pro pokračování.]]> + Databáze nenalezena! Zkontrolujte, prosím, že informace v "připojovacím řetězci" souboru "web.config" jsou správné.

    Pro pokračování otevřete, prosím, soubor "web.config" (za pužití Visual Studia nebo Vašeho oblíbeného tedtového editoru), přejděte na jeho konec, přidejte připojovací řetězec pro Vaši databázi v klíčí nazvaném "umbracoDbDSN" a soubor uložte.

    - Klikněte na tlačítko zopakovat, až budete hotovi.
    - Další informace o editování souboru web.config zde.

    ]]>
    - + Klikněte na tlačítko zopakovat, až budete hotovi.
    + Další informace o editování souboru web.config zde.

    ]]>
    + Pokud je to nezbytné, kontaktujte vašeho poskytovatele hostingu. Jestliže instalujete na místní počítač nebo server, budete potřebovat informace od Vašeho systémového administrátora.]]> - Stiskněte tlačítko povýšit pro povýšení Vaší databáze na Umbraco %0%

    Neobávejte se - žádný obsah nebude odstraněn a všechno bude fungovat jak má!

    ]]>
    - Stiskněte Následující pro pokračování. ]]> - následující, pro pokračování konfiguračního průvodce]]> - Heslo výchozího uživatele musí být změněno!]]> - Výchozí uživatel byl deaktivován, nebo nemá přístup k umbracu!

    Netřeba nic dalšího dělat. Klikněte na Následující pro pokračování.]]> - Heslo výchozího uživatele bylo úspěšně změněno od doby instalace!

    Netřeba nic dalšího dělat. Klikněte na Následující pro pokračování.]]> - Heslo je změněno! - Mějte skvělý start, sledujte naše uváděcí videa - Kliknutím na tlačítko následující (nebo modifikováním umbracoConfigurationStatus v souboru web.config) přijímáte licenci tohoto software tak, jak je uvedena v poli níže. Upozorňujeme, že tato distribuce Umbraca se skládá ze dvou různých licencí, open source MIT licence pro framework a umbraco freeware licence, která pokrývá UI. - Není nainstalováno. - Dotčené soubory a složky - Další informace o nastavování oprávnění pro umbraco zde - Musíte udělit ASP.NET oprávnění měnit následující soubory/složky - Vaše nastavení oprávnění je téměř dokonalé!

    + Stiskněte Následující pro pokračování. ]]> + následující, pro pokračování konfiguračního průvodce]]> + Heslo výchozího uživatele musí být změněno!]]> + Výchozí uživatel byl deaktivován, nebo nemá přístup k umbracu!

    Netřeba nic dalšího dělat. Klikněte na Následující pro pokračování.]]> + Heslo výchozího uživatele bylo úspěšně změněno od doby instalace!

    Netřeba nic dalšího dělat. Klikněte na Následující pro pokračování.]]> + Heslo je změněno! + Mějte skvělý start, sledujte naše uváděcí videa + Kliknutím na tlačítko následující (nebo modifikováním umbracoConfigurationStatus v souboru web.config) přijímáte licenci tohoto software tak, jak je uvedena v poli níže. Upozorňujeme, že tato distribuce Umbraca se skládá ze dvou různých licencí, open source MIT licence pro framework a umbraco freeware licence, která pokrývá UI. + Není nainstalováno. + Dotčené soubory a složky + Další informace o nastavování oprávnění pro umbraco zde + Musíte udělit ASP.NET oprávnění měnit následující soubory/složky + Vaše nastavení oprávnění je téměř dokonalé!

    Můžete provozovat umbraco bez potíží, ale nebudete smět instalovat balíčky, které jsou doporučené pro plné využívání všech možností umbraca.]]>
    - Jak to vyřešit - Klikněte zde, chcete-li číst textovou verzi - výukové video o nastavovaní oprávnění pro složky umbraca, nebo si přečtěte textovou verzi.]]> - Vaše nastavení oprávnění může být problém! + Jak to vyřešit + Klikněte zde, chcete-li číst textovou verzi + výukové video o nastavovaní oprávnění pro složky umbraca, nebo si přečtěte textovou verzi.]]> + Vaše nastavení oprávnění může být problém!

    Můžete provozovat umbraco bez potíží, ale nebudete smět vytvářet složky a instalovat balíčky, které jsou doporučené pro plné využívání všech možností umbraca.]]>
    - Vaše nastavení oprívnění není připraveno pro umbraco! + Vaše nastavení oprívnění není připraveno pro umbraco!

    Abyste mohli umbraco provozovat, budete muset aktualizovat Vaše nastavení oprávnění.]]>
    - Vaše nastavení oprávnění je dokonalé!

    + Vaše nastavení oprávnění je dokonalé!

    Jste připraveni provozovat umbraco a instalovat balíčky!]]>
    - Řešení potíží se složkami - Následujte tento odkaz pro další informace o potížích s ASP.NET a vytvářením složek. - Nastavování oprávnění pro složky - Řešení potíží se složkami + Následujte tento odkaz pro další informace o potížích s ASP.NET a vytvářením složek. + Nastavování oprávnění pro složky + - Chci začít od nuly - Chci začít od nuly + zjistěte jak) + (zjistěte jak) Stále se můžete později rozhodnout nainstalovat Runway. Za tím účelem navštivte Vývojářskou sekci a zvolte Balíčky. ]]> - Právě jste vytvořili čistou platformu Umbraco. Co chcete dělat dále? - Runway je nainstalován - Právě jste vytvořili čistou platformu Umbraco. Co chcete dělat dále? + Runway je nainstalován + Toto je náš seznam doporučených modulů, vyberte ty, které chcete nainstalovat, nebo si prohlédněte úplný seznam modulů ]]> - Doporučeno pouze pro zkušené uživatele - Chci začít s jednoduchým webem - Doporučeno pouze pro zkušené uživatele + Chci začít s jednoduchým webem + "Runway" je jednoduchý web poskytující některé základní typy dokumentů a šablon. Instalátor pro Vás může Runway nainstalovat automaticky a Vy ho pak můžete jednoduše editovat, rozšířit anebo úplně odstranit. Není nezbytný a můžete bez problému provozovat Umbraco bez něj. Runway nicméně nabízí jednoduché základy založené na nejlepších praktikách tak, abyste mohli začít rychleji, než kdykoliv jindy. Rozhodnete-li se Runway si nainstalovat, můžete si volitelně vybrat základní stavební bloky zvané Moduly Runway a stránky Runway si tak vylepšit.

    @@ -886,62 +885,62 @@ Volitelné moduly: Horní navigace, Mapa webu, Kontakt, Galerie. ]]>
    - Co je Runway - Krok 1/5: Přijetí licence - Krok 2/5: Konfigurace databáze - Krok 3/5: Ověřování oprávnění k souborům - Krok 4/5: Kontrola zabezpečení umbraca - Krok 5/5: Umbraco je připraveno a můžete začít - Děkujeme, že jeste si vybrali umbraco - Prohlédněte si svůj nový web + Co je Runway + Krok 1/5: Přijetí licence + Krok 2/5: Konfigurace databáze + Krok 3/5: Ověřování oprávnění k souborům + Krok 4/5: Kontrola zabezpečení umbraca + Krok 5/5: Umbraco je připraveno a můžete začít + Děkujeme, že jeste si vybrali umbraco + Prohlédněte si svůj nový web Nainstalovali jste Runway, tak proč se nepodívat, jak Váš nový web vypadá.]]> - Další pomoc a informace + Další pomoc a informace Abyste získali pomoc od naší oceňované komunity, projděte si dokumentaci, nebo si pusťte některá videa zdarma o tom, jak vytvořit jednoduchý web, jak používat balíčky a rychlý úvod do terminologie umbraca]]> - Umbraco %0% je nainstalováno a připraveno k použití - soubor /web.config a upravit klíč AppSetting umbracoConfigurationStatus dole na hodnotu '%0%'.]]> - ihned začít kliknutím na tlačítko "Spustit Umbraco" níže.
    Jestliže je pro Vás umbraco nové, + Umbraco %0% je nainstalováno a připraveno k použití + soubor /web.config a upravit klíč AppSetting umbracoConfigurationStatus dole na hodnotu '%0%'.]]> + ihned začít kliknutím na tlačítko "Spustit Umbraco" níže.
    Jestliže je pro Vás umbraco nové, spoustu zdrojů naleznete na naších stránkách "začínáme".]]>
    - Spustit Umbraco + Spustit Umbraco Chcete-li spravovat Váš web, jednoduše přejděte do administrace umbraca a začněte přidávat obsah, upravovat šablony a stylopisy, nebo přidávat nové funkce]]> - Připojení k databázi selhalo. - Umbraco verze 3 - Umbraco verze 4 - Shlédnout - umbraca %0% jako čisté instalace nebo povýšením z 3.0. + Připojení k databázi selhalo. + Umbraco verze 3 + Umbraco verze 4 + Shlédnout + umbraca %0% jako čisté instalace nebo povýšením z 3.0.

    Stiskněte "následující" pro spuštění průvodce.]]>
    - - - Kód jazyka - Název jazyka - - - Byli jste nečinní a odhlášení proběhne automaticky za - Obnovte nyní pro uložení práce - - - Šťastnou super neděli - Šťastné šílené pondělí - Šťastné husté úterý - Šťastnou překrásnou středu - Šťastný bouřlivý čtvrtek - Šťastný bláznivý pátek - Šťastnou kočkobotu - přihlašte se níže - Přihlásit se pomocí - Relace vypršela - © 2001 - %0%
    umbraco.org

    ]]>
    - Zapomenuté heslo? - Na uvedenou adresu bude zaslán e-mail s odkazem pro obnovení hesla - Pokud odpovídá našim záznamům, bude na zadanou adresu zaslán e-mail s pokyny k obnovení hesla - Zobrazit heslo - Skrýt heslo - Vrátit se na přihlašovací obrazovku - Zadejte nové heslo - Vaše heslo bylo aktualizováno - Odkaz, na který jste klikli, je neplatný nebo jeho platnost vypršela - Umbraco: Resetování hesla - + + Kód jazyka + Název jazyka + + + Byli jste nečinní a odhlášení proběhne automaticky za + Obnovte nyní pro uložení práce + + + Šťastnou super neděli + Šťastné šílené pondělí + Šťastné husté úterý + Šťastnou překrásnou středu + Šťastný bouřlivý čtvrtek + Šťastný bláznivý pátek + Šťastnou kočkobotu + přihlašte se níže + Přihlásit se pomocí + Relace vypršela + © 2001 - %0%
    umbraco.org

    ]]>
    + Zapomenuté heslo? + Na uvedenou adresu bude zaslán e-mail s odkazem pro obnovení hesla + Pokud odpovídá našim záznamům, bude na zadanou adresu zaslán e-mail s pokyny k obnovení hesla + Zobrazit heslo + Skrýt heslo + Vrátit se na přihlašovací obrazovku + Zadejte nové heslo + Vaše heslo bylo aktualizováno + Odkaz, na který jste klikli, je neplatný nebo jeho platnost vypršela + Umbraco: Resetování hesla + @@ -1022,30 +1021,30 @@ ]]> - - - Ovládací panel - Sekce - Obsah - - - Vyberte stránku výše... - %0% byl zkopírován do %1% - Níže vyberte, kam má být dokument %0% zkopírován - %0% byl přesunut do %1% - Níže vyberte, kam má být dokument %0% přesunut - byl vybrán jako kořen Vašeho nového obsahu, klikněte na 'ok' níže. - Ještě nebyl vybrán uzel, vyberte, prosím, uzel ze seznamu výše, než stisknete 'ok' - Aktuální uzel není povolen pod vybraným uzlem kvůli jeho typu - Aktuální uzel nemůže být přesunut do jedné ze svých podstránek - Aktuální uzel nemůže být v kořeni - Operace není povolena, protože máte nedostatečná práva pro 1 nebo více podřizených dokumentů. - Vztáhněte kopírované položky k originálu - - - Upravte vaše oznámení pro %0% - Nastavení oznámení bylo uloženo pro - + + Ovládací panel + Sekce + Obsah + + + Vyberte stránku výše... + %0% byl zkopírován do %1% + Níže vyberte, kam má být dokument %0% zkopírován + %0% byl přesunut do %1% + Níže vyberte, kam má být dokument %0% přesunut + byl vybrán jako kořen Vašeho nového obsahu, klikněte na 'ok' níže. + Ještě nebyl vybrán uzel, vyberte, prosím, uzel ze seznamu výše, než stisknete 'ok' + Aktuální uzel není povolen pod vybraným uzlem kvůli jeho typu + Aktuální uzel nemůže být přesunut do jedné ze svých podstránek + Aktuální uzel nemůže být v kořeni + Operace není povolena, protože máte nedostatečná práva pro 1 nebo více podřizených dokumentů. + Vztáhněte kopírované položky k originálu + + + Upravte vaše oznámení pro %0% + Nastavení oznámení bylo uloženo pro + - Následující jazyky byly změněny %0% - Ahoj %0%

    + Následující jazyky byly změněny %0% + Ahoj %0%

    Toto je automatická zpráva informující Vás, že úloha '%1%' byla provedena na stránce '%2%' @@ -1086,623 +1085,623 @@

    Mějte hezký den!

    Zdraví umbraco robot

    ]]>
    - Byly změněny následující jazyky:

    + Byly změněny následující jazyky:

    %0% ]]>
    - [%0%] Upozornění o %1% na %2% - Upozornění - - - Akce - Vytvořeno - Vytvořit balíček - [%0%] Upozornění o %1% na %2% + Upozornění + + + Akce + Vytvořeno + Vytvořit balíček + a výběrem balíčku. Balíčky umbraco mají obvykle přípony ".umb" nebo ".zip". ]]> - Tím se balíček odstraní - Přetáhněte sem pro nahrání - Zahrnout všechny podřízené uzly - nebo kliknutím sem vyberte soubor balíčku - Nahrát balíček - Nainstalujte místní balíček výběrem ze svého počítače. Instalujte pouze balíčky ze zdrojů, které znáte a kterým důvěřujete - Nahrát další balíček - Zrušit a nahrát další balíček - Přijímám - podmínky použití - Cesta k souboru - Absolutní cesta k souboru (ie: /bin/umbraco.bin) - Nainstalováno - Nainstalované balíčky - Instalovat místní - Dokončit - Tento balíček nemá žádné zobrazení konfigurace - Zatím nebyly vytvořeny žádné balíčky - Nemáte nainstalované žádné balíčky - Balíčky v pravém horním rohu obrazovky.]]> - Akce balíčku - Web autora - Obsah balíčku - Soubory balíčku - URL ikony - Nainstalovat balíček - Licence - URL licence - Vlastnosti balíčku - Hledat balíčky - Výsledky pro - Nemohli jsme nic najít - Zkuste prosím vyhledat jiný balíček nebo procházet jednotlivé kategorie - Oblíbené - Nové - - karma body - Informace - Vlastník - Přispěvatelé - Vytvořeno - Aktuální verze - .NET verze - Počet stažení - Počet lajků - kompatibilita - Tento balíček je kompatibilní s následujícími verzemi Umbraco, jak ohlásili členové komunity. Plnou kompatibilitu nelze zaručit u verzí hlášených pod 100% - Externí zdroje - Autor - Dokumentace - Meta data balíčku - Název balíčku - Balíček neobsahuje žádné položky -
    + Tím se balíček odstraní + Přetáhněte sem pro nahrání + Zahrnout všechny podřízené uzly + nebo kliknutím sem vyberte soubor balíčku + Nahrát balíček + Nainstalujte místní balíček výběrem ze svého počítače. Instalujte pouze balíčky ze zdrojů, které znáte a kterým důvěřujete + Nahrát další balíček + Zrušit a nahrát další balíček + Přijímám + podmínky použití + Cesta k souboru + Absolutní cesta k souboru (ie: /bin/umbraco.bin) + Nainstalováno + Nainstalované balíčky + Instalovat místní + Dokončit + Tento balíček nemá žádné zobrazení konfigurace + Zatím nebyly vytvořeny žádné balíčky + Nemáte nainstalované žádné balíčky + Balíčky v pravém horním rohu obrazovky.]]> + Akce balíčku + Web autora + Obsah balíčku + Soubory balíčku + URL ikony + Nainstalovat balíček + Licence + URL licence + Vlastnosti balíčku + Hledat balíčky + Výsledky pro + Nemohli jsme nic najít + Zkuste prosím vyhledat jiný balíček nebo procházet jednotlivé kategorie + Oblíbené + Nové + + karma body + Informace + Vlastník + Přispěvatelé + Vytvořeno + Aktuální verze + .NET verze + Počet stažení + Počet lajků + kompatibilita + Tento balíček je kompatibilní s následujícími verzemi Umbraco, jak ohlásili členové komunity. Plnou kompatibilitu nelze zaručit u verzí hlášených pod 100% + Externí zdroje + Autor + Dokumentace + Meta data balíčku + Název balíčku + Balíček neobsahuje žádné položky +
    Můžete jej ze systému bezpečně odstranit kliknutím na "odebrat balíček" níže.]]>
    - Možnosti balíčku - Čti mě balíčku - Úložiště balíčku - Potvrdit odinstalování - Balíček byl odinstalován - Balíček byl úspěšně odinstalován - Odinstalovat balíček - + Možnosti balíčku + Čti mě balíčku + Úložiště balíčku + Potvrdit odinstalování + Balíček byl odinstalován + Balíček byl úspěšně odinstalován + Odinstalovat balíček + Upozornění: všechny dokumenty, media atd. závislé na položkách, které odstraníte, přestanou pracovat a mohou vést k nestabilitě systému, takže odinstalovávejte opatrně. Jste-li na pochybách, kontaktujte autora balíčku.]]> - Verze balíčku - Upgradování z verze - Balíček je již nainstalován - Tento balíček nelze nainstalovat, vyžaduje minimální verzi Umbraco - Odinstalovávám... - Stahuji... - Importuji... - Instaluji... - Restartuji, prosím čekejte... - Vše je hotovo, váš prohlížeč se nyní obnoví, prosím čekejte... - Klepnutím na tlačítko „Dokončit“ dokončete instalaci a znovu načtěte stránku. - Nahrávám balíček... - - - Vložit s úplným formatováním (nedoporučeno) - Text, který chcete vložit, obsahuje speciální znaky nebo formatování. Toto může být způsobeno kopirováním textu z Microsoft Wordu. Umbraco může odstranit speciální znaky nebo formatování, takže vložený obsah bude pro web vhodnější. - Vložit jako čistý text bez jakéhokoliv formátování - Vložit, ale odstranit formátování (doporučeno) - - - Ochrana prostřednictvím rolí - použijte členské skupiny umbraca.]]> - Musíte vytvořit členskou skupinu před tím, než můžete použít autentizaci prostřednictvím rolí - Chybová stránka - Použita, když jsou lidé přihlášení, ale nemají přístup - Vyberte, jak omezit přístup k této stránce - %0% je nyní chráněna - Ochrana odebrána z %0% - Přihlašovací stránka - Vyberte stránku, která obsahuje přihlašovací formulář - Odstranit ochranu - %0%?]]> - Vyberte stránky, které obsahují přihlašovací formulář a chybová hlášení - Vyberte role, které mají přístup k této stránce - %0%]]> - %0%]]> - Ochrana konkrétních členů - Pokud si přejete udělit přístup konkrétním členům - Nastavte přihlašovací jmého a heslo pro tuto stránku - Jednouživatelská ochrana - Jestliže chcete nastavit jenom jednoduchou ochranu prostřednictvím uživatelského jména a hesla - - - Nedostatečná uživatelská oprávnění k publikování všech potomků - Verze balíčku + Upgradování z verze + Balíček je již nainstalován + Tento balíček nelze nainstalovat, vyžaduje minimální verzi Umbraco + Odinstalovávám... + Stahuji... + Importuji... + Instaluji... + Restartuji, prosím čekejte... + Vše je hotovo, váš prohlížeč se nyní obnoví, prosím čekejte... + Klepnutím na tlačítko „Dokončit“ dokončete instalaci a znovu načtěte stránku. + Nahrávám balíček... + + + Vložit s úplným formatováním (nedoporučeno) + Text, který chcete vložit, obsahuje speciální znaky nebo formatování. Toto může být způsobeno kopirováním textu z Microsoft Wordu. Umbraco může odstranit speciální znaky nebo formatování, takže vložený obsah bude pro web vhodnější. + Vložit jako čistý text bez jakéhokoliv formátování + Vložit, ale odstranit formátování (doporučeno) + + + Ochrana prostřednictvím rolí + použijte členské skupiny umbraca.]]> + Musíte vytvořit členskou skupinu před tím, než můžete použít autentizaci prostřednictvím rolí + Chybová stránka + Použita, když jsou lidé přihlášení, ale nemají přístup + Vyberte, jak omezit přístup k této stránce + %0% je nyní chráněna + Ochrana odebrána z %0% + Přihlašovací stránka + Vyberte stránku, která obsahuje přihlašovací formulář + Odstranit ochranu + %0%?]]> + Vyberte stránky, které obsahují přihlašovací formulář a chybová hlášení + Vyberte role, které mají přístup k této stránce + %0%]]> + %0%]]> + Ochrana konkrétních členů + Pokud si přejete udělit přístup konkrétním členům + Nastavte přihlašovací jmého a heslo pro tuto stránku + Jednouživatelská ochrana + Jestliže chcete nastavit jenom jednoduchou ochranu prostřednictvím uživatelského jména a hesla + + + Nedostatečná uživatelská oprávnění k publikování všech potomků + - - - - - - - - Ověření se nezdařilo pro požadovaný jazyk '% 0%'. Tento jazyk byl uložen, ale nezveřejněn. - Probíhá publikování - počkejte, prosím... - %0% ze %1% stránek bylo publikováno... - %0% byla publikována - %0% a podstránky byly publikovány - Publikovat %0% a všechny její podstránky - ok pro publikování %0% a tedy zveřejnění jejího obsahu.

    + + + Ověření se nezdařilo pro požadovaný jazyk '% 0%'. Tento jazyk byl uložen, ale nezveřejněn. + Probíhá publikování - počkejte, prosím... + %0% ze %1% stránek bylo publikováno... + %0% byla publikována + %0% a podstránky byly publikovány + Publikovat %0% a všechny její podstránky + ok pro publikování %0% a tedy zveřejnění jejího obsahu.

    Můžete publikovat tuto stránku a všechny její podstránky zatrhnutím publikovat všchny podstránky níže. ]]>
    - Zahrnout nepublikované podřízené stránky - - - Nenakonfigurovali jste žádné schválené barvy - - - Můžete vybrat pouze položky typu (typů): %0% - Vybrali jste aktuálně odstraněnou položku obsahu nebo položku v koši - Vybrali jste aktuálně odstraněné položky obsahu nebo položky v koši - - - Smazaná položka - Vybrali jste aktuálně odstraněnou položku média nebo položku v koši - Vybrali jste aktuálně odstraněné položky médií nebo položky médií v koši - V koši - - - zadejte externí odkaz - zvolte interní stránku - Nadpis - Odkaz - Otevřít v novém okně - zadejte titulek - Zadejte odkaz - - Přidat vnější odkaz - Přidat vnitřní odkaz - Přidat - Vnitřní stránka - URL - Posunout dolů - Posunout nahoru - Odebrat odkaz - - - Zrušit oříznutí - Uložit oříznutí - Přidat nové oříznutí - Hotovo - Vrátit změny - - - Vyberte verzi, kterou chcete porovnat s aktuální verzí - Současná verze - Červený text nebude ve vybrané verzi zobrazen, zelený znamená přidaný].]]> - Dokument byl vrácen na starší verzi - Tohle zobrazuje vybranou verzi jako html, jestliže chcete vidět rozdíly mezi 2 verzemi najednou, použijte rozdílové zobrazení - Vrátit starší verzi - Vybrat verzi - Zobrazení - - - Editovat skriptovací soubor - - - Obsah - Formuláře - Média - Členové - Balíčky - Nastavení - Překlad - Uživatelé - - Domovník - Kurýr - Vývojář - Průvodce nastavením Umbraca - Zpravodaje - Statistiky - Nápověda - - - Příručky - Nejlepší videopříručky Umbraco - Navštívit our.umbraco.com - Navštívit umbraco.tv - - - Výchozí šablona - Pro importování typu dokumentu vyhledejte soubor ".udt" ve svém počítači tak, že kliknete na tlačítko "Prohledat" a pak kliknete na "Import" (na následující obrazovce budete vyzváni k potvrzení) - Název nové záložky - Typ uzlu - Typ - Stylopis - Skript - Záložka - Název záložky - Záložky - Nadřazený typ obsahu povolen - Tento typ obsahu používá - jako nadřazený typ obsahu. Záložky z nadřazených typů obsahu nejsou zobrazeny a mohou byt editovány pouze na nadřazených typech obsahu samotných - Na této záložce nejsou definovány žádné vlastnosti. Pro vytvoření nové vlastnosti klikněte na odkaz "přidat novou vlastnost" nahoře. - Vytvořit odpovídající šablonu - Přidat ikonu - - - Řazení - Datum vytvoření - Třídění bylo ukončeno. - Abyste nastavili, jak mají být položky seřazeny, přetáhněte jednotlivé z nich nahoru či dolů. Anebo klikněte na hlavičku sloupce pro setřídění celé kolekce - - Tato položka nemá vnořené položky k seřazení - - - Validace - Před uložením položky je nutné opravit chyby - Chyba - Uloženo - Nedostatečná uživatelská oprávnění, operace nemohla být dokončena - Zrušeno - Operace byla zrušena doplňkem třetí strany - Typ vlastnosti už existuje - Typ vlastnosti vytvořen - Datový typ: %1%]]> - Typ vlastnosti odstraněn - Typ vlastnosti uložen - Záložka vytvořena - Záložka odstraněna - Záložka s id: %0% odstraněna - Stylopis nebyl uložen - Stylopis byl uložen - Stylopis byl uložen bez chyb - Datový typ byl uložen - Položka slovníku byla uložena - Obsah byl publikován - a je viditelný na webu - %0% dokumentů zveřejněných a viditelných na webu - %0% zveřejněných a viditelných na webu - %0% dokumentů zveřejněných pro jazyky %1% a viditelných na webu - Obsah byl uložen - Nezapomeňte na publikování, aby se změny projevily - Načasování publikování bylo aktualizováno - %0% uloženo - Odeslat ke schválení - Změny byly odeslány ke schválení - %0% změn bylo odesláno ke schválení - Médium bylo uloženo - Médium bylo uloženo bez chyb - Člen byl uložen - Skupina členů byla uložena - Vlastnost stylopisu byla uložena - Stylopis byl uložen - Šablona byla uložena - Chyba při ukládání uživatele (zkontrolujte log) - Uživatel byl uložen - Typ uživatele byl uložen - Skupina uživatelů byla uložena - Jazyky a názvy hostitelů byly uloženy - Při ukládání jazyků a názvů hostitelů došlo k chybě - Soubor nebyl uložen - soubor nemohl být uložen. Zkontrolujte, prosím, oprávnění k souboru - Soubor byl uložen - Soubor byl uložen bez chyb - Jazyk byl uložen - Typ média byl uložen - Typ člena byl uložen - Skupina členů byla uložena - Šablona nebyla uložena - Ujistěte se, prosím, že nemáte 2 šablony se stejným aliasem - Šablona byla uložena - Šablona byla uložena bez chyb! - Publikování obsahu bylo zrušeno - Varianta obsahu %0% nebyla publikována - Povinný jazyk '%0%' nebyl publikován. Všechny jazyky pro tuto položku obsahu nejsou nyní publikovány. - Částečný pohled byl uložen - Částečný pohled byl uložen bez chyb! - Částečný pohled nebyl uložen - Při ukládání souboru došlo k chybě. - Oprávnění byla uložena pro - Smazáno %0% skupin uživatelů - %0% bylo smazáno - Povoleno %0% uživatelů - Zakázáno %0% uživatelů - %0% je nyní povoleno - %0% je nyní zakázáno - Skupiny uživatelů byly nastaveny - Odemčeno %0% uživatelů - %0% je nyný odemčeno - Člen byl exportován do souboru - Při exportu člena došlo k chybě - Uživatel %0% byl smazán - Pozvat uživatele - Pozvánka byla znovu odeslána na %0% - Dokument nelze publikovat, protože %0% není publikována - Ověření pro jazyk '%0%' se nezdařilo - Typ dokumentu byl exportován do souboru - Při exportu typu dokumentu došlo k chybě - Datum vydání nemůže být v minulosti - Nelze naplánovat publikování dokumentu, protože %0% není publikována - Dokument nelze naplánovat na publikování, protože „%0%“ má datum zveřejnění později než nepovinný jazyk - Datum vypršení platnosti nemůže být v minulosti - Datum vypršení nemůže být před datem vydání - - Publikování bylo zrušeno doplňkem třetí strany - Publikování se nezdařilo, protože nadřazená stránka není publikována - - - Přidat styl - Upravit styl - Styly Rich Text editoru - Definujte styly, které by měly být k dispozici v editoru formátovaného textu pro tuto šablonu stylů - Editovat stylopis - Editovat vlastnost stylopisu - Název, který identifikuje vlastnost stylu v editoru formátovaného textu - Náhled - Jak bude text vypadat v Rich Text editoru. - CSS identifikátor nebo třída - Používá syntaxi CSS, např. "h1" nebo ".redHeader" - Styly - CSS, který by měl být použit v editoru RTF, např. "color:red;" - Kód - Rich Text editor - - Používá CSS syntaxi např.: h1, .redHeader, .blueTex - - - Nepodařilo se odstranit šablonu s ID %0% - Editovat šablonu - Sekce - Vložit obsahovou oblast - Vložit zástupce obsahové oblasti - Vložit - Vyberte, co chcete vložit do své šablony - Vložit položku slovníku - Položka slovníku je zástupný symbol pro překladatelný text, což usnadňuje vytváření návrhů pro vícejazyčné webové stránky. - Vložit makro - - Makro je konfigurovatelná součást, která je skvělá pro opakovaně použitelné části návrhu, kde potřebujete předat parametry, jako jsou galerie, formuláře a seznamy. - - Vložit pole stránky umbraco - Zobrazuje hodnotu pojmenovaného pole z aktuální stránky s možnostmi upravit hodnotu nebo alternativní hodnoty. - Částečná šablona - - Částečná šablona je samostatný soubor šablony, který lze vykreslit uvnitř jiné šablony. Je to skvělé pro opakované použití nebo pro oddělení složitých šablon. - - Nadřazená šablona - Žádný master - Vykreslit podřízenou šablonu - Zahrnout nepublikované podřízené stránky + + + Nenakonfigurovali jste žádné schválené barvy + + + Můžete vybrat pouze položky typu (typů): %0% + Vybrali jste aktuálně odstraněnou položku obsahu nebo položku v koši + Vybrali jste aktuálně odstraněné položky obsahu nebo položky v koši + + + Smazaná položka + Vybrali jste aktuálně odstraněnou položku média nebo položku v koši + Vybrali jste aktuálně odstraněné položky médií nebo položky médií v koši + V koši + + + zadejte externí odkaz + zvolte interní stránku + Nadpis + Odkaz + Otevřít v novém okně + zadejte titulek + Zadejte odkaz + + Přidat vnější odkaz + Přidat vnitřní odkaz + Přidat + Vnitřní stránka + URL + Posunout dolů + Posunout nahoru + Odebrat odkaz + + + Zrušit oříznutí + Uložit oříznutí + Přidat nové oříznutí + Hotovo + Vrátit změny + + + Vyberte verzi, kterou chcete porovnat s aktuální verzí + Současná verze + Červený text nebude ve vybrané verzi zobrazen, zelený znamená přidaný].]]> + Dokument byl vrácen na starší verzi + Tohle zobrazuje vybranou verzi jako html, jestliže chcete vidět rozdíly mezi 2 verzemi najednou, použijte rozdílové zobrazení + Vrátit starší verzi + Vybrat verzi + Zobrazení + + + Editovat skriptovací soubor + + + Obsah + Formuláře + Média + Členové + Balíčky + Nastavení + Překlad + Uživatelé + + Domovník + Kurýr + Vývojář + Průvodce nastavením Umbraca + Zpravodaje + Statistiky + Nápověda + + + Příručky + Nejlepší videopříručky Umbraco + Navštívit our.umbraco.com + Navštívit umbraco.tv + + + Výchozí šablona + Pro importování typu dokumentu vyhledejte soubor ".udt" ve svém počítači tak, že kliknete na tlačítko "Prohledat" a pak kliknete na "Import" (na následující obrazovce budete vyzváni k potvrzení) + Název nové záložky + Typ uzlu + Typ + Stylopis + Skript + Záložka + Název záložky + Záložky + Nadřazený typ obsahu povolen + Tento typ obsahu používá + jako nadřazený typ obsahu. Záložky z nadřazených typů obsahu nejsou zobrazeny a mohou byt editovány pouze na nadřazených typech obsahu samotných + Na této záložce nejsou definovány žádné vlastnosti. Pro vytvoření nové vlastnosti klikněte na odkaz "přidat novou vlastnost" nahoře. + Vytvořit odpovídající šablonu + Přidat ikonu + + + Řazení + Datum vytvoření + Třídění bylo ukončeno. + Abyste nastavili, jak mají být položky seřazeny, přetáhněte jednotlivé z nich nahoru či dolů. Anebo klikněte na hlavičku sloupce pro setřídění celé kolekce + + Tato položka nemá vnořené položky k seřazení + + + Validace + Před uložením položky je nutné opravit chyby + Chyba + Uloženo + Nedostatečná uživatelská oprávnění, operace nemohla být dokončena + Zrušeno + Operace byla zrušena doplňkem třetí strany + Typ vlastnosti už existuje + Typ vlastnosti vytvořen + Datový typ: %1%]]> + Typ vlastnosti odstraněn + Typ vlastnosti uložen + Záložka vytvořena + Záložka odstraněna + Záložka s id: %0% odstraněna + Stylopis nebyl uložen + Stylopis byl uložen + Stylopis byl uložen bez chyb + Datový typ byl uložen + Položka slovníku byla uložena + Obsah byl publikován + a je viditelný na webu + %0% dokumentů zveřejněných a viditelných na webu + %0% zveřejněných a viditelných na webu + %0% dokumentů zveřejněných pro jazyky %1% a viditelných na webu + Obsah byl uložen + Nezapomeňte na publikování, aby se změny projevily + Načasování publikování bylo aktualizováno + %0% uloženo + Odeslat ke schválení + Změny byly odeslány ke schválení + %0% změn bylo odesláno ke schválení + Médium bylo uloženo + Médium bylo uloženo bez chyb + Člen byl uložen + Skupina členů byla uložena + Vlastnost stylopisu byla uložena + Stylopis byl uložen + Šablona byla uložena + Chyba při ukládání uživatele (zkontrolujte log) + Uživatel byl uložen + Typ uživatele byl uložen + Skupina uživatelů byla uložena + Jazyky a názvy hostitelů byly uloženy + Při ukládání jazyků a názvů hostitelů došlo k chybě + Soubor nebyl uložen + soubor nemohl být uložen. Zkontrolujte, prosím, oprávnění k souboru + Soubor byl uložen + Soubor byl uložen bez chyb + Jazyk byl uložen + Typ média byl uložen + Typ člena byl uložen + Skupina členů byla uložena + Šablona nebyla uložena + Ujistěte se, prosím, že nemáte 2 šablony se stejným aliasem + Šablona byla uložena + Šablona byla uložena bez chyb! + Publikování obsahu bylo zrušeno + Varianta obsahu %0% nebyla publikována + Povinný jazyk '%0%' nebyl publikován. Všechny jazyky pro tuto položku obsahu nejsou nyní publikovány. + Částečný pohled byl uložen + Částečný pohled byl uložen bez chyb! + Částečný pohled nebyl uložen + Při ukládání souboru došlo k chybě. + Oprávnění byla uložena pro + Smazáno %0% skupin uživatelů + %0% bylo smazáno + Povoleno %0% uživatelů + Zakázáno %0% uživatelů + %0% je nyní povoleno + %0% je nyní zakázáno + Skupiny uživatelů byly nastaveny + Odemčeno %0% uživatelů + %0% je nyný odemčeno + Člen byl exportován do souboru + Při exportu člena došlo k chybě + Uživatel %0% byl smazán + Pozvat uživatele + Pozvánka byla znovu odeslána na %0% + Dokument nelze publikovat, protože %0% není publikována + Ověření pro jazyk '%0%' se nezdařilo + Typ dokumentu byl exportován do souboru + Při exportu typu dokumentu došlo k chybě + Datum vydání nemůže být v minulosti + Nelze naplánovat publikování dokumentu, protože %0% není publikována + Dokument nelze naplánovat na publikování, protože „%0%“ má datum zveřejnění později než nepovinný jazyk + Datum vypršení platnosti nemůže být v minulosti + Datum vypršení nemůže být před datem vydání + + Publikování bylo zrušeno doplňkem třetí strany + Publikování se nezdařilo, protože nadřazená stránka není publikována + + + Přidat styl + Upravit styl + Styly Rich Text editoru + Definujte styly, které by měly být k dispozici v editoru formátovaného textu pro tuto šablonu stylů + Editovat stylopis + Editovat vlastnost stylopisu + Název, který identifikuje vlastnost stylu v editoru formátovaného textu + Náhled + Jak bude text vypadat v Rich Text editoru. + CSS identifikátor nebo třída + Používá syntaxi CSS, např. "h1" nebo ".redHeader" + Styly + CSS, který by měl být použit v editoru RTF, např. "color:red;" + Kód + Rich Text editor + + Používá CSS syntaxi např.: h1, .redHeader, .blueTex + + + Nepodařilo se odstranit šablonu s ID %0% + Editovat šablonu + Sekce + Vložit obsahovou oblast + Vložit zástupce obsahové oblasti + Vložit + Vyberte, co chcete vložit do své šablony + Vložit položku slovníku + Položka slovníku je zástupný symbol pro překladatelný text, což usnadňuje vytváření návrhů pro vícejazyčné webové stránky. + Vložit makro + + Makro je konfigurovatelná součást, která je skvělá pro opakovaně použitelné části návrhu, kde potřebujete předat parametry, jako jsou galerie, formuláře a seznamy. + + Vložit pole stránky umbraco + Zobrazuje hodnotu pojmenovaného pole z aktuální stránky s možnostmi upravit hodnotu nebo alternativní hodnoty. + Částečná šablona + + Částečná šablona je samostatný soubor šablony, který lze vykreslit uvnitř jiné šablony. Je to skvělé pro opakované použití nebo pro oddělení složitých šablon. + + Nadřazená šablona + Žádný master + Vykreslit podřízenou šablonu + @RenderBody(). ]]> - Definujte pojmenovanou sekci - Definujte pojmenovanou sekci + @section {...}. Ta může být vykreslena v konkrétní oblasti nadřazené šablony pomocí @RenderSection. ]]> - Vykreslit pojmenovanou sekci - Vykreslit pojmenovanou sekci + @RenderSection(name). Tím se vykreslí oblast podřízené šablony, která je zabalena do odpovídající definice @section[name] {...}. ]]> - Název sekce - Sekce je povinná - Název sekce + Sekce je povinná + @section, jinak se zobrazí chyba. ]]> - Tvůrce dotazů - položky vráceny, do - zkopírovat do schránky - Chci - veškerý obsah - obsah typu "%0%" - z(e) - můj web - kde - a - je - není - před - před (včetně zvoleného datumu) - po - po (včetně zvoleného datumu) - rovná se - nerovná se - obsahuje - neobsahuje - větší než - větší nebo rovno - menší než - menší nebo rovno - Id - Název - Datum vytvoření - Datum poslední aktualizace - řadit podle - vzestupně - sestupně - Šablona - - Rychlá příručka k šablonovým značkám umbraca - - - Obrázek - Makro - Vybrat typ obsahu - Vybrat rozvržení - Přidat řádek - Přidat obsah - Zahodit obsah - Nastavení aplikováno - Tento obsah zde není povolen - Tento obsah je zde povolen - Klepněte pro vložení - Klepnutím vložíte obrázek - Titulek obrázku... - Zde pište... - Rozvržení mřížky - Rozvržení je celková pracovní oblast pro editor mřížky, obvykle potřebujete pouze jedno nebo dvě různá rozvržení - Přidat rozvržení mřížky - Upravte rozvržení nastavením šířky sloupců a přidáním dalších sekcí - Konfigurace řádků - Řádky jsou předdefinované buňky uspořádané vodorovně - Přidat konfiguraci řádku - Upravte řádek nastavením šířky buněk a přidáním dalších buněk - Sloupce - Celkový počet sloupců v rozvržení mřížky - Nastavení - Nakonfigurujte, jaká nastavení mohou editoři změnit - Styly - Nakonfigurujte, co mohou editoři stylů změnit - Povolit všechny editory - Povolit všechny konfigurace řádků - Maximální počet položek - Nechte prázdné nebo nastavte na 0 pro neomezené - Nastavit jako výchozí - Vyberat navíc - Zvolit výchozí - jsou přidány - Varování - Odstraňujete konfiguraci řádku - - Odstranění názvu konfigurace řádku povede ke ztrátě dat pro veškerý existující obsah založený na této konfiguraci. - - - - Složení - Skupina - Nepřidali jste žádné skupiny - Přidat skupinu - Zděděno od - Přidat vlastnost - Požadovaný popisek - Povolit zobrazení seznamu - Nakonfiguruje položku obsahu tak, aby zobrazovala seznam svých potomků a seznam potomků, které je možné prohledávat, potomci se nebudou zobrazovat ve stromu - Povolené šablony - Vyberte, kteří editoři šablon mohou používat obsah tohoto typu - Povolit jako root - Povolit editorům vytvářet obsah tohoto typu v kořenovém adresáři stromu obsahu. - Povolené typy podřízených uzlů - Povolit vytváření obsahu zadaných typů pod obsahem tohoto typu. - Vybrat podřízený uzel - Zdědí záložky a vlastnosti z existujícího typu dokumentu. Nové záložky budou přidány do aktuálního typu dokumentu nebo sloučeny, pokud existuje záložka se stejným názvem. - Tento typ obsahu se používá ve složení, a proto jej nelze poskládat. - Nejsou k dispozici žádné typy obsahu, které lze použít jako složení. - Odebráním složení odstraníte všechna související data vlastností. Jakmile uložíte typ dokumentu, již není cesta zpět. - Vytvořit nové - Použít existující - Nastavení editoru - Konfigurace - Ano, smazat - bylo přesunuto pod - bylo zkopírováno pod - Vybrat složku, kterou chcete přesunout - Vybrat složku, kterou chcete kopírovat - ve stromové struktuře níže - Všechny typy dokumentů - Všechny dokumenty - Všechny média - použití tohoto typu dokumentu bude trvale smazáno, prosím potvrďte, že je chcete také odstranit. - použití tohoto typu média bude trvale smazáno, potvrďte, že je chcete také odstranit. - použití tohoto typu člena bude trvale smazáno, potvrďte, že je chcete také odstranit - a všechny dokumenty používající tento typ - a všechny mediální položky používající tento typ - a všichni členové používající tento typ - Člen může upravovat - Povolit editaci této vlastnosti členem na jeho stránce profilu - Obsahuje citlivá data - Skrýt tuto hodnotu vlastnosti před editory obsahu, kteří nemají přístup k prohlížení citlivých informací - Zobrazit v profilu člena - Povolit zobrazení této vlastnosti na stránce profilu člena - záložka nemá žádné řazení - Kde se toto složení používá? - Toto složení se v současnosti používá ve složení následujících typů obsahu: - Povolit různé jazyky - Povolit editorům vytvářet obsah tohoto typu v různých jazycích. - Povolit různé jazyky - Typ prvku - Je typ prvku - Typ prvku je určen k použití například ve vnořeném obsahu, nikoli ve stromu. - Jakmile byl typ dokumentu použit k vytvoření jedné nebo více položek obsahu, nelze jej změnit na typ prvku. - To neplatí pro typ prvku - V této vlastnosti jste provedli změny. Opravdu je chcete zahodit? - - - Přidat jazyk - Povinný jazyk - Před publikováním uzlu je nutné vyplnit vlastnosti v tomto jazyce. - Výchozí jazyk - Web Umbraco může mít nastaven pouze jeden výchozí jazyk. - Přepnutí výchozího jazyka může mít za následek chybějící výchozí obsah. - Nahradit nepřeložený obsah za - Žádné nahrazení nepřeloženého jazyka - Chcete-li povolit automatické zobrazení vícejazyčného obsahu v jiném jazyce, pokud není v požadovaném jazyce přeložen, vyberte jej zde. - Nahrazujicí jazyk - žádný - - - Přidat parametr - Upravit parametr - Zadejte název makra - Parametry - Definujte parametry, které by měly být k dispozici při použití tohoto makra. - Vyberte soubor makra pro částečnou šablonu - - - Stavební modely - to může chvíli trvat, nebojte se - Generované modely - Modely nelze vygenerovat - Generování modelů selhalo, viz výjimka v logu Umbraca - - - Přidat záložní pole - Náhradní pole - Přidat výchozí hodnotu - Výchozí hodnota - Alternativní pole - Alternativní text - Velká a malá písmena - Kódování - Vybrat pole - Konvertovat - Ano, převést konce řádků - Nahrazuje nové řádky html tagem &lt;br&gt; - Vlastní pole - Ano, pouze datum - Formát a kódování - Formátovat jako datum - Naformátuje hodnotu jako datum nebo datum s časem podle aktivního jazyka - HTML kódování - Nahradí speciální znaky jejich HTML ekvivalentem. - Bude vloženo za hodnotou pole - Bude vloženo před hodnotou pole - Malá písmena - Upravit výstup - Nic - Ukázka výstupu - Vložit za polem - Vložit před polem - Rekurzivní - Ano, udělej to rekurzivní - Oddělovač - Standardní pole - Velká písmena - Kódování URL - Formátuje speciální znaky v URL adresách - Bude použito pouze pokud jsou pole nahoře prázdná - Toto pole bude použito pouze pokud je primární pole prázdné - Ano, s časem. Oddělovač: - - - Podrobnosti překladu - Stáhnout XML DTD - Pole - Zahrnout podstránky - Tvůrce dotazů + položky vráceny, do + zkopírovat do schránky + Chci + veškerý obsah + obsah typu "%0%" + z(e) + můj web + kde + a + je + není + před + před (včetně zvoleného datumu) + po + po (včetně zvoleného datumu) + rovná se + nerovná se + obsahuje + neobsahuje + větší než + větší nebo rovno + menší než + menší nebo rovno + Id + Název + Datum vytvoření + Datum poslední aktualizace + řadit podle + vzestupně + sestupně + Šablona + + Rychlá příručka k šablonovým značkám umbraca + + + Obrázek + Makro + Vybrat typ obsahu + Vybrat rozvržení + Přidat řádek + Přidat obsah + Zahodit obsah + Nastavení aplikováno + Tento obsah zde není povolen + Tento obsah je zde povolen + Klepněte pro vložení + Klepnutím vložíte obrázek + Titulek obrázku... + Zde pište... + Rozvržení mřížky + Rozvržení je celková pracovní oblast pro editor mřížky, obvykle potřebujete pouze jedno nebo dvě různá rozvržení + Přidat rozvržení mřížky + Upravte rozvržení nastavením šířky sloupců a přidáním dalších sekcí + Konfigurace řádků + Řádky jsou předdefinované buňky uspořádané vodorovně + Přidat konfiguraci řádku + Upravte řádek nastavením šířky buněk a přidáním dalších buněk + Sloupce + Celkový počet sloupců v rozvržení mřížky + Nastavení + Nakonfigurujte, jaká nastavení mohou editoři změnit + Styly + Nakonfigurujte, co mohou editoři stylů změnit + Povolit všechny editory + Povolit všechny konfigurace řádků + Maximální počet položek + Nechte prázdné nebo nastavte na 0 pro neomezené + Nastavit jako výchozí + Vyberat navíc + Zvolit výchozí + jsou přidány + Varování + Odstraňujete konfiguraci řádku + + Odstranění názvu konfigurace řádku povede ke ztrátě dat pro veškerý existující obsah založený na této konfiguraci. + + + + Složení + Skupina + Nepřidali jste žádné skupiny + Přidat skupinu + Zděděno od + Přidat vlastnost + Požadovaný popisek + Povolit zobrazení seznamu + Nakonfiguruje položku obsahu tak, aby zobrazovala seznam svých potomků a seznam potomků, které je možné prohledávat, potomci se nebudou zobrazovat ve stromu + Povolené šablony + Vyberte, kteří editoři šablon mohou používat obsah tohoto typu + Povolit jako root + Povolit editorům vytvářet obsah tohoto typu v kořenovém adresáři stromu obsahu. + Povolené typy podřízených uzlů + Povolit vytváření obsahu zadaných typů pod obsahem tohoto typu. + Vybrat podřízený uzel + Zdědí záložky a vlastnosti z existujícího typu dokumentu. Nové záložky budou přidány do aktuálního typu dokumentu nebo sloučeny, pokud existuje záložka se stejným názvem. + Tento typ obsahu se používá ve složení, a proto jej nelze poskládat. + Nejsou k dispozici žádné typy obsahu, které lze použít jako složení. + Odebráním složení odstraníte všechna související data vlastností. Jakmile uložíte typ dokumentu, již není cesta zpět. + Vytvořit nové + Použít existující + Nastavení editoru + Konfigurace + Ano, smazat + bylo přesunuto pod + bylo zkopírováno pod + Vybrat složku, kterou chcete přesunout + Vybrat složku, kterou chcete kopírovat + ve stromové struktuře níže + Všechny typy dokumentů + Všechny dokumenty + Všechny média + použití tohoto typu dokumentu bude trvale smazáno, prosím potvrďte, že je chcete také odstranit. + použití tohoto typu média bude trvale smazáno, potvrďte, že je chcete také odstranit. + použití tohoto typu člena bude trvale smazáno, potvrďte, že je chcete také odstranit + a všechny dokumenty používající tento typ + a všechny mediální položky používající tento typ + a všichni členové používající tento typ + Člen může upravovat + Povolit editaci této vlastnosti členem na jeho stránce profilu + Obsahuje citlivá data + Skrýt tuto hodnotu vlastnosti před editory obsahu, kteří nemají přístup k prohlížení citlivých informací + Zobrazit v profilu člena + Povolit zobrazení této vlastnosti na stránce profilu člena + záložka nemá žádné řazení + Kde se toto složení používá? + Toto složení se v současnosti používá ve složení následujících typů obsahu: + Povolit různé jazyky + Povolit editorům vytvářet obsah tohoto typu v různých jazycích. + Povolit různé jazyky + Typ prvku + Je typ prvku + Typ prvku je určen k použití například ve vnořeném obsahu, nikoli ve stromu. + Jakmile byl typ dokumentu použit k vytvoření jedné nebo více položek obsahu, nelze jej změnit na typ prvku. + To neplatí pro typ prvku + V této vlastnosti jste provedli změny. Opravdu je chcete zahodit? + + + Přidat jazyk + Povinný jazyk + Před publikováním uzlu je nutné vyplnit vlastnosti v tomto jazyce. + Výchozí jazyk + Web Umbraco může mít nastaven pouze jeden výchozí jazyk. + Přepnutí výchozího jazyka může mít za následek chybějící výchozí obsah. + Nahradit nepřeložený obsah za + Žádné nahrazení nepřeloženého jazyka + Chcete-li povolit automatické zobrazení vícejazyčného obsahu v jiném jazyce, pokud není v požadovaném jazyce přeložen, vyberte jej zde. + Nahrazujicí jazyk + žádný + + + Přidat parametr + Upravit parametr + Zadejte název makra + Parametry + Definujte parametry, které by měly být k dispozici při použití tohoto makra. + Vyberte soubor makra pro částečnou šablonu + + + Stavební modely + to může chvíli trvat, nebojte se + Generované modely + Modely nelze vygenerovat + Generování modelů selhalo, viz výjimka v logu Umbraca + + + Přidat záložní pole + Náhradní pole + Přidat výchozí hodnotu + Výchozí hodnota + Alternativní pole + Alternativní text + Velká a malá písmena + Kódování + Vybrat pole + Konvertovat + Ano, převést konce řádků + Nahrazuje nové řádky html tagem &lt;br&gt; + Vlastní pole + Ano, pouze datum + Formát a kódování + Formátovat jako datum + Naformátuje hodnotu jako datum nebo datum s časem podle aktivního jazyka + HTML kódování + Nahradí speciální znaky jejich HTML ekvivalentem. + Bude vloženo za hodnotou pole + Bude vloženo před hodnotou pole + Malá písmena + Upravit výstup + Nic + Ukázka výstupu + Vložit za polem + Vložit před polem + Rekurzivní + Ano, udělej to rekurzivní + Oddělovač + Standardní pole + Velká písmena + Kódování URL + Formátuje speciální znaky v URL adresách + Bude použito pouze pokud jsou pole nahoře prázdná + Toto pole bude použito pouze pokud je primární pole prázdné + Ano, s časem. Oddělovač: + + + Podrobnosti překladu + Stáhnout XML DTD + Pole + Zahrnout podstránky + - Žádní uživatelé překladatelé nebyli nalezeni. Vytvořte, prosím, překladatele před tím, než začnete posílat obsah k překladu - Stránka '%0%' byla poslána k překladu - Poslat stránku '%0%' k překladu - Slov celkem - Přeložit do - Překlad hotov. - Klikutím níže můžete vidět stránky, které jste právě přeložili. Jestliže je nalezena originální stránka, dostanete srovnání 2 stránek. - Překlad selhal, xml soubor může být poškozený - Možnosti překladu - Překladatel - Nahrát xml překladu - - - Obsah - Šablony obsahu - Média - Prohlížeč mezipaměti - Koš - Vytvořené balíčky - Datové typy - Slovník - Instalované balíčky - Instalovat téma - Instalovat startovní sadu - Jazyky - Instalovat místní balíček - Makra - Typy medií - Členové - Skupiny členů - Role - Typy členů - Typy dokumentů - Typy vztahů/vazeb - Balíčky - Balíčky - Částečné šablony - Makra částečných šablon - Instalovat z úložiště - Instalovat Runway - Moduly Runway - Skriptovací soubory - Skripty - Stylopisy - Šablony - Prohlížeč logu - Uživatelé - Nastavení - Šablony - Třetí strana - - Oprávnění uživatele - Typy uživatelů - - - Nová aktualizace je připrvena - %0% je připraven, klikněte zde pro stažení - Žádné spojení se serverem - Chyba při kontrole aktualizace. Zkontrolujte, prosím, trasovací zásobník pro další informace - - - Přístupy - Na základě přiřazených skupin a počátečních uzlů má uživatel přístup k následujícím uzlům - Přiřadit přístup - Administrátor - Pole kategorie - Uživatel byl vytvořen - Změnit heslo - Změnit fotku - Změnit heslo - nebyl uzamčen - Heslo nebylo změněno - Potvrdit heslo - Můžete změnit své heslo pro přístup do administrace Umbraca vyplněním formuláře níže a kliknutím na tlačítko 'Změnit Heslo' - Kanál obsahu - Vytvořit dalšího uživatele - Vytvořte nové uživatele a udělte mu přístup do Umbraco. Po vytvoření nového uživatele bude vygenerováno heslo, které s ním můžete sdílet. - Popis - Deaktivovat uživatele - Typ dokumentu - Editor - Výtah - Neúspěšné pokusy o přihlášení - Přejít na uživatelský profil - Přidáním skupin přidělte přístup a oprávnění - Pozvat dalšího uživatele - Pozvěte nové uživatele, a poskytněte jim přístup do Umbraco. Uživatelům bude zaslán e-mail s pozvánkou a s informacemi o tom, jak se přihlásit do Umbraco. Pozvánky mají platnost 72 hodin. - Jazyk - Nastavte jazyk, který uvidíte v nabídkách a dialogových oknech - Poslední datum uzamčení - Poslední přihlášení - Heslo bylo naposledy změněno - Přihlašovací jméno - Úvodní uzel v knihovně medií - Omezte knihovnu médií na konkrétní počáteční uzel - Úvodní uzly v knihovně medií - Omezte knihovnu médií na konkrétní počáteční uzly - Sekce - Deaktivovat přistup k Umbracu - se dosud nepřihlásil - Staré heslo - Heslo - Resetovat heslo - Vyše heslo bylo změněno! - Potvrďte, prosím, nové heslo - Zadejte Vaše nové heslo - Vaše nové heslo nesmí být prázdné! - Současné heslo - Neplatné současné heslo - Nové heslo a potvrzující heslo se liší. Zkuste to, prosím, znovu! - Potvrzující heslo není stejné jako nové heslo! - Nahradit oprávnění podřízených uzlů - Nyní měníte oprávnění pro stránky: - Vyberte stránky, pro které chcete měnit oprávnění - Odebrat fotografii - Výchozí oprávnění - Upřesnění oprávnění - Nastavte oprávnění pro konkrétní uzly - Profil - Prohledat všechny podřízené uzly - Přidejte sekce, do kterých mají uživatelé přístup - Vybrat skupiny uživatelů - Nebyl vybrán žádný počáteční uzel - Nebyly vybrány žádné počáteční uzly - Úvodní uzel v obsahu - Omezte strom obsahu na konkrétní počáteční uzel - Úvodní uzly obsahu - Omezte strom obsahu na konkrétní počáteční uzly - Uživatel byl naposledy aktualizován - byl vytvořen - Nový uživatel byl úspěšně vytvořen. Pro přihlášení do Umbraco použijte heslo níže. - Správa uživatelů - Uživatelské jméno - Oprávnění uživatele - Uživatelská skupina - byl pozván - Novému uživateli byla zaslána pozvánka s informacemi, jak se přihlásit do Umbraco. - Dobrý den, vítejte v Umbraco! Za pouhou 1 minutu budete moci používat Umbraco. Jenom od vás potřebujeme, abyste si nastavili heslo a přidali obrázek pro svůj avatar. - Vítejte v Umbraco! Vaše pozvánka bohužel vypršela. Obraťte se na svého správce a požádejte jej, aby jí znovu odeslal. - Nahrání vaší fotografie usnadní ostatním uživatelům, aby vás poznali. Kliknutím na kruh výše nahrajte svou fotku. - Spisovatel - Změnit - Váš profil - Vaše nedávná historie - Relace vyprší za - Pozvat uživatele - Vytvořit uživatele - Odeslat pozvánku - Zpět na seznam uživatelů - Umbraco: Pozvánka - Žádní uživatelé překladatelé nebyli nalezeni. Vytvořte, prosím, překladatele před tím, než začnete posílat obsah k překladu + Stránka '%0%' byla poslána k překladu + Poslat stránku '%0%' k překladu + Slov celkem + Přeložit do + Překlad hotov. + Klikutím níže můžete vidět stránky, které jste právě přeložili. Jestliže je nalezena originální stránka, dostanete srovnání 2 stránek. + Překlad selhal, xml soubor může být poškozený + Možnosti překladu + Překladatel + Nahrát xml překladu + + + Obsah + Šablony obsahu + Média + Prohlížeč mezipaměti + Koš + Vytvořené balíčky + Datové typy + Slovník + Instalované balíčky + Instalovat téma + Instalovat startovní sadu + Jazyky + Instalovat místní balíček + Makra + Typy medií + Členové + Skupiny členů + Role + Typy členů + Typy dokumentů + Typy vztahů/vazeb + Balíčky + Balíčky + Částečné šablony + Makra částečných šablon + Instalovat z úložiště + Instalovat Runway + Moduly Runway + Skriptovací soubory + Skripty + Stylopisy + Šablony + Prohlížeč logu + Uživatelé + Nastavení + Šablony + Třetí strana + + Oprávnění uživatele + Typy uživatelů + + + Nová aktualizace je připrvena + %0% je připraven, klikněte zde pro stažení + Žádné spojení se serverem + Chyba při kontrole aktualizace. Zkontrolujte, prosím, trasovací zásobník pro další informace + + + Přístupy + Na základě přiřazených skupin a počátečních uzlů má uživatel přístup k následujícím uzlům + Přiřadit přístup + Administrátor + Pole kategorie + Uživatel byl vytvořen + Změnit heslo + Změnit fotku + Změnit heslo + nebyl uzamčen + Heslo nebylo změněno + Potvrdit heslo + Můžete změnit své heslo pro přístup do administrace Umbraca vyplněním formuláře níže a kliknutím na tlačítko 'Změnit Heslo' + Kanál obsahu + Vytvořit dalšího uživatele + Vytvořte nové uživatele a udělte mu přístup do Umbraco. Po vytvoření nového uživatele bude vygenerováno heslo, které s ním můžete sdílet. + Popis + Deaktivovat uživatele + Typ dokumentu + Editor + Výtah + Neúspěšné pokusy o přihlášení + Přejít na uživatelský profil + Přidáním skupin přidělte přístup a oprávnění + Pozvat dalšího uživatele + Pozvěte nové uživatele, a poskytněte jim přístup do Umbraco. Uživatelům bude zaslán e-mail s pozvánkou a s informacemi o tom, jak se přihlásit do Umbraco. Pozvánky mají platnost 72 hodin. + Jazyk + Nastavte jazyk, který uvidíte v nabídkách a dialogových oknech + Poslední datum uzamčení + Poslední přihlášení + Heslo bylo naposledy změněno + Přihlašovací jméno + Úvodní uzel v knihovně medií + Omezte knihovnu médií na konkrétní počáteční uzel + Úvodní uzly v knihovně medií + Omezte knihovnu médií na konkrétní počáteční uzly + Sekce + Deaktivovat přistup k Umbracu + se dosud nepřihlásil + Staré heslo + Heslo + Resetovat heslo + Vyše heslo bylo změněno! + Potvrďte, prosím, nové heslo + Zadejte Vaše nové heslo + Vaše nové heslo nesmí být prázdné! + Současné heslo + Neplatné současné heslo + Nové heslo a potvrzující heslo se liší. Zkuste to, prosím, znovu! + Potvrzující heslo není stejné jako nové heslo! + Nahradit oprávnění podřízených uzlů + Nyní měníte oprávnění pro stránky: + Vyberte stránky, pro které chcete měnit oprávnění + Odebrat fotografii + Výchozí oprávnění + Upřesnění oprávnění + Nastavte oprávnění pro konkrétní uzly + Profil + Prohledat všechny podřízené uzly + Přidejte sekce, do kterých mají uživatelé přístup + Vybrat skupiny uživatelů + Nebyl vybrán žádný počáteční uzel + Nebyly vybrány žádné počáteční uzly + Úvodní uzel v obsahu + Omezte strom obsahu na konkrétní počáteční uzel + Úvodní uzly obsahu + Omezte strom obsahu na konkrétní počáteční uzly + Uživatel byl naposledy aktualizován + byl vytvořen + Nový uživatel byl úspěšně vytvořen. Pro přihlášení do Umbraco použijte heslo níže. + Správa uživatelů + Uživatelské jméno + Oprávnění uživatele + Uživatelská skupina + byl pozván + Novému uživateli byla zaslána pozvánka s informacemi, jak se přihlásit do Umbraco. + Dobrý den, vítejte v Umbraco! Za pouhou 1 minutu budete moci používat Umbraco. Jenom od vás potřebujeme, abyste si nastavili heslo a přidali obrázek pro svůj avatar. + Vítejte v Umbraco! Vaše pozvánka bohužel vypršela. Obraťte se na svého správce a požádejte jej, aby jí znovu odeslal. + Nahrání vaší fotografie usnadní ostatním uživatelům, aby vás poznali. Kliknutím na kruh výše nahrajte svou fotku. + Spisovatel + Změnit + Váš profil + Vaše nedávná historie + Relace vyprší za + Pozvat uživatele + Vytvořit uživatele + Odeslat pozvánku + Zpět na seznam uživatelů + Umbraco: Pozvánka + @@ -1958,348 +1957,345 @@ ]]> - Pozvat - Zasílám pozvání... - Smazat uživatele - Opravdu chcete smazat tento uživatelský účet? - Vše - Aktivní - Zakázané - Uzamčeno - Pozváno - Neaktivní - Jméno (A-Z) - Jméno (Z-A) - Nejnovější - Nejstarší - Poslední přihlášení - Nebyly přidány žádné skupiny uživatelů - - - Validace - Ověřit jako e-mailovou adresu - Ověřit jako číslo - Ověřit jako URL - ...nebo zadat vlastní ověření - Pole je povinné - Zadat chybovou zprávu pro vlastní validaci (volitelné) - Zadat regulární výraz - Zadat chybovou zprávu pro vlastní validaci (volitelné) - Musíte přidat alespoň - Můžete jen mít - položky - vybrané položky - Neplatné datum - Není číslo - Neplatný e-mail - Hodnota nemůže být nulová - Hodnota nemůže být prázdná - Hodnota je neplatná, neodpovídá správnému vzoru - Vlastní ověření - %1% více.]]> - %1% příliš mnoho.]]> - - - - Hodnota je nastavena na doporučenou hodnotu: '%0%'. - Hodnota byla nastavena na '%1%' pro XPath '%2%' v konfiguračním souboru '%3%'. - Očekávaná hodnota '%1%' pro '%2%' v konfiguračním souboru '%3%', ale nalezeno '%0%'. - Nalezena neočekávaná hodnota '%0%' pro '%2%' v konfiguračním souboru '%3%'. - - Vlastní chyby jsou nastaveny na '%0%'. - Vlastní chyby jsou aktuálně nastaveny na '%0%'. Před nasazením se doporučuje nastavit na '%1%'. - Vlastní chyby byly úspěšně nastaveny na '%0%'. - MacroErrors jsou nastaveny na '%0%'. - MakroErrors jsou nastaveny na '%0%', což zabrání úplnému načtení některých nebo všech stránek na vašem webu, pokud dojde k chybám v makrech. Náprava nastaví hodnotu na '%1%'. - MakroErrors jsou nyní nastaveny na '%0%'. - - Try Skip IIS Custom Errors je nastaveno na '%0%' a používáte verzi IIS '%1%'. - Try Skip IIS Custom Errors je aktuálně nastaveno na '%0%'. Doporučuje se nastavit %1% pro vaši verzi služby IIS (%2%). - Try Skip IIS Custom Errors úspěšně nastaveno na '%0%'. - - '% 0%' v konfiguračním souboru '% 1%'.]]> - Došlo k chybě, zkontrolujte ji v logu: %0%. - Databáze - Databázové schéma je pro tuto verzi Umbraco správné - Bylo zjištěno %0% problémů se schématem vaší databáze (podrobnosti najdete v logu) - Při ověřování databázového schématu vůči aktuální verzi Umbraco byly zjištěny některé chyby. - Certifikát vašeho webu je platný. - Chyba ověření certifikátu: '%0%' - Platnost SSL certifikátu vašeho webu vypršela. - Platnost certifikátu SSL vašeho webu vyprší za %0% dní. - Chyba při pingování adresy URL %0% - '%1%' - Aktuálně prohlížíte web pomocí schématu HTTPS. - AppSetting 'Umbraco.Core.UseHttps' je v souboru web.config nastaven na 'false'. Jakmile vstoupíte na tento web pomocí schématu HTTPS, mělo by být nastaveno na 'true'. - AppSetting 'Umbraco.Core.UseHttps' je v souboru web.config nastaven na '%0%', vaše cookies %1% jsou označeny jako zabezpečené. - V souboru web.config se nepodařilo aktualizovat nastavení 'Umbraco.Core.UseHttps'. Chyba: %0% - - Povolit HTTPS - Nastaví nastavení umbracoSSL na true v appSettings v souboru web.config. - AppSetting 'Umbraco.Core.UseHttps' je nyní nastaveno na 'true' v souboru web.config, vaše cookies budou označeny jako zabezpečené. - Fix - Nelze opravit kontrolu pro porovnání hodnot pomocí 'ShouldNotEqual'. - Nelze opravit kontrolu pro porovnání hodnot pomocí 'ShouldEqual' s poskytnutou hodnotou. - Hodnota k opravě nebyla poskytnuta. - Režim kompilace ladění je zakázán. - Režim ladění je aktuálně povolen. Před spuštěním webu se doporučuje toto nastavení deaktivovat. - Režim ladění byl úspěšně deaktivován. - Režim sledování je deaktivován. - Režim sledování je aktuálně povolen. Před spuštěním se doporučuje toto nastavení deaktivovat. - Režim sledování byl úspěšně deaktivován. - Všechny složky mají nastavena správná oprávnění. - - Soubor neexistuje: '%0%'. - - %0%.]]> - %0%. Pokud nejsou psány, není třeba podniknout žádné kroky.]]> - Všechny soubory mají nastavena správná oprávnění. - - %0%.]]> - %0%. Pokud nejsou psány, není třeba podniknout žádné kroky.]]> - X-Frame-Options, které určuje, zda může být obsah webu zobrazen na jiném webu pomocí IFRAME.]]> - X-Frame-Options, které určuje, zda může být obsah webu zobrazen na jiném webu pomocí IFRAME.]]> - Nastavit záhlaví v Konfiguraci - Přidá hodnotu do sekce httpProtocol/customHeaders do web.config, aby se zabránilo tomu, že web může být zobrazen na jiném webu pomocí IFRAME. - Do souboru web.config bylo přidáno nastavení pro vytvoření záhlaví, které zabrání jinému webu, zobrazit tento web pomocí IFRAME. - Nelze aktualizovat soubor web.config. Chyba: %0% - X-Content-Type-Options použitá k ochraně před zranitelnostmi čichání MIME.]]> - X-Content-Type-Options použité k ochraně před zranitelnostmi čichání MIME nebyly nalezeny.]]> - Přidá hodnotu do sekce httpProtocol/customHeaders v souboru web.config, která chrání před zranitelnostmi MIME. - Do souboru web.config bylo přidáno nastavení pro vytvoření záhlaví, které chrání před zranitelnostmi MIME. - Strict-Transport-Security, také známo jako HSTS-header, bylo nalezeno.]]> - Strict-Transport-Security nebylo nalezeno.]]> - Do sekce httpProtocol/customHeaders v souboru web.config přidá záhlaví 'Strict-Transport-Security' s hodnotou 'max-age = 10886400'. Tuto opravu použijte pouze v případě, že vaše domény budou spuštěny s https po dobu příštích 18 týdnů (minimálně). - Do vašeho souboru web.config bylo přidáno záhlaví HSTS. - X-XSS-Protection bylo nalezeno.]]> - X-XSS-Protection bylo nalezeno.]]> - Přidá záhlaví 'X-XSS-Protection' s hodnotou '1; mode=block' do sekce httpProtocol/customHeaders v souboru web.config. - Záhlaví X-XSS-Protection bylo přidáno do vašeho souboru web.config. - - %0%.]]> - Nebyly nalezeny žádné hlavičky odhalující informace o technologii webových stránek. - V souboru Web.config nelze najít system.net/mailsettings. - V části system.net/mailsettings v souboru web.config není hostitel nakonfigurován. - Nastavení SMTP jsou správně nakonfigurována a služba funguje jak má. - Server SMTP konfigurovaný s hostitelem '%0%' a portem '%1%' nelze nalézt. Zkontrolujte prosím, zda jsou nastavení SMTP v souboru Web.config a v sekci system.net/mailsettings správná. - %0%.]]> - %0%.]]> -

    Výsledky plánovaných kontrol Umbraco Health Checks provedených na %0% v %1% jsou následující:

    %2%]]>
    - Stav Umbraco Health Check: %0% - Zkontrolovat všechny skupiny - Zkontrolovat skupinu - - Kontrola vyhodnocuje různé oblasti vašeho webu z hlediska nastavení osvědčených postupů, konfigurace, potenciálních problémů atd. Problémy lze snadno vyřešit stisknutím tlačítka. Můžete přidat své vlastní kontroly, podívejte se na dokumentaci pro více informací o vlastních kontrolách.

    + Pozvat + Zasílám pozvání... + Smazat uživatele + Opravdu chcete smazat tento uživatelský účet? + Vše + Aktivní + Zakázané + Uzamčeno + Pozváno + Neaktivní + Jméno (A-Z) + Jméno (Z-A) + Nejnovější + Nejstarší + Poslední přihlášení + Nebyly přidány žádné skupiny uživatelů + + + Validace + Ověřit jako e-mailovou adresu + Ověřit jako číslo + Ověřit jako URL + ...nebo zadat vlastní ověření + Pole je povinné + Zadat chybovou zprávu pro vlastní validaci (volitelné) + Zadat regulární výraz + Zadat chybovou zprávu pro vlastní validaci (volitelné) + Musíte přidat alespoň + Můžete jen mít + položky + vybrané položky + Neplatné datum + Není číslo + Neplatný e-mail + Hodnota nemůže být nulová + Hodnota nemůže být prázdná + Hodnota je neplatná, neodpovídá správnému vzoru + Vlastní ověření + %1% více.]]> + %1% příliš mnoho.]]> + + + + Hodnota je nastavena na doporučenou hodnotu: '%0%'. + Hodnota byla nastavena na '%1%' pro XPath '%2%' v konfiguračním souboru '%3%'. + Očekávaná hodnota '%1%' pro '%2%' v konfiguračním souboru '%3%', ale nalezeno '%0%'. + Nalezena neočekávaná hodnota '%0%' pro '%2%' v konfiguračním souboru '%3%'. + + Vlastní chyby jsou nastaveny na '%0%'. + Vlastní chyby jsou aktuálně nastaveny na '%0%'. Před nasazením se doporučuje nastavit na '%1%'. + Vlastní chyby byly úspěšně nastaveny na '%0%'. + MacroErrors jsou nastaveny na '%0%'. + MakroErrors jsou nastaveny na '%0%', což zabrání úplnému načtení některých nebo všech stránek na vašem webu, pokud dojde k chybám v makrech. Náprava nastaví hodnotu na '%1%'. + MakroErrors jsou nyní nastaveny na '%0%'. + + Try Skip IIS Custom Errors je nastaveno na '%0%' a používáte verzi IIS '%1%'. + Try Skip IIS Custom Errors je aktuálně nastaveno na '%0%'. Doporučuje se nastavit %1% pro vaši verzi služby IIS (%2%). + Try Skip IIS Custom Errors úspěšně nastaveno na '%0%'. + + Soubor neexistuje: '%0%'. + '% 0%' v konfiguračním souboru '% 1%'.]]> + Došlo k chybě, zkontrolujte ji v logu: %0%. + Databáze - Databázové schéma je pro tuto verzi Umbraco správné + Bylo zjištěno %0% problémů se schématem vaší databáze (podrobnosti najdete v logu) + Při ověřování databázového schématu vůči aktuální verzi Umbraco byly zjištěny některé chyby. + Certifikát vašeho webu je platný. + Chyba ověření certifikátu: '%0%' + Platnost SSL certifikátu vašeho webu vypršela. + Platnost certifikátu SSL vašeho webu vyprší za %0% dní. + Chyba při pingování adresy URL %0% - '%1%' + Aktuálně prohlížíte web pomocí schématu HTTPS. + AppSetting 'Umbraco.Core.UseHttps' je v souboru web.config nastaven na 'false'. Jakmile vstoupíte na tento web pomocí schématu HTTPS, mělo by být nastaveno na 'true'. + AppSetting 'Umbraco.Core.UseHttps' je v souboru web.config nastaven na '%0%', vaše cookies %1% jsou označeny jako zabezpečené. + V souboru web.config se nepodařilo aktualizovat nastavení 'Umbraco.Core.UseHttps'. Chyba: %0% + + Povolit HTTPS + Nastaví nastavení umbracoSSL na true v appSettings v souboru web.config. + AppSetting 'Umbraco.Core.UseHttps' je nyní nastaveno na 'true' v souboru web.config, vaše cookies budou označeny jako zabezpečené. + Fix + Nelze opravit kontrolu pro porovnání hodnot pomocí 'ShouldNotEqual'. + Nelze opravit kontrolu pro porovnání hodnot pomocí 'ShouldEqual' s poskytnutou hodnotou. + Hodnota k opravě nebyla poskytnuta. + Režim kompilace ladění je zakázán. + Režim ladění je aktuálně povolen. Před spuštěním webu se doporučuje toto nastavení deaktivovat. + Režim ladění byl úspěšně deaktivován. + Režim sledování je deaktivován. + Režim sledování je aktuálně povolen. Před spuštěním se doporučuje toto nastavení deaktivovat. + Režim sledování byl úspěšně deaktivován. + Všechny složky mají nastavena správná oprávnění. + + %0%.]]> + %0%. Pokud nejsou psány, není třeba podniknout žádné kroky.]]> + Všechny soubory mají nastavena správná oprávnění. + + %0%.]]> + %0%. Pokud nejsou psány, není třeba podniknout žádné kroky.]]> + X-Frame-Options, které určuje, zda může být obsah webu zobrazen na jiném webu pomocí IFRAME.]]> + X-Frame-Options, které určuje, zda může být obsah webu zobrazen na jiném webu pomocí IFRAME.]]> + Nastavit záhlaví v Konfiguraci + Přidá hodnotu do sekce httpProtocol/customHeaders do web.config, aby se zabránilo tomu, že web může být zobrazen na jiném webu pomocí IFRAME. + Do souboru web.config bylo přidáno nastavení pro vytvoření záhlaví, které zabrání jinému webu, zobrazit tento web pomocí IFRAME. + Nelze aktualizovat soubor web.config. Chyba: %0% + X-Content-Type-Options použitá k ochraně před zranitelnostmi čichání MIME.]]> + X-Content-Type-Options použité k ochraně před zranitelnostmi čichání MIME nebyly nalezeny.]]> + Přidá hodnotu do sekce httpProtocol/customHeaders v souboru web.config, která chrání před zranitelnostmi MIME. + Do souboru web.config bylo přidáno nastavení pro vytvoření záhlaví, které chrání před zranitelnostmi MIME. + Strict-Transport-Security, také známo jako HSTS-header, bylo nalezeno.]]> + Strict-Transport-Security nebylo nalezeno.]]> + Do sekce httpProtocol/customHeaders v souboru web.config přidá záhlaví 'Strict-Transport-Security' s hodnotou 'max-age = 10886400'. Tuto opravu použijte pouze v případě, že vaše domény budou spuštěny s https po dobu příštích 18 týdnů (minimálně). + Do vašeho souboru web.config bylo přidáno záhlaví HSTS. + X-XSS-Protection bylo nalezeno.]]> + X-XSS-Protection bylo nalezeno.]]> + Přidá záhlaví 'X-XSS-Protection' s hodnotou '1; mode=block' do sekce httpProtocol/customHeaders v souboru web.config. + Záhlaví X-XSS-Protection bylo přidáno do vašeho souboru web.config. + + %0%.]]> + Nebyly nalezeny žádné hlavičky odhalující informace o technologii webových stránek. + V souboru Web.config nelze najít system.net/mailsettings. + V části system.net/mailsettings v souboru web.config není hostitel nakonfigurován. + Nastavení SMTP jsou správně nakonfigurována a služba funguje jak má. + Server SMTP konfigurovaný s hostitelem '%0%' a portem '%1%' nelze nalézt. Zkontrolujte prosím, zda jsou nastavení SMTP v souboru Web.config a v sekci system.net/mailsettings správná. + %0%.]]> + %0%.]]> +

    Výsledky plánovaných kontrol Umbraco Health Checks provedených na %0% v %1% jsou následující:

    %2%]]>
    + Stav Umbraco Health Check: %0% + Zkontrolovat všechny skupiny + Zkontrolovat skupinu + + Kontrola vyhodnocuje různé oblasti vašeho webu z hlediska nastavení osvědčených postupů, konfigurace, potenciálních problémů atd. Problémy lze snadno vyřešit stisknutím tlačítka. Můžete přidat své vlastní kontroly, podívejte se na dokumentaci pro více informací o vlastních kontrolách.

    ]]> -
    - - - Zakázat sledování URL - Povolit sledování URL - Jazyk - Originální URL - Přesměrováno na - Správa URL přesměrování - Na tuto položku obsahu přesměrovávají následující adresy URL: - Nebyla provedena žádná přesměrování - Jakmile bude publikovaná stránka přejmenována nebo přesunuta, bude automaticky provedeno přesměrování na novou stránku. - Opravdu chcete odstranit přesměrování z '%0%' na '%1%'? - Přesměrování bylo odstraněno. - Chyba při odebírání URL přesměrování. - Toto odstraní přesměrování - Opravdu chcete zakázat sledování URL adres? - Sledování URL adres je nyní zakázáno. - Při deaktivaci sledování URL adres došlo k chybě, další informace naleznete v logu. - Sledování URL adres je nyní povoleno. - Chyba při povolení sledování URL adres, další informace lze nalézt v logu. - - - Žádné položky ze slovníku na výběr - - - %0% znaků.]]> - %1% je moc.]]> - - - Obsah s ID: {0} v koši souvisí s původním nadřazeným obsahem s ID: {1} - Média s ID: {0} v koši souvisí s původním nadřazeným médiem s ID: {1} - Tuto položku nelze automaticky obnovit - Neexistuje žádné místo, kde lze tuto položku automaticky obnovit. Položku můžete přesunout ručně pomocí stromu níže. - byla obnovena pod - - - Směr - Nadřazený s potomkem - Obousměrný - Nadřazená - Potomek - Počet - Vazby - Vytvořeno - Komentář - Název - Žádné vazby pro tento typ vazby. - Typ vazby - Vazby - - - Začínáme - Správa přesměrování - Obsah - Vítejte - Správa Examine - Stav publikování - Tvůrce modelů - Health Check - Profilování - Začínáme - Instalovat Umbraco formuláře - - - Jít zpět - Aktivní rozvržení: - Skočit do - skupina - prošlo - varování - selhalo - návrh - Kontrola prošla - Kontrola selhala - Otevřít hledání v backoffice - Otevřít/zavřít nápovědu backoffice - Otevřít/zavřít možnosti vašeho profilu - Otevřít kontextové menu pro - Aktuální jazyk - Přepnout jazyk na - Vytvořit novou složku - Částečná šablona - Makro částečné šablony - Člen - Datový typ - Prohledat přesměrování - Prohledat skupiny uživatelů - Prohledat uživatele - Vytvořit položku - Vytvořit - Upravit - Název - - - Závislosti - Tento datový typ nemá žádné závislosti. - Použito v dokumentových typech - Žádné vazby na typy dokumentů. - Použito v typech médií - Žádné vazby na typy médií. - Použito v typech členů - Žádné vazby na typy členů. - Použito v - Použito v dokumentech - Použito ve členech - Použito v médiích - - - Úrovně logování - Uložená vyhledávání - Celkem položek - Časové razítko - Úroveň - Stroj - Zpráva - Výjimka - Vlastnosti - Vyhledat na Googlu - Vyhledat zprávu na Googlu - Vyhledat na Bing - Vyhledat zprávu na Bing - Prohledat naše Umbraco - Vyhledat tuto zprávu na našich fórech a dokumentech Umbraco - Vyhledat Our Umbraco na Googlu - Prohledat Our Umbraco fóra pomocí Googlu - Prohledat Umbraco Source - Vyhledat ve zdrojovém kódu Umbraco na Github - Prohledat Umbraco Issues - Prohledat Umbraco Issues na Github - Smazat toto vyhledávání - Najít logy s ID požadavku - Najít logy se jmenným prostorem - Najít logy s názvem stroje - Otevřít - - - Kopírovat %0% - %0% z %1% - Odebrat všechny položky - - - Otevřít akce vlastností - - - Čekejte - Stav obnovení - Cache paměť - - + + + Zakázat sledování URL + Povolit sledování URL + Jazyk + Originální URL + Přesměrováno na + Správa URL přesměrování + Na tuto položku obsahu přesměrovávají následující adresy URL: + Nebyla provedena žádná přesměrování + Jakmile bude publikovaná stránka přejmenována nebo přesunuta, bude automaticky provedeno přesměrování na novou stránku. + Opravdu chcete odstranit přesměrování z '%0%' na '%1%'? + Přesměrování bylo odstraněno. + Chyba při odebírání URL přesměrování. + Toto odstraní přesměrování + Opravdu chcete zakázat sledování URL adres? + Sledování URL adres je nyní zakázáno. + Při deaktivaci sledování URL adres došlo k chybě, další informace naleznete v logu. + Sledování URL adres je nyní povoleno. + Chyba při povolení sledování URL adres, další informace lze nalézt v logu. + + + Žádné položky ze slovníku na výběr + + + %0% znaků.]]> + %1% je moc.]]> + + + Obsah s ID: {0} v koši souvisí s původním nadřazeným obsahem s ID: {1} + Média s ID: {0} v koši souvisí s původním nadřazeným médiem s ID: {1} + Tuto položku nelze automaticky obnovit + Neexistuje žádné místo, kde lze tuto položku automaticky obnovit. Položku můžete přesunout ručně pomocí stromu níže. + byla obnovena pod + + + Směr + Nadřazený s potomkem + Obousměrný + Nadřazená + Potomek + Počet + Vazby + Vytvořeno + Komentář + Název + Žádné vazby pro tento typ vazby. + Typ vazby + Vazby + + + Začínáme + Správa přesměrování + Obsah + Vítejte + Správa Examine + Stav publikování + Tvůrce modelů + Health Check + Profilování + Začínáme + Instalovat Umbraco formuláře + + + Jít zpět + Aktivní rozvržení: + Skočit do + skupina + prošlo + varování + selhalo + návrh + Kontrola prošla + Kontrola selhala + Otevřít hledání v backoffice + Otevřít/zavřít nápovědu backoffice + Otevřít/zavřít možnosti vašeho profilu + Otevřít kontextové menu pro + Aktuální jazyk + Přepnout jazyk na + Vytvořit novou složku + Částečná šablona + Makro částečné šablony + Člen + Datový typ + Prohledat přesměrování + Prohledat skupiny uživatelů + Prohledat uživatele + Vytvořit položku + Vytvořit + Upravit + Název + + + Závislosti + Tento datový typ nemá žádné závislosti. + Použito v dokumentových typech + Žádné vazby na typy dokumentů. + Použito v typech médií + Žádné vazby na typy médií. + Použito v typech členů + Žádné vazby na typy členů. + Použito v + Použito v dokumentech + Použito ve členech + Použito v médiích + + + Úrovně logování + Uložená vyhledávání + Celkem položek + Časové razítko + Úroveň + Stroj + Zpráva + Výjimka + Vlastnosti + Vyhledat na Googlu + Vyhledat zprávu na Googlu + Vyhledat na Bing + Vyhledat zprávu na Bing + Prohledat naše Umbraco + Vyhledat tuto zprávu na našich fórech a dokumentech Umbraco + Vyhledat Our Umbraco na Googlu + Prohledat Our Umbraco fóra pomocí Googlu + Prohledat Umbraco Source + Vyhledat ve zdrojovém kódu Umbraco na Github + Prohledat Umbraco Issues + Prohledat Umbraco Issues na Github + Smazat toto vyhledávání + Najít logy s ID požadavku + Najít logy se jmenným prostorem + Najít logy s názvem stroje + Otevřít + + + Kopírovat %0% + %0% z %1% + Odebrat všechny položky + + + Otevřít akce vlastností + + + Čekejte + Stav obnovení + Cache paměť + + - - Znovu načíst - Cache databáze - - + Znovu načíst + Cache databáze + + Znovuvytvoření může být náročné. Použijte jej, když nestačí obnovení stránky, a domníváte se, že mezipaměť databáze nebyla správně vygenerována - což by naznačovalo možný kritický problém Umbraco. ]]> - - Obnovit - Internals - - + Obnovit + Internals + + nebudete muset používat. ]]> - - Sběr - Stav publikované mezipaměti - Mezipaměti - - - Profilování výkonu - - + Sběr + Stav publikované mezipaměti + Mezipaměti + + + Profilování výkonu + + Umbraco aktuálně běží v režimu ladění. To znamená, že můžete použít vestavěný profiler výkonu k vyhodnocení výkonu při vykreslování stránek.

    Pokud chcete aktivovat profiler pro konkrétní vykreslení stránky, jednoduše při požadavku na stránku jednoduše přidejte umbDebug=true do URL.

    Pokud chcete, aby byl profiler ve výchozím nastavení aktivován pro všechna vykreslení stránky, můžete použít přepínač níže. Ve vašem prohlížeči nastaví soubor cookie, který automaticky aktivuje profiler. Jinými slovy, profiler bude ve výchozím nastavení aktivní pouze ve vašem prohlížeči, ne v ostatních.

    ]]> -
    - Ve výchozím stavu aktivovat profiler - Přátelské připomenutí - - + Ve výchozím stavu aktivovat profiler + Přátelské připomenutí + + Nikdy byste neměli nechat produkční web běžet v režimu ladění. Režim ladění je vypnut nastavením debug="false" na elementu compilation v souboru web.config.

    ]]> -
    - - + + Umbraco v současné době neběží v režimu ladění, takže nemůžete použít vestavěný profiler. Takto by to mělo být pro produkční web.

    @@ -2307,53 +2303,53 @@ Režim ladění je zapnut nastavením debug="true" na elementu compilation v souboru web.config.

    ]]> -
    - - - Hodiny tréninkových videí Umbraco jsou blíž než si myslíte - - Chcete ovládnout Umbraco? Stačí strávit pár minut sledování jednoho z těchto videí o používání Umbraco. Nebo navštivte umbraco.tv , kde najdete ještě více videí o Umbraco

    +
    + + + Hodiny tréninkových videí Umbraco jsou blíž než si myslíte + + Chcete ovládnout Umbraco? Stačí strávit pár minut sledování jednoho z těchto videí o používání Umbraco. Nebo navštivte umbraco.tv, kde najdete ještě více videí o Umbraco

    ]]> -
    - Chcete-li začít - - - Začněte zde - Tato část obsahuje stavební bloky pro váš web Umbraco. Podle níže uvedených odkazů se dozvíte více o práci s položkami v části Nastavení - Zjistit více - - v sekci Dokumentace v Our Umbraco + + Chcete-li začít + + + Začněte zde + Tato část obsahuje stavební bloky pro váš web Umbraco. Podle níže uvedených odkazů se dozvíte více o práci s položkami v části Nastavení + Zjistit více + + v sekci Dokumentace v Our Umbraco ]]> - - - fóru komunity + + + fóru komunity ]]> - - - výuková videa (některá jsou zdarma, jiná vyžadují předplatné) + + + výuková videa (některá jsou zdarma, jiná vyžadují předplatné) ]]> - - - nástrojích zvyšujících produktivitu a komerční podpoře + + + nástrojích zvyšujících produktivitu a komerční podpoře ]]> - - - školení a certifikace + + + školení a certifikace ]]> - - - - Vítejte v přátelském CMS - Děkujeme, že jste si vybrali Umbraco - myslíme si, že by to mohl být začátek něčeho krásného. I když se to může zpočátku zdát ohromující, udělali jsme hodně pro to, aby byla křivka učení co nejhladší a nejrychlejší. - - - Umbraco formuláře - Vytvářejte formuláře pomocí intuitivního rozhraní drag and drop. Od jednoduchých kontaktních formulářů, které odesílají e-maily, až po pokročilé dotazníky, které se integrují do systémů CRM. Vaši klienti to budou milovat! - +
    + + + Vítejte v přátelském CMS + Děkujeme, že jste si vybrali Umbraco - myslíme si, že by to mohl být začátek něčeho krásného. I když se to může zpočátku zdát ohromující, udělali jsme hodně pro to, aby byla křivka učení co nejhladší a nejrychlejší. + + + Umbraco formuláře + Vytvářejte formuláře pomocí intuitivního rozhraní drag and drop. Od jednoduchých kontaktních formulářů, které odesílají e-maily, až po pokročilé dotazníky, které se integrují do systémů CRM. Vaši klienti to budou milovat! +
    diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml index b6d10589fe..d7dccbc08c 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml @@ -839,7 +839,7 @@ Sætter folderrettigheder op Umbraco har behov for 'write/modify' adgang til bestemte foldere, for at kunne gemme filer som billeder og PDF'er. Umbraco gemmer også midlertidige data (eksempelvis cachen) for at forbedre ydelsen på dit website. Jeg har lyst til at begynde på bar bund - lær hvordan) Du kan stadig vælge at installere Runway senere. Gå venligst til Udvikler-sektionen og vælg Pakker.]]> + lær hvordan) Du kan stadig vælge at installere Runway senere. Gå venligst til Udvikler-sektionen og vælg Pakker.]]> Du har lige opsat en ren Umbraco-platform. Hvad ønsker du nu at gøre? Runway er installeret Dette er vores liste over anbefalede moduler. Kryds dem af du ønsker at installere eller se den fulde liste af moduler ]]> @@ -885,7 +885,7 @@ Log ind nedenfor Log ind med Din session er udløbet - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Glemt adgangskode? En e-mail vil blive sendt til den angivne adresse med et link til at nulstille din adgangskode En e-mail med instruktioner for nulstilling af adgangskoden vil blive sendt til den angivne adresse, hvis det matcher vores optegnelser @@ -1054,10 +1054,6 @@ Mange hilsner fra Umbraco robotten - - %0% kunne ikke udgives, fordi et 3. parts modul annullerede handlingen Medtag ikke-udgivede undersider @@ -1106,7 +1102,6 @@ Mange hilsner fra Umbraco robotten Nuværende version Rød tekst vil ikke blive vist i den valgte version. Grøn betyder tilføjet]]> Dokument tilbagerullet - Vælg en version at sammenligne med den nuværende version Her vises den valgte version som html. Hvis du ønsker at se forskellen mellem de 2 versioner på samme tid, brug 'diff'-oversigten Tilbagerulning til Vælg version @@ -1439,7 +1434,7 @@ Mange hilsner fra Umbraco robotten Dette benyttes ikke for en Element-type Du har lavet ændringer til denne egenskab. Er du sikker på at du vil kassere dem? Visning - Label hen over (fuld brede) + Label hen over (fuld bredde) Tilføj sprog @@ -1682,13 +1677,14 @@ Mange hilsner fra Umbraco robotten Indtast et regulært udtryk Du skal tilføje mindst Du kan kun have + Tilføj op til elementer elementer valgt Ugyldig dato Ikke et tal Ugyldig e-mail - %1% more.]]> - %1% too many.]]> + %1% mere.]]> + %1% for mange.]]> Slå URL tracker fra diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/de.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/de.xml index 518ad58bea..7d61559280 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/de.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/de.xml @@ -709,7 +709,6 @@ Aus Ok Öffnen - Optionen An oder @@ -821,9 +820,11 @@ Die Datenbank wurde für Umbraco %0% konfiguriert. Klicken Sie auf <strong>weiter</strong>, um fortzufahren. - <p>Die angegebene Datenbank ist leider nicht erreichbar. Bitte prüfen Sie die Verbindungszeichenfolge ("Connection String") in der "web.config"-Datei.</p> - <p>Um fortzufahren, passen Sie bitte die "web.config"-Datei mit einem beliebigen Text-Editor an. Scrollen Sie dazu nach unten, fügen Sie die Verbindungszeichenfolge für die zuverbindende Datenbank als Eintrag "UmbracoDbDSN" hinzu und speichern Sie die Datei.</p> - <p>Klicken Sie nach erfolgter Anpassung auf <strong>Wiederholen</strong>.<br />Wenn Sie weitere technische Informationen benötigen, besuchen Sie <a href="https://our.umbraco.com/wiki" target="_blank">The Umbraco documentation wiki</a>.</p> + Die angegebene Datenbank ist leider nicht erreichbar. Bitte prüfen Sie die Verbindungszeichenfolge ("Connection String") in der "web.config"-Datei.

    +

    Um fortzufahren, passen Sie bitte die "web.config"-Datei mit einem beliebigen Text-Editor an. Scrollen Sie dazu nach unten, fügen Sie die Verbindungszeichenfolge für die zuverbindende Datenbank als Eintrag "UmbracoDbDSN" hinzu und speichern Sie die Datei.

    +

    Klicken Sie nach erfolgter Anpassung auf Wiederholen.
    Wenn Sie weitere technische Informationen benötigen, besuchen Sie The Umbraco documentation wik.

    + ]]>
    Um diesen Schritt abzuschließen, müssen Sie die notwendigen Informationen zur Datenbankverbindung angeben.<br />Bitte kontaktieren Sie Ihren Provider bzw. Server-Administrator für weitere Informationen. @@ -865,7 +866,7 @@ Ich möchte mit einem leeren System ohne Inhalte und Vorgaben starten Die Website ist zur Zeit komplett leer und ohne Inhalte und Vorgaben zu Erstellung eigener Dokumenttypen und Vorlagen bereit. - (<a href="http://Umbraco.tv/documentation/videos/for-site-builders/foundation/document-types">So geht's</a>) + (<a href="https://umbraco.tv/documentation/videos/for-site-builders/foundation/document-types">So geht's</a>) Sie können "Runway" auch jederzeit später installieren. Verwenden Sie hierzu den Punkt "Pakete" im Entwickler-Bereich. Die Einrichtung von Umbraco ist abgeschlossen und das Content-Management-System steht bereit. Wie soll es weitergehen? @@ -926,7 +927,7 @@ Hier anmelden: Anmelden mit Sitzung abgelaufen - <p style="text-align:right;">&copy; 2001 - %0% <br /><a href="http://umbraco.com" style="text-decoration: none" target="_blank">umbraco.org</a></p> + <p style="text-align:right;">&copy; 2001 - %0% <br /><a href="https://umbraco.com" style="text-decoration: none" target="_blank">umbraco.org</a></p> Kennwort vergessen? Es wird eine E-Mail mit einem Kennwort-Zurücksetzen-Link an die angegebene Adresse geschickt. Es wird eine E-Mail mit Anweisungen zum Zurücksetzen des Kennwortes an die angegebene Adresse geschickt sofern diese im Datenbestand gefunden wurde. @@ -1492,9 +1493,6 @@ Neuer Stil Stil bearbeiten Rich text editor Stile - - Definiere die Stile, die im 'Rich-Text-Editor' verfügbar sein sollen. - Definiere die Styles, die im Rich-Text-Editor dieses Stylesheets verfügbar sein sollen. Stylesheet bearbeiten Stylesheet-Regel bearbeiten diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml index 2ab1d90b07..c7b974e208 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml @@ -26,7 +26,7 @@ Exit Move Notifications - Public access + Restrict Public Access Publish Unpublish Reload @@ -71,7 +71,7 @@ Allow access to create nodes Allow access to delete nodes Allow access to move a node - Allow access to set and change public access for a node + Allow access to set and change access restrictions for a node Allow access to publish a node Allow access to unpublish a node Allow access to change permissions for a node @@ -796,7 +796,6 @@ Other Articles Videos - Clear Installing @@ -851,8 +850,8 @@

    To proceed, please edit the "web.config" file (using Visual Studio or your favourite text editor), scroll to the bottom, add the connection string for your database in the key named "UmbracoDbDSN" and save the file.

    Click the retry button when - done.
    - More information on editing web.config here.

    ]]>
    + done.
    + More information on editing web.config here.

    ]]> Please contact your ISP if necessary. If you're installing on a local machine or server you might need information from your system administrator.]]> @@ -899,7 +898,7 @@ I want to start from scratch learn how) + (learn how) You can still choose to install Runway later on. Please go to the Developer section and choose Packages. ]]> You've just set up a clean Umbraco platform. What do you want to do next? @@ -967,7 +966,7 @@ To manage your website, simply open the Umbraco back office and start adding con Log in below Sign in with Session timed out - © 2001 - %0%
    Umbraco.com

    ]]>
    + © 2001 - %0%
    Umbraco.com

    ]]>
    Forgotten password? An email will be sent to the address specified with a link to reset your password An email with password reset instructions will be sent to the specified address if it matched our records @@ -2180,7 +2179,7 @@ To manage your website, simply open the Umbraco back office and start adding con The health checker evaluates various areas of your site for best practice settings, configuration, potential problems, etc. You can easily fix problems by pressing a button. - You can add your own health checks, have a look at the documentation for more information about custom health checks.

    + You can add your own health checks, have a look at the documentation for more information about custom health checks.

    ]]>
    @@ -2261,7 +2260,7 @@ To manage your website, simply open the Umbraco back office and start adding con Open/Close your profile options Setup Culture and Hostnames for %0% Create new node under %0% - Setup Public access on %0% + Setup access restrictions on %0% Setup Permissions on %0% Change sort order for %0% Create Content Template based on %0% @@ -2282,10 +2281,17 @@ To manage your website, simply open the Umbraco back office and start adding con Name Add new row View more options - Has translation - Missing translation - Dictionary items - Perform action %0% on the %1% node + Search the Umbraco backoffice + Search for content nodes, media nodes etc. across the backoffice. + When autocomplete results are available, press up and down arrows, or use the tab key and use the enter key to select. + Path: + Found in + Has translation + Missing translation + Dictionary items + Select one of the options to edit the node. + Perform action %0% on the %1% node + Add image caption References @@ -2430,7 +2436,7 @@ To manage your website, simply open the Umbraco back office and start adding con Hours of Umbraco training videos are only a click away Want to master Umbraco? Spend a couple of minutes learning some best practices by watching one of these videos about using Umbraco. And visit umbraco.tv for even more Umbraco videos

    +

    Want to master Umbraco? Spend a couple of minutes learning some best practices by watching one of these videos about using Umbraco. And visit umbraco.tv for even more Umbraco videos

    ]]>
    To get you started @@ -2441,27 +2447,27 @@ To manage your website, simply open the Umbraco back office and start adding con Find out more in the Documentation section of Our Umbraco + Read more about working with the items in Settings in the Documentation section of Our Umbraco ]]> Community Forum + Ask a question in the Community Forum ]]> tutorial videos (some are free, some require a subscription) + Watch our tutorial videos (some are free, some require a subscription) ]]> productivity boosting tools and commercial support + Find out about our productivity boosting tools and commercial support ]]> training and certification opportunities + Find out about real-life training and certification opportunities ]]> diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml index fb6b5a22d6..7a0afb0a69 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml @@ -27,7 +27,7 @@ Exit Move Notifications - Public access + Restrict Public Access Publish Unpublish Reload @@ -72,7 +72,7 @@ Allow access to create nodes Allow access to delete nodes Allow access to move a node - Allow access to set and change public access for a node + Allow access to set and change access restrictions for a node Allow access to publish a node Allow access to unpublish a node Allow access to change permissions for a node @@ -259,7 +259,7 @@ This document is published but its URL cannot be routed Publish Published - Published (pending changes)> + Published (pending changes) Publication Status %0% and all content items underneath and thereby making their content publicly available.]]> @@ -805,7 +805,6 @@ Other Articles Videos - Clear Installing @@ -858,8 +857,8 @@

    To proceed, please edit the "web.config" file (using Visual Studio or your favourite text editor), scroll to the bottom, add the connection string for your database in the key named "UmbracoDbDSN" and save the file.

    Click the retry button when - done.
    - More information on editing web.config here.

    ]]> + done.
    + More information on editing web.config here.

    ]]> Please contact your ISP if necessary. If you're installing on a local machine or server you might need information from your system administrator.]]> @@ -906,7 +905,7 @@ I want to start from scratch learn how) + (learn how) You can still choose to install Runway later on. Please go to the Developer section and choose Packages. ]]> You've just set up a clean Umbraco platform. What do you want to do next? @@ -974,7 +973,7 @@ To manage your website, simply open the Umbraco back office and start adding con Log in below Sign in with Session timed out - © 2001 - %0%
    Umbraco.com

    ]]>
    + © 2001 - %0%
    Umbraco.com

    ]]>
    Forgotten password? An email will be sent to the address specified with a link to reset your password An email with password reset instructions will be sent to the specified address if it matched our records @@ -1367,7 +1366,6 @@ To manage your website, simply open the Umbraco back office and start adding con Current version Red text will not be shown in the selected version. , green means added]]> Document has been rolled back - Select a version to compare with the current version This displays the selected version as HTML, if you wish to see the difference between 2 versions at the same time, use the diff view Rollback to Select version @@ -1423,6 +1421,7 @@ To manage your website, simply open the Umbraco back office and start adding con Validation errors must be fixed before the item can be saved Failed Saved + Saved. To view the changes please reload your browser Insufficient user permissions, could not complete the operation Cancelled Operation was cancelled by a 3rd party add-in @@ -2200,7 +2199,7 @@ To manage your website, simply open the Umbraco back office and start adding con The health checker evaluates various areas of your site for best practice settings, configuration, potential problems, etc. You can easily fix problems by pressing a button. - You can add your own health checks, have a look at the documentation for more information about custom health checks.

    + You can add your own health checks, have a look at the documentation for more information about custom health checks.

    ]]>
    @@ -2282,7 +2281,7 @@ To manage your website, simply open the Umbraco back office and start adding con Open/Close your profile options Setup Culture and Hostnames for %0% Create new node under %0% - Setup Public access on %0% + Setup access restrictions on %0% Setup Permissions on %0% Change sort order for %0% Create Content Template based on %0% @@ -2303,10 +2302,17 @@ To manage your website, simply open the Umbraco back office and start adding con Name Add new row View more options - Has translation - Missing translation - Dictionary items - Perform action %0% on the %1% node + Search the Umbraco backoffice + Search for content nodes, media nodes etc. across the backoffice. + When autocomplete results are available, press up and down arrows, or use the tab key and use the enter key to select. + Path: + Found in + Has translation + Missing translation + Dictionary items + Select one of the options to edit the node. + Perform action %0% on the %1% node + Add image caption References @@ -2451,7 +2457,7 @@ To manage your website, simply open the Umbraco back office and start adding con Hours of Umbraco training videos are only a click away Want to master Umbraco? Spend a couple of minutes learning some best practices by watching one of these videos about using Umbraco. And visit umbraco.tv for even more Umbraco videos

    +

    Want to master Umbraco? Spend a couple of minutes learning some best practices by watching one of these videos about using Umbraco. And visit umbraco.tv for even more Umbraco videos

    ]]>
    To get you started @@ -2462,27 +2468,27 @@ To manage your website, simply open the Umbraco back office and start adding con Find out more in the Documentation section of Our Umbraco + Read more about working with the items in Settings in the Documentation section of Our Umbraco ]]> Community Forum + Ask a question in the Community Forum ]]> tutorial videos (some are free, some require a subscription) + Watch our tutorial videos (some are free, some require a subscription) ]]> productivity boosting tools and commercial support + Find out about our productivity boosting tools and commercial support ]]> training and certification opportunities + Find out about real-life training and certification opportunities ]]> diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/es.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/es.xml index 202e479f48..2f4fac3450 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/es.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/es.xml @@ -504,11 +504,11 @@ Margen interno Insertar Instalar - Inválido + Inválido Justificar Etiqueta Idioma - Último + Último Diseño Cargando Bloqueado @@ -520,7 +520,7 @@ Mensaje Mover Nombre - Nuevo + Nuevo Próximo No de @@ -625,7 +625,7 @@ Configuración de la base de datos instalar para instalar %0% la base de datos de Umbraco]]> Próximo para continuar]]> - ¡No se ha encontrado ninguna base de datos! Mira si la información en la cadena de conexión del “web.config” es correcta.

    Para continuar, edita el "web.config" (bien sea usando Visual Studio o tu editor de texto preferido), ve al final del archivo y añade la cadena de conexión para la base de datos con el nombre (key) "umbracoDbDSN" y guarda el archivo.

    Pincha en reintentar cuando hayas terminado.
    Pincha aquí para mayor información de como editar el web.config (en inglés)

    ]]>
    + ¡No se ha encontrado ninguna base de datos! Mira si la información en la cadena de conexión del “web.config” es correcta.

    Para continuar, edita el "web.config" (bien sea usando Visual Studio o tu editor de texto preferido), ve al final del archivo y añade la cadena de conexión para la base de datos con el nombre (key) "umbracoDbDSN" y guarda el archivo.

    Pincha en reintentar cuando hayas terminado.
    Pincha aquí para mayor información de como editar el web.config (en inglés)

    ]]>
    Por favor, contacta con tu ISP si es necesario. Si estás realizando la instalación en una máquina o servidor local, quizás necesites información de tu administrador de sistemas.]]> Pincha en actualizar para actualizar la base de datos a Umbraco %0%

    Ningún contenido será borrado de la base de datos y seguirá funcionando después de la actualización

    ]]>
    Pincha en Próximo para continuar. ]]> @@ -652,7 +652,7 @@ Configurando los permisos de directorios Umbraco necesita permisos de lectura/escritura en algunos directorios para poder almacenar archivos tales como imágenes y PDFs. También almacena datos en la caché para mejorar el rendimiento de tu sitio web Quiero empezar de cero - aprende cómo). Todavía podrás elegir instalar Runway más adelante. Por favor ve a la sección del Desarrollador y elige Paquetes.]]> + aprende cómo). Todavía podrás elegir instalar Runway más adelante. Por favor ve a la sección del Desarrollador y elige Paquetes.]]> Acabas de configurar una nueva plataforma Umbraco. ¿Qué deseas hacer ahora? Se ha instalado Runway Esta es nuestra lista de módulos recomendados, selecciona los que desees instalar, o mira la lista completa de módulos ]]> @@ -696,7 +696,7 @@ Resplandeciente sábado Iniciar sesión La sesión ha caducado - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    ¿Olvidaste tu contraseña? Enviaremos un email a la dirección especificada con un enlace para restaurar tu contraseña Un email con instrucciones para restaurar tu contraseña será enviado a la dirección especificada si ésta está registrada. diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/fr.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/fr.xml index 04752bf478..498245c441 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/fr.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/fr.xml @@ -812,7 +812,7 @@

    Pour poursuivre, veuillez éditer le fichier "web.config" (avec Visual Studio ou votre éditeur de texte favori), scroller jusqu'en bas, ajouter le "connection string" pour votre base de données dans la ligne avec la clé "umbracoDbDSN" et sauvegarder le fichier.

    Cliquez sur le bouton Réessayer lorsque cela est fait. -
    +
    Plus d'informations sur l'édition du fichier web.config ici.

    ]]> Veuillez contacter votre fournisseur de services internet si nécessaire. @@ -860,7 +860,7 @@ Je veux démarrer "from scratch" Apprenez comment) + (Apprenez comment) Vous pouvez toujours choisir d'installer Runway plus tard. Pour cela, allez dans la section "Développeur" et sélectionnez "Packages". ]]> Vous venez de mettre en place une plateforme Umbraco toute nette. Que voulez-vous faire ensuite ? @@ -928,7 +928,7 @@ Pour gérer votre site, ouvrez simplement le backoffice Umbraco et commencez à Connectez-vous ci-dessous Identifiez-vous avec La session a expiré - © 2001 - %0%
    Umbraco.com

    ]]>
    + © 2001 - %0%
    Umbraco.com

    ]]>
    Mot de passe oublié? Un email contenant un lien pour ré-initialiser votre mot de passe sera envoyé à l'adresse spécifiée Un email contenant les instructions de ré-initialisation de votre mot de passe sera envoyée à l'adresse spécifiée si elle correspond à nos informations. @@ -1370,6 +1370,7 @@ Pour gérer votre site, ouvrez simplement le backoffice Umbraco et commencez à Les erreurs de validation doivent être corrigées avant de pouvoir sauvegarder l'élément Echec Sauvegardé + Sauvegardé. Veuillez rafraîchir votre navigateur pour voir les changements Permissions utilisateur insuffisantes, l'opération n'a pas pu être complétée Annulation L'opération a été annulée par une extension tierce @@ -2323,7 +2324,7 @@ Pour gérer votre site, ouvrez simplement le backoffice Umbraco et commencez à Des heures de vidéos de formation Umbraco ne sont qu'à un clic d'ici Vous voulez maîtriser Umbraco? Passez quelques minutes à apprendre certaines des meilleures pratiques en regardant une de ces vidéos à propos de l'utilisation d'Umbraco. Et visitez umbraco.tv pour encore plus de vidéos Umbraco

    +

    Vous voulez maîtriser Umbraco? Passez quelques minutes à apprendre certaines des meilleures pratiques en regardant une de ces vidéos à propos de l'utilisation d'Umbraco. Et visitez umbraco.tv pour encore plus de vidéos Umbraco

    ]]>
    Pour démarrer @@ -2334,27 +2335,27 @@ Pour gérer votre site, ouvrez simplement le backoffice Umbraco et commencez à En savoir plus dans la section Documentation de Our Umbraco + Lisez-en plus sur la façon de travailler avec les éléments dans la section Settings dans la section Documentation de Our Umbraco ]]> Community Forum + Posez une question dans le Community Forum ]]> tutoriels vidéos (certains sont gratuits, certains nécessitent un abonnement) + Regardez nos tutoriels vidéos (certains sont gratuits, certains nécessitent un abonnement) ]]> outils d'amélioration de productivité et notre support commercial + Découvrez nos outils d'amélioration de productivité et notre support commercial ]]> formations et certifications + Découvrez nos possibilités de formations et certifications ]]> diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/he.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/he.xml index e100cb4301..fcc9cfb8ad 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/he.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/he.xml @@ -361,8 +361,8 @@

    To proceed, please edit the "web.config" file (using Visual Studio or your favourite text editor), scroll to the bottom, add the connection string for your database in the key named "UmbracoDbDSN" and save the file.

    Click the retry button when - done.
    - More information on editing web.config here.

    ]]>
    + done.
    + More information on editing web.config here.

    ]]> Please contact your ISP if necessary. If you're installing on a local machine or server you might need information from your system administrator.]]> @@ -409,7 +409,7 @@ אני רוצה להתחיל מאתר ריק learn how) + (learn how) You can still choose to install Runway later on. Please go to the Developer section and choose Packages. ]]> סיימת להתקין את מערכת אומברקו, מה ברצונך לעשות כעת? @@ -467,7 +467,7 @@ To manage your website, simply open the Umbraco back office and start adding con יש לבצע חידוש פעילות על מנת לשמור על התוכן - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    לוח הבקרה diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/it.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/it.xml index c7842ab5ff..812da01703 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/it.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/it.xml @@ -359,7 +359,7 @@ installa per installare il database Umbraco %0% ]]> Avanti per proseguire.]]> Database non trovato! Perfavore, controlla che le informazioni della stringa di connessione nel file "web.config" siano corrette.

    -

    Per procedere, edita il file "web.config" (utilizzando Visual Studio o l'editor di testo che preferisci), scorri in basso, aggiungi la stringa di connessione per il database chiamato "umbracoDbDSN" e salva il file.

    Clicca il tasto riprova quando hai finito.
    Maggiori dettagli per la modifica del file web.config qui.

    ]]>
    +

    Per procedere, edita il file "web.config" (utilizzando Visual Studio o l'editor di testo che preferisci), scorri in basso, aggiungi la stringa di connessione per il database chiamato "umbracoDbDSN" e salva il file.

    Clicca il tasto riprova quando hai finito.
    Maggiori dettagli per la modifica del file web.config qui.

    ]]> Premi il tasto aggiorna per aggiornare il database ad Umbraco %0%

    Non preoccuparti, il contenuto non verrà perso e tutto continuerà a funzionare dopo l'aggiornamento!

    ]]>
    Premi il tasto Avanti per continuare.]]> @@ -386,7 +386,7 @@ - Guarda come) Puoi anche installare eventuali Runway in un secondo momento. Vai nella sezione Developer e scegli Pacchetti.]]> + Guarda come) Puoi anche installare eventuali Runway in un secondo momento. Vai nella sezione Developer e scegli Pacchetti.]]> Runway è installato Riconnetti adesso per salvare il tuo lavoro - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Dashboard diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ja.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ja.xml index 161a6fa0dd..80aad2c301 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ja.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ja.xml @@ -493,7 +493,7 @@

    続行するには"web.config"ファイルを編集(Visual Studioないし使い慣れたテキストエディタで)し、下の方にスクロールし、"umbracoDbDSN"という名前のキーでデータベースの接続文字列を追加して保存します。

    再施行ボタンをクリックして - 続けます。
    + 続けます。
    より詳細にはこちらの web.config を編集します。

    ]]> 必要ならISPに連絡するなどしてみてください。 @@ -541,7 +541,7 @@ スクラッチから始めたい どうしたらいいの?) + (どうしたらいいの?) 後からRunwayをインストールする事もできます。そうしたくなった時は、Developerセクションのパッケージへどうぞ。 ]]> Umbracoプラットフォームのクリーンセットアップが完了しました。この後はどうしますか? @@ -608,7 +608,7 @@ Runwayをインストールして作られた新しいウェブサイトがど ハッピー土曜日 ウェブサイトにログインします。 セッションタイムアウトしました。 - © 2001 - %0%
    umbraco.org

    ]]>
    + © 2001 - %0%
    umbraco.org

    ]]>
    ダッシュボード diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ko.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ko.xml index dc2a2c8212..02f50e73b2 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ko.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ko.xml @@ -357,8 +357,8 @@ 데이터베이스를 찾을 수 없습니다. “web.config”파일의 "connection string"이 바르게 설정되었는지 확인하세요.

    "web.config" 파일에 맨아래에 ,키네임을 "UmbracoDbDSN"로 하여 사용하시는 데이터베이스의 connection string 정보를 입력하시고 파일을 저장하세요.

    - 완료 후재시도버튼을 누르세요.
    - web.config의 더많은 정보는 여기에 있습니다.

    ]]>
    + 완료 후재시도버튼을 누르세요.
    + web.config의 더많은 정보는 여기에 있습니다.

    ]]>
    필요하시다면 사용하시는 ISP쪽에 문의하시기 바랍니다.. 로컬 머신이나 서버에 설치되어 있다면 해당 시스템 관리자에게 문의하시기 바랍니다.]]> @@ -395,7 +395,7 @@ scratch를 시작하기 원합니다. learn how) + (learn how) Runway설치를 나중에 실행하실 수 있습니다. 개발도구 부분에서 패키지를 선택하세요. ]]> 여러분은 Umbraco 플랫폼 설치를 완료하였습니다. 다음엔 어떤 작업을 원하십니까? @@ -452,7 +452,7 @@ TRANSLATE ME: 'Renew now to save your work' - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    대시보드 diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nb.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nb.xml index 86bf8fa6f6..cc0b46f200 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nb.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nb.xml @@ -437,7 +437,7 @@ Databasekonfigurasjon installer-knappen for å installere Umbraco %0% databasen]]> Neste for å fortsette.]]> - Databasen ble ikke funnet! Vennligst sjekk at informasjonen i "connection string" i "web.config"-filen er korrekt.

    For å fortsette, vennligst rediger "web.config"-filen (bruk Visual Studio eller din favoritteditor), rull ned til bunnen, og legg til tilkoblingsstrengen for din database i nøkkelen "umbracoDbDSN" og lagre filen.

    Klikk prøv på nytt når du er ferdig.
    Mer informasjon om redigering av web.config her.

    ]]>
    + Databasen ble ikke funnet! Vennligst sjekk at informasjonen i "connection string" i "web.config"-filen er korrekt.

    For å fortsette, vennligst rediger "web.config"-filen (bruk Visual Studio eller din favoritteditor), rull ned til bunnen, og legg til tilkoblingsstrengen for din database i nøkkelen "umbracoDbDSN" og lagre filen.

    Klikk prøv på nytt når du er ferdig.
    Mer informasjon om redigering av web.config her.

    ]]>
    Vennligst kontakt din ISP om nødvendig. Hvis du installerer på en lokal maskin eller server, må du kanskje skaffe informasjonen fra din systemadministrator.]]> Trykk på knappen oppgrader for å oppgradere databasen din til Umbraco %0%

    Ikke vær urolig - intet innhold vil bli slettet og alt vil fortsette å virke etterpå!

    ]]>
    Trykk Neste for å fortsette.]]> @@ -464,7 +464,7 @@ Konfigurerer mappetillatelser Jeg ønsker å starte fra bunnen. - lær hvordan) Du kan fortsatt velge å installere Runway senere. Vennligst gå til Utvikler-seksjonen og velg Pakker.]]> + lær hvordan) Du kan fortsatt velge å installere Runway senere. Vennligst gå til Utvikler-seksjonen og velg Pakker.]]> Du har akkurat satt opp en ren Umbraco plattform. Hva vil du gjøre nå? Runway er installert Dette er vår liste av anbefalte moduler- Kryss av de du ønsker å installere, eller se denfulle listen av moduler ]]> @@ -509,7 +509,7 @@ Logg på nedenfor Logg på med Din sesjon er utløpt - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Skrivebord diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nl.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nl.xml index 140cd095ff..8bb21ee97f 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nl.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/nl.xml @@ -1,4 +1,4 @@ - + The Umbraco community @@ -8,13 +8,18 @@ Beheer domeinnamen Documentgeschiedenis Node bekijken - Wijzig documenttype + Documenttype wijzigen + Datatype aanpassen Kopiëren Nieuw + Export Nieuwe package + Groep maken Verwijderen Uitschakelen + Instellingen wijzigen Prullenbak leegmaken + Inschakelen Documenttype exporteren Documenttype importeren Package importeren @@ -27,20 +32,62 @@ Depubliceren Nodes opnieuw inladen Herpubliceer de site - Stel rechten voor pagina %0% in + Verwijder + Hernoem Herstellen + Stel rechten voor pagina %0% in + Kies waar u wilt kopiëren + Kies waar u wilt verplaatsen + naar de boomstructuur hieronder + Kies waar u de geselecteerde item(s) naartoe wilt kopiëren + Kies waar u de geselecteerde item(s) naartoe wilt verplaatsen + was verplaatst naar + was gekopieerd naar + was verwijderd Rechten Vorige versies Klaar voor publicatie Klaar voor vertalen + Groep instellen Sorteren Vertalen Bijwerken Rechten instellen Deblokkeer - Content template aanmaken + Inhoudssjabloon aanmaken Uitnodiging opnieuw versturen + + Inhoud + Administratie + Structuur + Andere + + + Toegang toestaan om cultuur- en hostnamen toe te wijzen + Toegang toestaan om het geschiedenislogboek van een node te bekijken + Toegang toestaan om een node te bekijken + Toegang toestaan om het documenttype van een node te wijzigen + Toegang toestaan om een node te kopiëren + Toegang toestaan om nodes aan te maken + Toegang toestaan om nodes te verwijderen + Toegang toestaan om een node te verplaatsen. + Toegang toestaan om openbare toegang voor een node in te stellen en te wijzigen + Toegang toestaan om een node te publiceren + Toegang toestaan om een node te depubliceren + Toegang toestaan om de machtigingen van een node te wijzigen + Toegang toestaan om een node terug te draaien naar een vorige status + Toegang toestaan om een node te verzenden voor goedkeuring voor publicatie + Toegang toestaan om een node te verzenden voor vertaling + Toegang toestaan om de volgorde van nodes te wijzigen + Toegang toestaan om een node te vertalen + Toegang toestaan om een node op te slaan + Toegang toestaan om Inhoudssjabloon aan te maken + + + Inhoud + Info + Toegang geweigerd. Nieuw domein toevoegen @@ -56,6 +103,10 @@ Domein '%0%' is bijgewerkt Bewerk huidige domeinen Overerven + + + Cultuur of erf de cultuur over van de oudernodes. Zal ook van toepassing
    zijn op de huidige node, tenzij een domein hieronder ook van toepassing is.]]>
    @@ -63,6 +114,35 @@ Tonen voor + Inhoud verwijderd + Inhoud gedepubliceerd + Inhoud gedepubliceerd voor talen: %0% + Inhoud gepubliceerd + Inhoud gepubliceerd voor talen: %0% + Inhoud bewaard + Inhoud bewaard voor talen: %0% + Inhoud verplaatst + Inhoud gekopieerd + Inhoud teruggezet + Inhoud verzonden voor publicatie + Inhoud verzonden voor publicatie voor talen: %0% + Sorteer onderliggende items door de gebruiker uitgevoerd + %0% + Kopieer + Publiceer + Publiceer + Verplaats + Bewaar + Bewaar + Verwijder + Depubliceer + Depubliceer + Terugzetten + Verzenden voor publicatie + Verzenden voor publicatie + Sorteer + Aangepast + Geschiedenis (alle varianten) Selectie ongedaan maken @@ -84,18 +164,34 @@ Nummering Macro invoegen Afbeelding invoegen + Publiceren en sluiten + Publiceren met onderliggende nodes Relaties wijzigen Terug naar overzicht Opslaan + Opslaan en sluiten Opslaan en publiceren + Opslaan en plannen Opslaan en verzenden voor goedkeuring - Sla list view op - voorbeeld bekijken - Voorbeeld bekijken is uitgeschakeld omdat er geen template is geselecteerd + Lijstweergave opslaan + Planning + Voorbeeld + Opslaan en voorbeeld bekijken + Voorbeeld bekijken is uitgeschakeld omdat er geen sjabloon is geselecteerd Stijl kiezen Stijlen tonen Tabel invoegen + Models genereren en sluiten Opslaan en models genereren + Ongedaan maken + Herhalen + Terugzetten + Tag verwijderen + Annuleren + Bevestigen + Meer publicatie opties + Indienen + Indienen en sluiten Om het documenttype voor de geselecteerde inhoud te wijzigen, selecteert u eerst uit de lijst van geldige types voor deze locatie. @@ -107,7 +203,7 @@ Documenttype gewijzigd Eigenschappen toewijzen Toewijzen aan eigenschap - Nieuwe template + Nieuw sjabloon Nieuw type geen Inhoud @@ -117,6 +213,12 @@ Toewijzen van eigenschappen kan niet worden afgerond, omdat één of meer eigenschappen meer dan één toewijzing hebben. Alleen alternatieve types geldig voor de huidige locatie worden weergegeven. + + Het maken van een map onder de bovenliggende map met ID %0% is mislukt + Het maken van een map onder de bovenliggende map met de naam %0% is mislukt + De mapnaam mag geen ongeldige tekens bevatten. + Verwijderen van item is mislukt: %0% + Is gepubliceerd Over deze pagina @@ -137,23 +239,35 @@ Laatst gepubliceerd op Er zijn geen items om weer te geven Er zijn geen items om weer te geven. + Er zijn geen subitems toegevoegd + Er zijn geen leden toegevoegd Mediatype Link naar media item(s) Ledengroep Rol Ledentype + Er zijn geen wijzigingen aangebracht Geen datum gekozen Pagina Titel + Dit media item heeft geen link + Inhoud kan niet worden toegevoegd aan dit item Eigenschappen - Dit document is gepubliceerd maar niet zichtbaar omdat de bovenliggende node '%0%' niet gepubliceerd is + Dit document is gepubliceerd maar niet zichtbaar omdat de bovenliggende pagina '%0%' niet gepubliceerd is + Deze cultuur is gepubliceerd maar is niet zichtbaar omdat het niet gepubliceerd is op de bovenliggende pagina '%0%' Dit document is gepubliceerd, maar het staat niet in de cache (interne serverfout) Kan de URL niet ophalen - Dit document is gepubliceerd, maar de URL conflicteert met %0% + Dit document is gepubliceerd maar de URL conflicteert met %0% + Dit document is gepubliceerd maar de URL kan niet worden gerouteerd Publiceren + Gepubliceerd + Gepubliceerd (hangende wijzigingen) Publicatiestatus + %0% en alle onderliggende content items en maak daarmee de inhoud openbaar.]]> + Publiceren op Depubliceren op Verwijderdatum + Datum instellen De sorteervolgorde is gewijzigd Om nodes te sorteren, sleep de nodes of klik op één van de kolomtitels. Je kan meerdere nodes tegelijk selecteren door de "shift"- of "control"knop in te drukken tijdens het selecteren. Statistieken @@ -161,43 +275,119 @@ Alternatieve tekst (optioneel) Type Depubliceren + Concept + Niet gemaakt Laatst gewijzigd Date/time this document was edited Bestand(en) verwijderen + Klik hier om de afbeelding van het media item te verwijderen + Klik hier om het bestand van het media item te verwijderen Link naar het document Lid van groep(en) Geen lid van groep(en) Subitems Doel Dit betekend de volgende tijd op de server: - Wat houd dit in?]]> + Wat houd dit in?]]> Ben je er zeker van dat je dit item wilt verwijderen? + Ben je zeker dat je alle items wilt verwijderen? Eigenschap %0% gebruikt editor %1% welke niet wordt ondersteund door Nested Content. + Er zijn geen content types geconfigureerd voor deze eigenschap. + Element type toevoegen + Selecteer een element type + Selecteer de groep waarvan je de eigenschappen wil tonen. Indien je niets selecteert, wordt de eerste groep van het elementtype gebruikt. + Voer een angular expressie in om te evalueren tegen de naam van elk item. Gebruik + om de itemindex weer te geven Voeg nog een tekstvak toe Verwijder dit tekstvak Content root + Inclusief niet-gepubliceerde inhoudsitems. Deze waarde is verborgen. Indien u toegang nodig heeft om deze waarde te bekijken, neem dan contact op met uw websitebeheerder. Deze waarde is verborgen + Welke talen wil je publiceren? Alle talen met inhoud zijn opgeslagen! + Welke talen wil je publiceren? + Welke talen wil je opslaan? + Alle talen met inhoud zijn opgeslagen bij het aanmaken! + Welke talen wil je ter goedkeuring verzenden? + Welke talen wil je plannen? + Selecteer de talen om te depubliceren. Een verplichte taal depubliceren zal alle talen depubliceren. + Gepubliceerde talen + Niet-gepubliceerde talen + Ongewijzigde talen + Deze talen zijn nog niet gemaakt + + Alle nieuwe varianten worden opgeslagen. + Welke varianten wil je publiceren? + Kies welke varianten u wilt opslaan. + Kies varianten om ter goedkeuring te verzenden. + Geplande publicatie instellen... + Selecteer de varianten om te depubliceren. Een verplichte taal depubliceren zal alle varianten depubliceren. + De volgende varianten zijn vereist om te kunnen publiceren: + + We zijn niet klaar om te publiceren + Klaar om te publiceren? + Klaar om op te slaan? + Ter goedkeuring verzenden + Selecteer de datum en tijd om het content item te publiceren en/of depubliceren. + Maak nieuw + Plakken vanaf het klembord + Dit item is in de prullenbak + + + Nieuw Inhoudssjabloon aanmaken voor '%0%' + Leeg + Selecteer een Inhoudssjabloon + Inhoudssjabloon aangemaakt + Inhoudssjabloon is aangemaakt voor '%0%' + Er bestaat al een Inhoudssjabloon met dezelfde naam + Een inhoudssjabloon is voorgedefinieerde inhoud die een editor kan selecteren om te gebruiken als basis voor het maken van nieuwe inhoud Klik om te uploaden Of klik hier om bestanden te kiezen - Dit bestand heeft niet het juiste file-type. Dit bestand kan niet geupload worden. + Je kan bestanden hier naartoe slepen om te uploaden. + Kan dit bestand niet uploaden, het heeft niet het juiste bestandstype. Maximale bestandsgrootte is + Media root + Het is niet gelukt om de media te verplaatsen + De bovenliggende map en de doelmap kunnen niet hetzelfde zijn + Kan media niet kopiëren + Kan de map onder de bovenliggende map met id %0% niet aanmaken + Kan de map met id %0% niet hernoemen + Sleep en zet je bestand(en) neer in dit gebied + Upload is niet toegelaten in deze locatie. - Maak nieuwe member aan - Alle Members + Maak nieuw lid aan + Alle leden + Ledengroepen hebben geen extra eigenschappen om te bewerken. Waar wil je de nieuwe %0% aanmaken? Aanmaken onder + Selecteer een documenttype waarvoor je een Inhoudssjabloon wil maken + Voer een mapnaam in Kies een type en een titel "Documenttypes".]]> + Documenttypes in de sectie Instellingen.]]> + De geselecteerde pagina in de boomstructuur laat geen nieuwe onderliggende paginas toe. + Rechten aanpassen voor dit documenttype + Nieuw documenttype aanmaken + Documenttypes in de sectie Instellingen, de optie Toestaan op root-niveau onder Rechten.]]> "Mediatypes".]]> - Document Type zonder template + De geselecteerde media in de boomstructuur laat niet toe dat er onderliggende media aangemaakt wordt. + Rechten aanpassen voor dit mediatype + Documenttype zonder sjabloon Nieuwe map - Nieuw data type + Nieuw datatype + Nieuw JavaScript bestand + Nieuwe lege partial view + Nieuwe partial view macro + Nieuwe partial view van fragment + Nieuwe partial view macro van fragment + Nieuwe partial view macro (zonder macro) + Nieuw style sheet bestand + Nieuw Rich Text Editor style sheet bestand Open je website @@ -212,8 +402,11 @@ Blijf op deze pagina Negeer wijzigingen Wijzigingen niet opgeslagen - Weet je zeker dat deze pagina wilt verlaten? - er zijn onopgeslagen wijzigingen - Depubliceren zal deze pagina en alle onderliggende paginas verwijderen van de site. + Weet je zeker dat deze pagina wilt verlaten? Er zijn onopgeslagen wijzigingen + Publiceren maakt de geselecteerde items zichtbaar op de site. + Depubliceren zal de geselecteerde items en alle onderliggende items verwijderen van de site. + Depubliceren zal deze pagina en alle onderliggende pagina's verwijderen van de site. + Wijzigingen niet opgeslagen. Aanpassingen aan het Documenttype zullen de wijzigingen ongedaan maken. Done @@ -241,16 +434,20 @@ Link Titel Link + Anker / querystring Naam - Beheer domeinnamen Sluit dit venster Weet je zeker dat je dit wilt verwijderen Weet je zeker dat je dit wilt uitschakelen + Weet u zeker dat u wilt verwijderen + %0% wil verwijderen]]> + %0% wil verwijderen]]> Weet je het zeker? Weet je het zeker? Knippen Pas woordenboekitem aan Taal aanpassen + Geselecteerde media bewerken Lokale link invoegen Karakter invoegen Voeg grafische titel in @@ -258,24 +455,30 @@ Link invoegen Klik om een Macro toe te voegen Tabel invoegen + Dit zal de taal verwijderen + De cultuur veranderen voor een taal kan een langdurige operatie zijn en zal ertoe leiden dat de inhoudscache en indexen opnieuw worden opgebouwd Laatst aangepast op Link Interne link: Plaats een hekje (“#”) voor voor interne links. In nieuw venster openen? + Macro instellingen Deze macro heeft geen eigenschappen die u kunt bewerken Plakken Bewerk rechten voor + Rechten instellen voor + Rechten instellen voor %0% voor gebruikersgroepf %1% + Selecteer de gebruikersgroepen waarvoor u de rechten wilt instellen De items worden nu uit de prullenbak verwijderd. Sluit dit venster niet terwijl de actie nog niet voltooid is. De prullenbak is nu leeg. Als items worden verwijderd uit de prullenbak, zijn ze voorgoed verwijderd. - regexlib.com ondervindt momenteel problemen waarover we geen controle hebben. Onze excuses voor het ongemak.]]> + regexlib.com ondervindt momenteel problemen waarover we geen controle hebben. Onze excuses voor het ongemak.]]> Zoek naar een reguliere expressie om validatie aan een formulierveld toe te voegen. Voorbeeld: 'email', 'postcode', 'URL'. Verwijder Macro Verplicht veld Site is opnieuw geïndexeerd De site is opnieuw gepubliceerd - De cache zal worden vernieuwd. Alle gepubliceerde inhoud zal worden ge-update, terwijl ongepubliceerde inhoud ongepubliceerd zal blijven. + De cache zal worden vernieuwd. Alle gepubliceerde inhoud zal worden bijgewerkt, terwijl ongepubliceerde inhoud ongepubliceerd zal blijven. Aantal kolommen Aantal regels Klik op de afbeelding voor volledige grootte @@ -283,19 +486,30 @@ Toon cache item Relateer aan origineel Onderliggende nodes meenemen - De vriendelijkste community + De vriendelijkste gemeenschap Link naar pagina Opent het gelinkte document in een nieuw venster of tab Link naar media + Selecteer content start node Selecteer media + Selecteer media type Selecteer icoon Selecteer item Selecteer link Selecteer macro Selecteer content + Selecteer content type + Selecteer media start node Selecteer member - Selecteer member group + Selecteer lid groep + Selecteer lid type + Selecteer node + Selecteer secties + Selecteer gebruiker + Selecteer gebruikers + Geen iconen gevonden Er zijn geen parameters voor deze macro + Er zijn geen macro's beschikbaar om in te voegen Externe login providers Error details Stacktrace @@ -304,15 +518,53 @@ De-Link je account Selecteer editor + Selecteer configuratie + Selecteer fragment + Dit zal de node en al zijn talen verwijderen. Als je slechts één taal wil verwijderen, moet je de node in die taal depubliceren. + %0% verwijderen.]]> + %0% verwijderen van de %1% groep]]> + Ja, verwijderen + + + Er zijn geen woordenboekitems. + ]]> Cultuurnaam + ]]> + Woordenboek overzicht + + + Ingestelde Zoekers + Toont eigenschappen en hulpmiddelen voor elke geconfigureerde Zoeker (bijv. zoals een multi-indexzoeker) + Veldwaarden + Gezondheidsstatus + De gezondheidsstatus van de index en of het kan gelezen worden + Indexeerders + Index info + De eigenschappen oplijsten van de index + Beheer de indexen van Examine + Bekijk de details van elke index en gebruik hulpmiddelen voor het beheer er van + Index opnieuw bouwen + + Afhankelijk van hoeveel inhoud er op je site staat, kan dit even duren.
    + Het wordt niet aanbevolen om een index opnieuw op te bouwen terwijl er veel verkeer op de website is of wanneer editors inhoud bewerken. + ]]> +
    + Zoekers + Zoek in de index en bekijk de resultaten + Hulpmiddelen + Hulpmiddelen om de index te beheren + velden + De index kan niet gelezen worden en moet opnieuw worden gebouwd + Het proces duurt langer dan verwacht, controleer het Umbraco logboek om te kijken of er geen fouten waren tijdens deze operatie + Deze index kan niet opnieuw worden opgebouwd want het heeft geen toegewezen + IIndexPopulator Typ jouw gebruikersnaam @@ -320,30 +572,54 @@ Bevestig jouw wachtwoord Benoem de %0%... Typ een naam... + Voer een e-mailadres in + Voer een gebruikersnaam in... Label... Voer een omschrijving in... Typ om te zoeken... Typ om te filteren... - Typ om tags toe te voegen (druk op enter na elke tag)... - Voer jouw email in - Jouw gebruikersnaam is meestal jouw email + Typ om tags toe te voegen (druk op Enter na elke tag)... + Voer jouw e-mailadres in + Voer een bericht in ... + Jouw gebruikersnaam is meestal jouw e-mailadres + #value of ?key=value + Voer een alias in... + Alias genereren... + Item aanmaken + Bewerken + Naam Maak een aangepaste lijstweergave Verwijder aangepaste lijstweergave + Een content type, media type of member type met deze alias bestaat al + + + Hernoemd + Voer een nieuwe mapnaam in + %0% is hernoemd naar %1% Prevalue toevoegen - Datebase datatype + Database datatype Data Editor GUID Render control - Buttons + Knoppen Geavanceerde instellingen inschakelen voor Context menu inschakelen Maximum standaard grootte van afbeeldingen Gerelateerde stylesheets Toon label Breedte en hoogte + Alle eigenschap types & eigenschap data + die dit datatype gebruiken zullen permanent verwijderd worden, bevestig dat u deze ook wilt verwijderen + Ja, verwijderen + en alle eigenschap types & eigenschap data die dit datatype gebruiken + Selecteer een map om te verplaatsen + naar in de boomstructuur hieronder + werd eronder verplaatst + %0% te verwijderen zullen alle eigenschappen en de data verwijderd worden van de volgende items:]]> + Ik begrijp dat deze actie alle eigenschappen en data zal verwijderen die gebaseerd is op dit datatype. Je data is opgeslagen, maar voordat je deze pagina kunt publiceren moet je eerst aan paar problemen oplossen: @@ -373,8 +649,11 @@ Geen actieve stijlen beschikbaar Plaats de cursor links van de twee cellen die je wilt samenvoegen Je kunt een cel die is samengevoegd niet delen + Deze eigenschap is ongeldig + Eigenschap '%0%' gebruikt editor '%1%' die niet ondersteund wordt in Element Types. + Opties Over Actie Acties @@ -383,19 +662,24 @@ Alles Weet je het zeker? Terug - Border + Terug naar overzicht + Rand bij - Cancel + Annuleren Cel marge Kies - Sluit + Wissen + Sluiten Sluit venster Comment Bevestig + Beperken Verhoudingen behouden - Ga verder - Copy + Inhoud + Doorgaan + Kopiëren Aanmaken + Sectie bijsnijden Database Datum Standaard @@ -403,27 +687,43 @@ Verwijderd Aan het verwijderen... Ontwerp + Woordenboek Afmetingen + Gooi weg Omlaag Download - Bewerk + Bewerken Bewerkt Elementen - Email + E-mail Fout - Vind + Veld + Zoeken + Eerste + Focus punt + Algemeen + Groepen + Groep Hoogte Help + Verbergen + Geschiedenis Icoon + Id Import + Ook in onderliggende mappen zoeken + Alleen in deze map zoeken + Info Binnenste marge Invoegen Installeren Ongeldig - Justify + Uitvullen Label Taal + Laatste Layout + Links Aan het laden Gesloten Inloggen @@ -431,37 +731,50 @@ Uitloggen Macro Verplicht + Bericht Verplaats Naam Nieuw Volgende Nee of + Uit OK Open + Aan of + Sorteren op Wachtwoord Pad Een ogenblik geduld aub... Vorige Eigenschappen - Email om formulier resultaten te ontvangen + Opnieuw opbouwen + E-mail om formulier resultaten te ontvangen Prullenbak De prullenbak is leeg + Vernieuwen Overblijvend + Verwijderen Hernoem Vernieuw Verplicht + Ophalen Opnieuw proberen Rechten + Geplande publicatie Zoeken We konden helaas niet vinden wat je zocht + Er zijn geen items toegevoegd Server + Instellingen Toon Toon pagina na verzenden Grootte Sorteer + Status Verstuur + Succes Typen Typ om te zoeken... onder @@ -489,23 +802,37 @@ huidig Embed geselecteerd + Andere + Artikels + Videos + Installeren Blauw Groep toevoegen - Property toevoegen + Eigenschap toevoegen Editor toevoegen - Template toevoegen + Sjabloon toevoegen Child node toevoegen Child toevoegen - Data type bewerken + Datatype bewerken Secties navigeren - Shortcuts - Toon shortcuts - Toggle lijstweergave - Toggle toestaan op root-niveau + Snelkoppeling + Toon snelkoppelingen + Lijstweergave in/uitschakelen + Toestaan op root-niveau in/uitschakelen + Regel in/uit commentaar zetten + Regel verwijderen + Kopieer Regels Omhoog + Kopieer Regels Omlaag + Verplaats Regels Omhoog + Verplaats Regels Omlaag + Algemeen + Editor + Cultuur varianten toestaan in/uitschakelen + Segmentatie toestaan in/uitschakelen Achtergrondkleur @@ -524,7 +851,7 @@ Database configuratie installeren om de Umbraco %0% database te installeren]]> Volgende om door te gaan.]]> - De database kon niet gevonden worden! Gelieve na te kijken of de informatie in de "connection string" van het "web.config" bestand correct is.

    Om door te gaan, gelieve het "web.config" bestand aan te passen (met behulp van Visual Studio of je favoriete tekstverwerker), scroll in het bestand naar beneden, voeg de connection string voor je database toe in de key met naam "umbracoDbDSN" en sla het bestand op.

    Klik op de knop opnieuw proberen als je hiermee klaar bent.
    Meer informatie over het aanpassen van de web.config vind je hier.

    ]]>
    + De database kon niet gevonden worden! Gelieve na te kijken of de informatie in de "connection string" van het "web.config" bestand correct is.

    Om door te gaan, gelieve het "web.config" bestand aan te passen (met behulp van Visual Studio of je favoriete tekstverwerker), scroll in het bestand naar beneden, voeg de connection string voor je database toe in de key met naam "umbracoDbDSN" en sla het bestand op.

    Klik op de knop opnieuw proberen als je hiermee klaar bent.
    Meer informatie over het aanpassen van de web.config vind je hier.

    ]]>
    Gelieve contact op te nemen met je ISP indien nodig. Wanneer je installeert op een lokale computer of server, dan heb je waarschijnlijk informatie nodig van je systeembeheerder.]]> Klik de upgrade knop om je database te upgraden naar Umbraco %0%

    Maak je geen zorgen - er zal geen inhoud worden gewist en alles blijft gewoon werken!

    ]]>
    Klik Volgende om verder te gaan.]]> @@ -553,7 +880,7 @@ Machtigingen worden aangepast Umbraco heeft write/modify toegang nodig op bepaalde mappen om bestanden zoals plaatjes en PDF's op te slaan. Het slaat ook tijdelijke data (ook bekend als 'de cache') op om de snelheid van je website te verbeteren. Ik wil met een lege website beginnen - leer hoe). Je kunt er later alsnog voor kiezen om Runway te installeren. Ga dan naar de Ontwikkelaar sectie en kies Packages.]]> + leer hoe). Je kunt er later alsnog voor kiezen om Runway te installeren. Ga dan naar de Ontwikkelaar sectie en kies Packages.]]> Je hebt zojuist een blanco Umbraco platform geinstalleerd. Wat wil je nu doen? Runway is geinstalleerd Dit is onze lijst van aanbevolen modules. Vink de modules die je wilt installeren, of bekijk de volledige lijst modules]]> @@ -591,20 +918,22 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Vernieuw je sessie om je wijzigingen te behouden - Goede zondag - Fijne maandag + Fijne super zondag + Fijne manische maandag Fijne dinsdag - Fijne woensdag - Fijne donderdag - Fijne vrijdag + Fijne geweldige woensdag + Fijne donderende donderdag + Fijne funky vrijdag Fijne zaterdag log hieronder in Inloggen met Sessie is verlopen - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Wachtwoord vergeten? - Er zal een email worden gestuurd naar het emailadres van jouw account. Hierin staat een link om je wachtwoord te resetten - Een email met daarin de wachtwoord reset uitleg zal worden gestuurd als het emailadres in onze database voorkomt. + Er zal een e-mail worden gestuurd naar het e-mailadres van jouw account. Hierin staat een link om je wachtwoord te resetten + Een e-mail met daarin de wachtwoord reset uitleg zal worden gestuurd als het e-mailadres in onze database voorkomt. + Wachtwoord tonen + Wacthwoord verbergen Terug naar loginformulier Geef alsjeblieft een nieuw wachtwoord op Je wachtwoord is aangepast @@ -633,21 +962,23 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Bewerk de notificatie voor %0% + Notificatie instellingen opgeslagen voor - Hi %0%

    + ]]>
    + De volgende talen zijn gewijzigd %0% + Hi %0%

    Dit is een geautomatiseerde mail om u op de hoogte te brengen dat de taak '%1%' is uitgevoerd op pagina '%2%' @@ -675,11 +1006,65 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Dit is een bericht van uw Content Management Systeem.

    ]]>
    + De volgende talen zijn gewijzigd:

    + %0% + ]]>
    [%0%] Notificatie over %1% uitgevoerd op %2% Notificaties + Acties + Aangemaakt + Package aanmaken Kies een package op je computer door op "Bladeren" te klikken en de package te selecteren. Umbraco packages hebben meestal ".umb" of ".zip" als extensie. + Dit zal de package verwijderen + Neerzetten om te uploaden + Inclusief alle onderliggende nodes + of klik hier om een package bestand te kiezen + Package uploaden + Installeer een lokale package door het op je computer te selecteren. Installeer alleen packages van bronnen die je vertrouwt. + Nog een package uploaden + Annuleren en een andere package uploaden + Accepteren + gebruiksvoorwaarden + Pad naar bestand + Absoluut pad naar bestand (bv: /bin/umbraco.bin) + Geïnstalleerd + Geïnstalleerde packages + Lokaal installeren + Voltooien + Deze package heeft geen instellingen + Er zijn nog geen packages aangemaakt + Er zijn geen packages geïnstalleerd + 'Packages' rechtsboven in je scherm.]]> + Package Acties + Auteur URL + Package Inhoud + Package Bestanden + Icoon URL + Package installeren + Licentie + Licentie URL + Package Eigenschappen + Zoeken naar packages + Resultaten voor + We konden niets vinden voor + Probeer een ander pakket te zoeken of blader door de categorieën + Populair + Nieuwe releases + heeft + karma punten + Informatie + Eigenaar + Bijdragers + Aangemaakt + Huidige versie + .NET versie + Downloads + Likes + Compatibiliteit + Deze package is compatibel met de volgende versies van Umbraco, zoals gerapporteerd door de communityleden. Volledige compatibiliteit kan niet worden gegarandeerd voor versies die voor minder dan 100% worden gerapporteerd + Externe bronnen Auteur Documentatie Package meta data @@ -700,15 +1085,17 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je wees dus voorzichtig met verwijderen. Als je het niet zeker weet, neem dan contact op met de auteur van de package. ]]> Package versie - Package reeds geinstalleerd + Upgraden van versie + Package is reeds geinstalleerd Deze package kan niet worden geinstalleerd omdat minimaal Umbraco versie %0% benodigd is. - Aan het deinstalleren... - Aan het downloaden... - Aan het importeren... - Aan het installeren... - Aan het herstarten, een ongenblik geduld aub... - Geinstalleerd! Je browser zal nu automatisch ververst worden... - Klik op "finish" om de installatie te voltooien en de pagina te verversen. + Deïnstalleren... + Downloaden... + Importeren... + Installeren... + Aan het herstarten, een ogenblik geduld aub... + Geïnstalleerd! Je browser zal nu automatisch ververst worden... + Klik op "Voltooien" om de installatie te voltooien en de pagina te vernieuwen. + Package uploaden... Plakken met alle opmaak (Niet aanbevolen) @@ -717,24 +1104,30 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Plakken, en verwijder de opmaak (aanbevolen) - Geavanceerd: Beveilig door de Member Groups te selecteren die toegang hebben op de pagina - gebruik makend van Umbraco's member groups.]]> - Je moet eerst een membergroup maken voordat je kunt werken met role-based authentication. - Error Pagina + Groepsgebaseerde beveiliging + Als je toegang wilt verlenen aan alle leden van specifieke ledengroepen + Je moet een ledengroep maken voordat je op groep gebaseerde authenticatie kunt gebruiken + Foutpagina Gebruikt om te tonen als een gebruiker is ingelogd, maar geen rechten heeft om de pagina te bekijken - Hoe wil je de pagina beveiligen? - %0% is nu beveiligd - Beveiliging verwijderd van %0% + %0% beveiligen?]]> + %0% is nu beveiligd]]> + %0%]]> Login Pagina Kies de pagina met het login-formulier - Verwijder beveiliging + Beveiliging verwijderen + %0% wilt verwijderen?]]> Kies de pagina's die het login-formulier en de error-berichten bevatten - Kies de roles die toegang hebben tot deze pagina - Geef de gebruikersnaam en wachtwoord voor deze pagina - Eenvoudig: Beveilig door middel van gebruikersnaam en wachtwoord - Als je eenvoudige beveiliging wilt gebruiken met behulp van een enkele gebruikersnaam en wachtwoord + %0%]]> + %0%]]> + Specifieke bescherming voor leden + Als je toegang wilt verlenen aan bepaalde leden + Onvoldoende gebruikersmachtigingen om alle onderliggende documenten te publiceren + + @@ -742,15 +1135,16 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je %0% kon niet gepubliceerd worden omdat het item niet meer geldig is. ]]> - - Inclusief ongepubliceerde subitems + + + Validatie mislukt voor de vereiste taal '%0%'. Deze taal werd opgeslagen maar is niet gepubliceerd. Publicatie in uitvoering - even geduld... %0% van %1% pagina’s zijn gepubliceerd... %0% is gepubliceerd @@ -758,11 +1152,22 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Publiceer %0% en alle subitems ok om %0% te publiceren en de wijzigingen zichtbaar te maken voor bezoekers.

    Je kunt deze pagina publiceren en alle onderliggende sub-pagina's door publiceer alle subitems aan te vinken hieronder. - ]]>
    + ]]> Je hebt geen goedgekeurde kleuren geconfigureerd + + Je kan alleen items van de volgende type(s) selecteren: %0% + Je hebt een content-item geselecteerd dat op dit ogenblik verwijderd of in the prullenbak is + Je hebt content-items geselecteerd die op dit ogenblik verwijderd of in the prullenbak zijn + + + Verwijderd item + Je hebt een media-item geselecteerd dat op dit ogenblik verwijderd of in the prullenbak is + Je hebt media-items geselecteerd die op dit ogenblik verwijderd of in the prullenbak zijn + Weggegooid + Externe link toevoegen Interne link toevoegen @@ -773,9 +1178,17 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Voer de link in - Reset + Uitsnede resetten + Uitsnede opslaan + Nieuwe uitsnede toevoegen + Klaar + Aanpassingen ongedaan maken + Gebruiker gedefinieerd + Wijzigingen + Aangemaakt + Selecteer een versie om te vergelijken met de huidige versie Huidige versie Rode tekst wordt niet getoond in de geselecteerde versie, groen betekent toegevoegd]]> Document is teruggezet @@ -788,23 +1201,20 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Bewerk script-bestand - Concierge Inhoud - Courier - Ontwikkelaar - Umbraco configuratiewizard + Formulieren Media Leden - Nieuwsbrieven + Packages Instellingen - Statistieken Vertaling Gebruikers - Help - Formulieren + Rondleidingen De beste Umbraco video tutorials + Bezoek our.umbraco.com + Bezoek umbraco.tv Standaard template @@ -821,26 +1231,29 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Dit inhoudstype gebruikt als basis inhoudstype. Tabs van basis inhoudstypes worden niet getoond en kunnen alleen worden aangepast op het basis inhoudstype zelf Geen eigenschappen gedefinieerd op dit tabblad. Klik op de link "voeg een nieuwe eigenschap" aan de bovenkant om een ​​nieuwe eigenschap te creëren. - Icon toevoegen + Maak een bijpassende sjabloon + Icoon toevoegen - Sort order - Creation date + Sorteer volgorde + Aanmaakdatum Sorteren gereed. - Sleep de pagina's omhoog of omlaag om de volgorde te veranderen. Of klik op de kolom-header om alle pagina's daarop te sorteren. + Sleep de pagina's omhoog of omlaag om de volgorde te veranderen. Of klik op de kolomkop om alle pagina's daarop te sorteren. + Dit item heeft geen subitems om te sorteren Validatie Validatiefouten moeten worden opgelost voor dit item kan worden opgeslagen Mislukt - Wegens onvoldoende rechten kon deze handeling kon niet worden uitegevoerd + Opgeslagen + Opgeslagen. Gelieve uw browser te herladen om de aanpassingen te zien + Wegens onvoldoende rechten kon deze handeling kon niet worden uitgevoerd Geannuleerd - Uitvoering is g eannuleerd door de plugin van een 3e partij - Publicatie werd geannuleerd door een plugin van een 3e partij + Uitvoering is geannuleerd door de plugin van een 3e partij Eigenschappentype bestaat al Eigenschappentype aangemaakt - Data type: %1%]]> + Datatype: %1%]]> Eigenschappentype verwijderd Inhoudstype opgeslagen Tab aangemaakt @@ -851,45 +1264,58 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Stylesheet opgeslagen zonder fouten Datatype opgeslagen Woordenboek item opgeslagen - Publicatie is mislukt omdat de bovenliggende pagina niet gepubliceerd is Inhoud gepubliceerd en zichtbaar op de website + %0% documenten gepubliceerd en zichtbaar op de website + %0% gepubliceerd en zichtbaar op de website + %0% documenten gepubliceerd voor de talen languages %1% en zichtbaar op de website Inhoud opgeslagen Vergeet niet te publiceren om de wijzigingen zichtbaar te maken + Een planning voor publicatie is bijgewerkt + %0% bewaard Verzend voor goedkeuring - Verandering zijn verstuurd voor goedkeuring + Aanpassingen zijn verstuurd voor goedkeuring + %0% aanpassingen zijn verstuurd voor goedkeuring Media opgeslagen Media opgeslagen zonder fouten Lid opgeslagen + Ledengroep opgeslagen Stijlsheet eigenschap opgeslagen Stijlsheet opgeslagen Template opgeslagen Fout bij opslaan gebruiker (zie logboek) Gebruiker opgeslagen Gebruikerstype opgeslagen + Gebruikersgroep opgeslagen + Cultuur en hostnaam opgeslagen + Fout bij opslaan culturen en hostnamen Bestand niet opgeslagen bestand kon niet worden opgeslagen. Controleer de bestandsbeveiliging Bestand opgeslagen Bestand opgeslagen zonder fouten Taal opgeslagen - Media Type opgeslagen - Member Type opgeslagen - Template niet opgeslagen - Controleer dat je geen 2 tamplates met dezelfde naam hebt - Template opgeslagen - Template opgeslagen zonder fouten! + Mediatype opgeslagen + Ledentype opgeslagen + Ledengroep opgeslagen + Sjabloon niet opgeslagen + Controleer dat je geen 2 sjablonen met dezelfde naam hebt + Sjabloon opgeslagen + Sjabloon opgeslagen zonder fouten! Inhoud gedepubliceerd + Inhoud variatie %0% gedepubliceerd + De verplichte taal '%0%' is gedepubliceerd. Alle talen voor deze inhoud zijn nu gedepubliceerd. Partial view opgeslagen Partial view opgeslagen zonder fouten! Partial view niet opgeslagen Er is een fout opgetreden bij het opslaan van het bestand. + Rechten opgeslagen voor %0% gebruikersgroepen verwijderd %0% is verwijderd %0% gebruikers geactiveerd - %0% users gedeactiveerd + %0% gebruikers gedeactiveerd %0% is nu geactiveerd %0% is nu gedeactiveerd - Gebruikers groepen zijn ingesteld + Gebruikersgroepen zijn ingesteld %0% gebruikers gedeblokkeerd %0% is nu gedeblokkeerd Lid is geexporteerd naar een bestand @@ -897,28 +1323,122 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Gebruiker %0% is verwijderd Gebruiker uitnodigen Uitnodiging is opnieuw gestuurd naar gebruiker %0% + Kan het document niet publiceren omdat de vereiste '%0%' niet is gepubliceerd + Validatie is mislukt voor de taal '%0%' + Documenttype is geëxporteerd naar een bestand + Er is een fout gebeurd tijdens het exporteren van het documenttype + De publicatiedatum kan niet in het verleden liggen + Kan het document niet plannen voor publicatie omdat de vereiste '%0%' niet is gepubliceerd + Kan het document niet plannen voor publicatie omdat de vereiste '%0%' een publicatiedatum heeft die later is dan een niet-verplichte taal + De vervaldatum kan niet in het verleden liggen + De vervaldatum kan niet voor de publicatiedatum liggen - Gebruik CSS syntax bijv: h1, .redHeader, .blueTex - Stijlsheet aanpassen - Bewerk stylesheet eigenschap + Stijl toevoegen + Stijl bewerken + Rich text editor stijlen + Definieer de stijlen die beschikbaar moeten zijn in de rich text editor voor deze stylesheet + Stylesheet bewerken + Stylesheet eigenschap bewerken Naam waarmee de stijl in de editor te kiezen is Voorbeeld + Hoe de tekst er zal uitzien in de rich text editor. + Selector + Gebruik CSS syntax, bv. "h1" or ".redHeader" Stijlen + De CSS die moet toegepast worden in de rich text editor, bv. "color:red;" + Code + Rich Text Editor - Template aanpassen - Invoegen inhoudsgebied - Invoegen inhoudsgebied placeholder - Invoegen dictionary item - Invoegen Macro - Invoegen Umbraco page field - Basistemplate - Quick Guide voor Umbraco template tags - Template + Kan sjabloon met ID %0% niet verwijderen + Sjabloon aanpassen + Secties + Inhoudsgebied invoegen + Een tijdelijke aanduiding voor het inhoudsgebied invoegen + Invoegen + Kies wat je wil invoegen in het sjabloon + Woordenboek item invoegen + Een woordenboekitem is een tijdelijke aanduiding voor een vertaalbaar stuk tekst, waardoor het gemakkelijk is om ontwerpen voor meertalige websites te maken. + Macro invoegen + + Een Macro is een configureerbaar component die gebruikt kan worden voor + herbruikbare delen van je ontwerp, waar je de optie nodig hebt om parameters op te geven, + zoals bij gallerijen, formulieren en lijsten. + + Umbraco pagina veld invoegen + Toont de waarde van een benoemd veld van de huidige pagina, met opties om de waarde te wijzigen of terug te vallen op alternatieve waarden. + Partial view + + Een partial view is een apart sjabloon dat kan gerendered worden in een ander sjabloon, + het is geschikt voor het hergebruiken van HTML of voor het scheiden van complexe sjablonen in afzonderlijke bestanden. + + Hoofdsjabloon + Geen hoofdsjabloon + Render onderliggend sjabloon + + @RenderBody() in te voegen. + ]]> + + Definieer een benoemde sectie + + @section { ... } te omwikkelen. Dit kan worden weergegeven + in een specifiek gebied van de bovenliggende sjabloon door @RenderSection te gebruiken. + ]]> + + Render een benoemde sectie + + @RenderSection(name) in te voegen. + This renders an area of a child template which is wrapped in a corresponding @section [name]{ ... } definition. + ]]> + + Sectienaam + Sectie is verplicht + + @section definiëren, anders wordt een fout getoond. + ]]> + + Querybouwer + items gevonden, in + kopiëren naar klembord + Ik wil + alle inhoud + inhoud van het type "%0%" + van + mijn website + waar + en + is + is niet + voor + voor (inclusief geselecteerde datum) + na + na (inclusief geselecteerde datum) + is gelijk aan + is niet gelijk aan + bevat + bevat niet + groter dan + groter dan of gelijk aan + kleiner dan + kleiner of gelijk aan + Id + Naam + Datum aangemaakt + Datum gewijzigd + sorteren op + oplopend + aflopend + Sjabloon - Image + Afbeelding Macro Item toevoegen Kies de indeling @@ -931,15 +1451,18 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Klik om een item te embedden Klik om een afbeelding in te voegen Afbeelding ondertitel... - Typ hier...... + Typ hier... Grid lay-outs Lay-outs zijn het globale werkgebied voor de grid editor. Je hebt meestal maar één of twee verschillende lay-outs nodig - Een grid layout toevoegen + Een grid lay-out toevoegen + Grid lay-out aanpassen De lay-out aanpassen door de kolombreedte aan te passen en extra kolommen toe te voegen Rijconfiguratie Rijen zijn voorgedefinieerde cellen die horizontaal zijn gerangschikt Een rijconfiguratie toevoegen + Rijconfiguratie aanpassen De rijconfiguratie aanpassen door de breedte van de cel in te stellen en extra cellen toe te voegen + Geen verdere instellingen beschikbaar Kolommen Het totaal aantal gecombineerde kolommen in de grid layout Instellingen @@ -954,29 +1477,38 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Kies extra Kies standaard zijn toegevoegd + Waarschuwing + Je gaat de rijconfiguratie verwijderen + + Een rijconfiguratienaam verwijderen zal er voor zorgen dat bestaande inhoud verloren gaat die gebaseerd is op deze configuratie. + Composities + Groep Er zijn nog geen groepen toegevoegd - Voeg groep toe + Groep toevoegen Inherited van - Voeg property toe + Eigenschap toevoegen Verplicht label - Zet list view aan - Laat de child nodes van het content item zien als een sorteer- en doorzoekbare lijstweergave zien. Deze child nodes worden dan niet in de boomstructuur getoond. - Toegestane Templates - Kies welke templates toegestaan zijn om door de editors op dit content-type gebruikt te worden - Sta toe op root-niveau - Sta editors toe om content van dit type aan te maken op root-niveau - Toegestane child node types - Sta content van een bepaald type toe om onder dit type aangemaakt te kunnen worden - Kies child node + Lijstweergave inschakelen + Laat de onderliggende nodes van het content item zien als een sorteer- en doorzoekbare lijstweergave. Deze onderliggende nodes worden dan niet in de boomstructuur getoond. + Toegestane Sjablonen + Kies welke sjablonen toegestaan zijn om door de editors op dit contenttype gebruikt te worden + Sta toe op hoofdniveau + Sta editors toe om inhoud van dit type aan te maken op hoofdniveau + Toegestane onderliggende node types + Sta inhoud van een bepaald type toe om onder dit type aangemaakt te kunnen worden + Kies onderliggende node Overgeërfde tabs en properties van een bestaand documenttype. Nieuwe tabs worden toegevoegd aan het huidige documenttype of samengevoegd als een tab met dezelfde naam al bestaat. Dit contenttype wordt gebruikt in een compositie en kan daarom niet zelf een compositie worden. Er zijn geen contenttypen beschikbaar om als compositie te gebruiken. + Een compositie verwijderen zal alle bijbehorende eigenschapsdata ook verwijderen. Zodra je het documenttype hebt opgeslagen is er geen weg meer terug. Beschikbare editors Herbruik Editor instellingen + Beschikbare configuraties + Nieuwe configuration aanmaken Configuratie Ja, verwijder is naar onder geplaatst @@ -988,8 +1520,8 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Alle documenten Alle media items die gebruik maken van dit documenttype zullen permanent verwijderd worden. Bevestig aub dat je deze ook wilt verwijderen. - die gebruik maken van dit media type zullen permanent verwijderd worden. Bevestig aub dat je deze ook wilt verwijderen. - die gebruik maken van dit member type zullen permanent verwijderd worden. Bevestig aub dat je deze ook wilt verwijderen. + die gebruik maken van dit mediatype zullen permanent verwijderd worden. Bevestig aub dat je deze ook wilt verwijderen. + die gebruik maken van dit lidtype zullen permanent verwijderd worden. Bevestig aub dat je deze ook wilt verwijderen. en alle documenten van dit type en alle media items van dit type en alle leden van dit type @@ -1000,6 +1532,45 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Toon in het profiel van leden Toelaten dat deze eigenschap wordt getoond op de profiel pagina van het lid. tab heeft geen sorteervolgorde + Waar wordt deze compositie gebruikt? + Deze samenstelling wordt momenteel gebruikt bij de samenstelling van de volgende inhoudstypen: + Variaties toestaan + Variëren per cultuur toestaan + Segmentatie toestaan + Varieer per cultuur + Varieer per segment + Editors toestaan om nieuwe inhoud aan te maken van dit type in verschillende talen. + Editors toestaan om nieuwe inhoud in verschillende talen te creëren + Editors toestaan om nieuwe segmenten van deze inhoud te creëren. + Variaties per cultuur toestaan + Segmentatie toestaan + Elementtype + Is een elementtype + Een elementtype is bedoeld om bijvoorbeeld in geneste inhoud gebruikt te worden en niet in de boomstructuur. + Een documenttype kan niet worden gewijzigd in een elementtype nadat het is gebruikt om een of meer contentitems te maken. + Dit is niet van toepassing op een elementtype + Je hebt wijzigingen aangebracht aan deze eigenschap. Ben je zeker dat je ze wil weggooien? + + + Taal toevoegen + Verplichte taal + Eigenschappen van deze taal moeten worden ingevuld voordat de node kan worden gepubliceerd. + Standaard taal + Een Umbraco site kan maar één standaardtaal hebben. + Als u de standaardtaal wijzigt, kan er standaardinhoud ontbreken. + Valt terug naar + Geen terugvaltaal + Om meertalige inhoud terug te laten vallen naar een andere taal als deze niet aanwezig is in de gevraagde taal, selecteert u deze hier. + Terugvaltaal + Geen + + + Parameter toevoegen + Parameter bewerken + Macro naam invoeren + Parameters + Definieer de parameters die beschikbaar moeten zijn bij het gebruik van deze macro. + Selecteer een partial view macro bestand Models aan het gereneren @@ -1009,25 +1580,36 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Models generatie is mislukt, kijk in de Umbraco log voor details + Terugval veld toevoegen + Terugval veld + Standaardwaarde toevoegen + Standaardwaarde Alternatief veld Alternatieve tekst Kapitalisatie - Encoding + Codering Selecteer veld Converteer regelafbreking - ]]> + Ja, converteer regeleinden + ]]> Aangepaste velden Ja, alleen datum + Opmaak en codering Opmaken als datum + Format the value as a date, or a date with time, according to the active culture HTML-encoderen Speciale karakters worden geëncodeerd naar HTML. Zal worden ingevoegd na de veld waarde Zal worden ingevoegd voor de veld waarde Kleine letters + Uitvoer wijzigen Geen + Uitvoervoorbeeld Invoegen na veld Invoegen voor veld Recursief + Ja, recursief maken + Scheidingsteken Standaard velden Hoofdletters URL-encoderen @@ -1069,6 +1651,9 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Vertaald XML-document uploaden + Inhoud + Inhoudssjablonen + Media Cachebrowser Prullenbak Gemaakte packages @@ -1085,17 +1670,24 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Ledengroepen Rollen Ledentypes - Documenttypen + Documenttypes RelatieTypen Packages Packages - Installeer uit repository + Partial Views + Partial View Macro Bestanden + Installeer vanuit repository Installeer Runway Runway modules Script bestanden Scripts Stylesheets Sjablonen + Logboeken + Gebruikers + Instellingen + Sjabloon + Derde partij Nieuwe update beschikbaar @@ -1123,7 +1715,7 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Omschrijving Geblokkeerde gebruiker Documenttype - Redacteur + Editor Samenvattingsveld Foute wachtwoord pogingen Ga naar gebruikersprofiel @@ -1147,6 +1739,7 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Wachtwoord Reset wachtwoord Je wachtwoord is veranderd! + Wachtwoord aangepast Herhaal nieuwe wachtwoord Voer nieuwe wachtwoord in Je nieuwe wachtwoord mag niet leeg zijn! @@ -1167,10 +1760,10 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Selecteer een gebruikersgroep Geen startnode geselecteerd Geen startnodes geselecteerd - Startnode in Content + Startnode in Inhoud Beperk de content toegang tot een specifieke startnode - Startnodes in Content - Beperk de content toegang tot specifieke startnodes + Startnodes in Inhoud + Beperk de Inhoud tot specifieke startnodes Laatste keer bijgewerkt is aangemaakt De gebruiker is aangemaakt. Om in te loggen in Umbraco gebruik je onderstaand wachtwoord. @@ -1181,6 +1774,7 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je is uitgenodigd Een uitnodiging is gestuurd naar de nieuwe gebruiker met informatie over hoe in te loggen in Umbraco Hallo en welkom in Umbraco! Binnen ongeveer één minuut kan je aan de slag. Je moet enkel je wachtwoord instellen en een foto toevoegen. + Welkom bij Umbraco! Helaas is je uitnodiging vervallen. Vraag aan je administrator om de uitnodiging opnieuw te versturen. Wijzig je foto zodat andere gebruikers je makkelijk kunnen herkennen. Auteur Wijzig @@ -1247,7 +1841,7 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je - + Klik hier om de uitnodiging te accepteren @@ -1287,14 +1881,45 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Uitnodiging opnieuw aan het versturen... Verwijder gebruiker Weet je zeker dat je deze gebruiker wil verwijderen? + Alles + Actief + Uitgeschakeld + Vergrendeld + Uitgenodigd + Inactief + Naam (A-Z) + Naam (Z-A) + Nieuwste + Oudste + Laatste login + Er zijn geen gebruikersgroepen toegevoegd Validatie - Valideer als email + Valideer als e-mailadres Valideer als nummer Valideer als URL - ...of gebruik custom validatie + ...of gebruik aangepaste validatie Veld is verplicht + Voer een foutmelding in voor de aangepaste validatie (optioneel) + Voer een reguliere expressie in + Voer een foutmelding in voor de aangepaste validatie (optioneel) + Je hebt minstens + Je mag maximum + Geef maximum + items + URL(s) + URL(s) geselecteerd + items geselecteerd + Ongeldige datum + Geen nummer + Ongeldig e-mailadres + Waarde mag niet null zijn + Waarde mag niet leeg zijn + Ongeldige waarde, het komt niet overeen met het correcte patroon + Aangepaste validatie + %1% nodig.]]> + %1% te veel.]]> - Try Skip IIS Custom foutmeldingen is ingesteld op '%0%'. IIS versie '%1%' wordt gebruikt. - Try Skip IIS Custom foutmeldingen is ingesteld op '%0%'. Het wordt voor de gebruikte IIS versie (%2%) aangeraden deze in te stellen op '%1%'. - Try Skip IIS Custom foutmeldingen ingesteld op '%0%'. + trySkipIisCustomErrors is ingesteld op '%0%'. IIS versie '%1%' wordt gebruikt. + trySkipIisCustomErrors is ingesteld op '%0%'. Het wordt voor de gebruikte IIS versie (%2%) aangeraden deze in te stellen op '%1%'. + trySkipIisCustomErrors ingesteld op '%0%'. '%0%' kon niet gevonden worden in configuratie bestand '%1%'.]]> Er is een fout opgetreden. Bekijk de log file voor de volledige fout: %0%. + Database - Het database schema is correct voor deze versie van Umbraco + %0% problemen zijn gevonden met het databaseschema (Controleer het logboek voor details) + Enkele fouten zijn gevonden tijdens het valideren van het databaseschema tegen de huidige versie van Umbraco. Het cerficaat van de website is ongeldig. Cerficaat validatie foutmelding: '%0%' + Het SSL certificaat van de website is vervallen. + Het SSL certificaat van de website zal vervallen binnen %0% dagen. Fout bij pingen van URL %0% - '%1%' De site wordt momenteel %0% bekeken via HTTPS. De appSetting 'Umbraco.Core.UseHttps' in web.config staat op 'false'. Indien HTTPS gebruikt wordt moet deze op 'true' staan. @@ -1349,13 +1979,13 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Trace mode staat uit. Trace mode staat momenteel aan. Wij raden aan deze instelling uit te zetten voor livegang. Trace mode uitgezet. - Alle mappen hebben de juiste permissie-instellingen! + Alle mappen hebben de juiste rechten. + --> %0%.]]> %0%. Als deze niet in gebruik zijn voor deze omgeving hoeft er geen actie te worden ondernomen.]]> - All files have the correct permissions set. + Alle bestanden hebben de juiste rechten. @@ -1363,47 +1993,393 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je - %0%.]]> - %0%. Als deze niet in gebruik zijn voor deze omgeving hoeft er geen actie te worden ondernomen.]]> + %0%.]]> + %0%. Als deze niet in gebruik zijn voor deze omgeving hoeft er geen actie te worden ondernomen.]]> X-Frame-Options header of meta-tag om IFRAMEing door andere websites te voorkomen is aanwezig!]]> X-Frame-Options header of meta-tag om IFRAMEing door andere websites te voorkomen is NIET aanwezig.]]> Voorkom IFRAMEing via web.config Voegt de instelling toe aan de httpProtocol/customHeaders section in web.config om IFRAMEing door andere websites te voorkomen. De instelling om IFRAMEing door andere websites te voorkomen is toegevoegd aan de web.config! Web.config kon niet aangepast worden door error: %0% - - %0%.]]> - Er zijn geen headers gevonden die informatie prijsgeven over de gebruikte website technologie! + %0%.]]> + Er zijn geen headers gevonden die informatie vrijgeven over de gebruikte website technologie! In de Web.config werd system.net/mailsettings niet gevonden In de Web.config sectie system.net/mailsettings is de host niet geconfigureerd. SMTP instellingen zijn correct ingesteld en werken zoals verwacht. De SMTP server geconfigureerd met host '%0%' en poort '%1%' kon niet gevonden worden. Controleer of de SMTP instellingen in Web.config file system.net/mailsettings correct zijn. - %0%.]]> - %0%.]]> + %0%.]]> + %0%.]]> +

    Resultaten van de geplande Umbraco Health Checks uitgevoerd op %0% op %1%:

    %2%]]>
    + Umbraco Health Check Status: %0% + Alle groepen controleren + Groep controleren + + De health checker evalueert verschillende delen van de website voor best practice instellingen, configuratie, mogelijke problemen, enzovoort. U kunt problemen eenvoudig oplossen met een druk op de knop. + U kunt uw eigen health checks toevoegen, kijk even naar de documentatie voor meer informatie over aangepaste health checks.

    + ]]> +
    - URL tracker uitzetten - URL tracker aanzetten + URL tracker uitschakelen + URL tracker inschakelen + Cultuur Originele URL Doorgestuurd naar + Redirect Url Beheer + De volgende URLs verwijzen naar dit content item: Er zijn geen redirects Er wordt automatisch een redirect aangemaakt als een gepubliceerde pagina hernoemd of verplaatst wordt. Weet je zeker dat je de redirect van '%0%' naar '%1%' wilt verwijderen? Redirect URL verwijderd. Fout bij verwijderen redirect URL. + Dit zal de redirect verwijderen Weet je zeker dat je de URL tracker wilt uitzetten? URL tracker staat nu uit. Fout bij het uitzetten van de URL Tracker. Meer informatie kan gevonden worden in de log file. URL tracker staat nu aan. Fout bij het aanzetten van de URL tracker. Meer informatie kan gevonden worden in de log file. + + Geen woordenboekitems om uit te kiezen + + + %0% karakters resterend.]]> + %1% te veel.]]> + Content verwijderd met id : {0} gerelateerd aan aan bovenliggend item met Id: {1} Media verwijderd met id: {0} gerelateerd aan aan bovenliggend item met Id: {1} Kan dit item niet automatisch herstellen - Er is geen 'herstel' relatie gevonden voor dit item. Gebruik de "Verplaats" optie om het manueel terug te zetten - Het item dat u wil herstellen onder ('%0%') zit in de prullenbak. Gebruik de "Verplaats" optie om het manueel terug te zetten + Er is geen locatie waar dit item automatisch kan worden hersteld. U kunt het item handmatig verplaatsen met behulp van de onderstaande boomstructuur. + was hersteld onder + + + Richting + Bovenliggend naar onderliggend + Bidirectioneel + Bovenliggend + Onderliggend + Aantal + Relaties + Gemaakt + Commentaar + Naam + Geen relaties voor dit relatietype. + Relatietype + Relaties + + + Aan de slag + Redirect URL Beheer + Inhoud + Welkom + Examine Beheer + Publicatiestatus + Models Builder + Gezondheidscontrole + Profilering + Aan de slag + Umbraco Forms installeren + + + Terug + Actieve layout: + Spring naar + groep + geslaagd + Waarschuwing + mislukt + suggestie + Controle geslaagd + Controle mislukt + Backoffice zoeken openen + Backoffice help openen/sluiten + Jouw profiel opties openen/sluiten + Cultuur en Hostnamen instellen voor %0% + Nieuwe node aanmaken onder %0% + Openbare toegang instellen op %0% + Rechten instellen op %0% + Sorteervolgorde wijzigen voor %0% + Maak een Inhoudssjabloon op basis van %0% + Open context menu voor + Huidige taal + Taal wijzigen naar + Map aanmaken + Partial View + Partial View Macro + Lid + Datatype + Zoeken in het redirect dashboard + Zoeken in de gebruikersgroep sectie + Zoeken in de gebruikers sectie + Item aanmaken + Aanmaken + Bewerken + Naam + Rij toevoegen + Bekijk meer opties + Vertaling aanwezig + Vertaling ontbreekt + Woordenboek items + + + Referenties + Dit Datatype heeft geen referenties. + Gebruikt in Documenttypes + Geen referenties naar Documenttypes. + Gebruikt in Mediatypes + Geen referenties naar Mediatypes. + Gebruikt in Ledentypes + Geen referenties naar Ledentypes. + Gebruikt door + Gebruikt in Documenten + Gebruikt in Leden + Gebruikt in Media + + + Opgeslagen zoekopdracht verwijderen + Log Niveaus + Opgeslagen Zoekopdrachten + Zoekopdracht opslaan + Enter a friendly name for your search query + Zoekopdracht filteren + Aantal items + Tijdstempel + Niveau + Machine + Bericht + Uitzondering + Eigenschappen + Zoeken Met Google + Dit bericht met Google opzoeken + Zoeken Met Bing + Dit bericht met Bing opzoeken + Zoeken in Our Umbraco + Search this message on Our Umbraco forums and docs + Our Umbraco met Google doorzoeken + Our Umbraco forums met Google doorzoeken + Umbraco broncode doorzoeken + Zoeken in Umbraco broncode op Github + Umbraco Issues doorzoeken + Umbraco Issues op Github doorzoeken + Zoekopdracht verwijderen + Logs met Request ID zoeken + Logs met Namespace zoeken + Logs met Machine Naam zoeken + Openen + Peilen + Elke 2 seconden + Elke 5 seconden + Elke 10 seconden + Elke 20 seconden + Elke 30 seconden + Elke 2s peilen + Elke 5s peilen + Elke 10s peilen + Elke 20s peilen + Elke 30s peilen + + + Kopieer %0% + %0% van %1% + Alle items verwijderen + Klembord leegmaken + + + Eigenschapsacties openen + Eigenschapsacties sluiten + + + Wachten + Status vernieuwen + Geheugencache + + + + Vernieuwen + Database Cache + + Opnieuw bouwen kan duur zijn. + Gebruik het wanneer herladen niet genoeg is en u denkt dat de databasecache niet correct + is gegenereerd—wat zou duiden op een kritiek Umbraco-probleem. + ]]> + + Opnieuw bouwen + Interne onderdelen + + niet te gebruiken. + ]]> + + Verzamelen + Gepubliceerde Cachestatus + Caches + + + Prestatieprofilering + + + Umbraco wordt uitgevoerd in de foutopsporingsmodus. Dit betekent dat u de ingebouwde prestatieprofiler kunt gebruiken om de prestaties te beoordelen bij het renderen van pagina's. +

    +

    + Als je de profiler voor een specifieke paginaweergave wilt activeren, voeg je umbDebug=true toe aan de querystring wanneer je de pagina opvraagt. +

    +

    + Als je wil dat de profiler standaard wordt geactiveerd voor alle paginaweergaven, kun je de onderstaande schakelaar gebruiken. + Het plaatst een cookie in je browser, die vervolgens de profiler automatisch activeert. + Met andere woorden, de profiler zal alleen voor jouw browser actief zijn, niet voor andere bezoekers. +

    + ]]> +
    + Activeer de profiler standaard + Vriendelijke herinnering + + + Je mag een productiesite nooit in de foutopsporingsmodus laten uitvoeren. Je kan de foutopsporingsmodus uitschakelen door de instelling debug="false" uit het <compilation /> element te verwijderen in het web.config bestand. +

    + ]]> +
    + + + Umbraco wordt op dit ogenblik niet uitgevoerd in de foutopsporingsmodus, dus je kan de ingebouwde profiler niet gebruiken. Dit is hoe het zou moeten zijn voor een productiewebsite. +

    +

    + De foutopsporingsmodus wordt ingeschakeld door debug="true" toe te voegen in het <compilation /> element in web.config. +

    + ]]> +
    + + + Je bent slechts een klik verwijderd van uren aan Umbraco trainingvideo's. + + Wil je Umbraco onder de knie krijgen? Besteed een paar minuten aan het leren van enkele best practices door een van deze video's over het gebruik van Umbraco te bekijken. Bezoek umbraco.tv voor meer Umbraco videos

    + ]]> +
    + Om je op weg te helpen + + + Start hier + Deze sectie bevat de bouwstenen voor jouw Umbraco-site. Volg de onderstaande links voor meer informatie over het werken met de items in de sectie Instellingen + Meer te weten komen + + in het Documentatiegedeelte van Our Umbraco + ]]> + + + Community Forum + ]]> + + + instructievideo's (sommige zijn gratis, andere vereisen een abonnement) + ]]> + + + productiviteitsverhogende programma's en commerciële ondersteuning + ]]> + + + training en certificering opportuniteiten + ]]> + + + + Welkom bij Het Vriendelijke CMS + Bedankt om voor Umbraco te kiezen - We denken dat dit het begin van iets moois is. Hoewel het in het begin misschien overweldigend aanvoelt, hebben we er veel aan gedaan om de leercurve zo soepel en snel mogelijk te laten verlopen. + + + Umbraco Forms + Maak formulieren met behulp van een intuïtieve interface. Van eenvoudige contactformulieren die e-mails versturen tot geavanceerde vragenlijsten die integreren met CRM-systemen. Je klanten zullen er dol op zijn! + + + Nieuwe blok aanmaken + Instellingensectie toevoegen + Weergave selecteren + Stylesheet selecteren + Miniatuur kiezen + Nieuwe aanmaken + Aangepaste stylesheet + Stylesheet toevoegen + Editor uiterlijk + Data modellen + Catalogus uiterlijk + Achtergrondkleur + Icoon kleur + Inhoud model + Label + Aangepaste weergave + Aangepaste weergave-omschrijving tonen + Overschrijf hoe dit blok wordt weergegeven in de BackOffice-gebruikersinterface. Kies een .html-bestand met je presentatie. + Instellingen model + Grootte van overlay-editor + Aangepaste weergave toevoegen + Instellingen toevoegen + Label sjabloon overschrijven + %0% wil verwijderen?]]> + %0% wil verwijderen?]]> + De inhoud van dit blok is nog steeds aanwezig, bewerken van deze inhoud is niet langer mogelijk en wordt weergegeven als niet-ondersteunde inhoud. + + Miniatuur + Miniatuur toevoegen + Lege aanmaken + Klembord + Instellingen + Geavanceerd + Inhoudseditor geforceerd verbergen + Je hebt aanpassingen gemaakt aan deze inhoud. Wil je deze wijzigingen verwerpen? + Wijzigingen opslaan? + + Fout! + Het Elementtype van dit blok bestaat niet meer + + + Wat zijn Inhoudssjablonen? + Inhoudssjablonen is vooraf gedefinieerde inhoud die kan worden geselecteerd bij het maken van een nieuwe node. + Hoe maak ik een Inhoudssjabloon? + + Er zijn 2 manieren om Inhoudssjablonen te maken:

    +
      +
    • Klik met de rechtermuisknop op een inhoudsnode en selecteer "Inhoudssjabloon aanmaken" om een nieuwe Inhoudssjabloon te maken.
    • +
    • Klik met de rechtermuisknop op Inhoudssjablonen in de boomstructuur in de sectie Instellingen en selecteer het documenttype waarvoor je een Inhoudssjabloon wilt maken.
    • +
    +

    Nadat de Inhoudssjabloon een naam heeft, kunnen redacteuren ze gaan gebruiken als basis voor hun nieuwe pagina.

    + ]]> +
    + Hoe beheer ik Inhoudssjablonen? + U kunt Inhoudssjablonen bewerken en verwijderen vanuit de boomstructuur "inhoudssjablonen" in de sectie Instellingen. Vouw het documenttype uit waarop de Inhoudssjabloon is gebaseerd en klik erop om het te bewerken of te verwijderen.
    diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pl.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pl.xml index cd22851724..a40f7e666b 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pl.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pl.xml @@ -612,8 +612,8 @@ Naciśnij przycisk instaluj, aby zainstalować bazę danych Umb

    Aby kontynuować, dokonaj edycji pliku "web.config" (używając Visual Studio lub dowolnego edytora tekstu), przemieść kursor na koniec pliku, dodaj parametry połączenia do Twojej bazy danych w kluczu o nazwie "umbracoDbDSN" i zapisz plik.

    Kliknij ponów próbę kiedy - skończysz.
    - Tu znajdziesz więcej informacji na temat edycji pliku "web.config".

    ]]> + skończysz.
    + Tu znajdziesz więcej informacji na temat edycji pliku "web.config".

    ]]> Skontaktuj się z Twoim dostawą usług internetowych jeśli zajdzie taka potrzeba. W przypadku instalacji na lokalnej maszynie lub serwerze możesz potrzebować pomocy administratora.]]> @@ -660,7 +660,7 @@ Naciśnij przycisk instaluj, aby zainstalować bazę danych Umb Chcę zacząć od zera dowiedz się jak) + (dowiedz się jak) Ciągle możesz wybrać, aby zainstalować Runway w późniejszym terminie. W tym celu przejdź do sekcji Deweloper i wybierz Pakiety. ]]> Właśnie stworzyłeś czystą instalację platformy Umbraco. Co chcesz zrobić teraz? @@ -728,7 +728,7 @@ Naciśnij przycisk instaluj, aby zainstalować bazę danych Umb Zaloguj się poniżej Zaloguj się z Sesja wygasła - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Zapomniałeś hasła? E-mail z linkiem do zresetowania hasła zostanie wysłany na podany adres E-mail z instrukcjami do zresetowania hasła zostanie wysłany, jeśli zgadza się z naszą bazą danych diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pt.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pt.xml index fbc70a6c47..0091cde73c 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pt.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/pt.xml @@ -354,8 +354,8 @@ Próximo para prosseguir.]]> Banco de dados não encontrado! Favor checar se a informação no "connection string" do "web.config" esteja correta.

    Para prosseguir, favor editar o arquivo "web.config" (usando Visual Studio ou seu editor de texto favorito), role até embaixo, adicione a connection string para seu banco de dados com a chave de nome "UmbracoDbDSN" e salve o arquivo

    -

    Clique o botão tentar novamente quando terminar.
    - Mais informações em como editar o web.config aqui.

    ]]>
    +

    Clique o botão tentar novamente quando terminar.
    + Mais informações em como editar o web.config aqui.

    ]]> Favor contatar seu provedor de internet ou hospedagem web se necessário. Se você estiver instalando em uma máquina ou servidor local é possível que você precise dessas informações por um administrador de sistema.]]> Pressione o botão atualizar para atualizar seu banco de dados para Umbraco %0%

    @@ -394,7 +394,7 @@ Para correr Umbraco você vai precisar atualizar as configurações de permissõ Também guarda informações temporárias (cache) para melhorar a performance do seu website.]]>
    Eu quero começar do zero learn how) + (learn how) Você ainda pode escolher instalar Runway mais tarde. Favor ir à seção Desenvolvedor e selecione pacotes.]]> Você acabou de configurar uma plataforma Umbraco limpa. O que deseja fazer a seguir? Runway está instalado @@ -445,7 +445,7 @@ Pressione "próximo" para iniciar o assistente.]]> Renovar agora para salvar seu trabalho - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Painel diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ru.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ru.xml index 651316e95c..df3c0361b9 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ru.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/ru.xml @@ -786,8 +786,7 @@

    Для настройки откройте файл "web.config" с помощью любого текстового редактора и добавьте нужную информацию в строку подключения (параметр "UmbracoDbDSN"), затем сохраните файл.

    Нажмите кнопку "Повторить" когда все будет готово
    - Более подробно о внесении изменений в файл "web.config" рассказано здесь.

    ]]> + Более подробно о внесении изменений в файл "web.config" рассказано здесь.

    ]]> Пожалуйста, свяжитесь с Вашим хостинг-провайдером, если есть необходимость, а если устанавливаете на локальную рабочую станцию или сервер, то получите информацию у Вашего системного администратора.]]> @@ -834,7 +833,7 @@ Здесь можно узнать об этом подробнее) Вы также можете отложить установку "Runway" на более позднее время. Перейдите к разделу "Разработка" и выберите пункт "Пакеты". + (Здесь можно узнать об этом подробнее) Вы также можете отложить установку "Runway" на более позднее время. Перейдите к разделу "Разработка" и выберите пункт "Пакеты". ]]> Вы только что установили чистую платформу Umbraco. Какой шаг будет следующим? "Runway" установлен @@ -891,7 +890,7 @@ Обновите сейчас, чтобы сохранить сделанные изменения - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Сегодня же выходной! Понедельник — день тяжелый... Вот уже вторник... diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/sv.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/sv.xml index 0e5353f477..f2cdc54657 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/sv.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/sv.xml @@ -504,7 +504,7 @@ Databaskonfiguration installera]]> Nästa för att fortsätta.]]> - Databasen kunde inte hittas! Kontrollera att informationen i databasanslutnings-inställningarna i filen "web.config" är rätt.

    För att fortsätta måste du redigera filen "web.config" (du kan använda Visual Studio eller din favorit text-redigerare), bläddra till slutet, lägg till databasanslutnings-inställningarna för din databas i fältet som heter "umbracoDbDSN" och spara filen.

    Klicka på Försök igen knappen när du är klar.
    > Mer information om att redigera web.config hittar du här.

    ]]>
    + Databasen kunde inte hittas! Kontrollera att informationen i databasanslutnings-inställningarna i filen "web.config" är rätt.

    För att fortsätta måste du redigera filen "web.config" (du kan använda Visual Studio eller din favorit text-redigerare), bläddra till slutet, lägg till databasanslutnings-inställningarna för din databas i fältet som heter "umbracoDbDSN" och spara filen.

    Klicka på Försök igen knappen när du är klar.
    Mer information om att redigera web.config hittar du här.

    ]]>
    Eventuellt kan du behöva kontakta ditt webb-hotell. Om du installerar på en lokal maskin eller server kan du få informationen från din systemadministratör.]]> Tryck Uppgradera knappen för att uppgradera din databas till Umbraco %0%

    Du behöver inte vara orolig. Inget innehåll kommer att raderas och efteråt kommer allt att fungera som vanligt!

    ]]>
    Tryck Nästa för att fortsätta.]]> @@ -532,7 +532,7 @@ Konfigurerar mapprättigheter Umbraco behöver skriv/ändra rättigheter till vissa mappar för att spara filer som bilder och PDFer. Umbraco sparar också temporär data (så kallad cache) för att öka prestandan på din webbplats. Jag vill börja från början - lär dig hur) Du kan fortfarande välja att installera Runway senare. Gå in i Utvecklarsektionen och välj Paket.]]> + lär dig hur) Du kan fortfarande välja att installera Runway senare. Gå in i Utvecklarsektionen och välj Paket.]]> Du har just installerat en ren Umbraco platform. Vad vill du göra härnäst? Runway är installerat Det här är vår lista över rekommenderade moduler, markera de moduler du vill installera, eller visa den fullständiga listan]]> @@ -567,7 +567,7 @@ Förnya nu för att spara ditt arbete - © 2001 - %0%
    umbraco.com

    ]]>
    + © 2001 - %0%
    umbraco.com

    ]]>
    Happy super Sunday Happy manic Monday Happy tremendous Tuesday @@ -589,6 +589,11 @@ eller klicka här för att välja filer Drag och släpp dina filer i denna yta + + Skapa en ny medlem + Alla medlemmar + Medlemsgrupper har inga extra egenskaper för redigering. + Välj sida ovan... %0% har kopierats till %1% diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/tr.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/tr.xml index a627b9edf2..fa0f909bfb 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/tr.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/tr.xml @@ -858,7 +858,7 @@

    Devam etmek için lütfen "web.config" dosyasını düzenleyin (Visual Studio veya favori metin düzenleyicinizi kullanarak), en alta kaydırın, veritabanınız için "UmbracoDbDSN" adlı anahtara bağlantı dizesini ekleyin ve dosyayı kaydedin.

    Yeniden dene düğmesini tıklayın. - bitti.
    + bitti.
    Web.config'i düzenleme hakkında daha fazla bilgi burada.

    ]]> @@ -924,7 +924,7 @@ nasıl yapılacağını öğrenin ) + (nasıl yapılacağını öğrenin ) Yine de Runway'i daha sonra kurmayı seçebilirsiniz. Lütfen Geliştirici bölümüne gidin ve Paketleri seçin. ]]> @@ -1009,7 +1009,7 @@ Web sitenizi yönetmek için, Umbraco'nun arka ofisini açın ve içerik eklemey Aşağıda oturum açın ile oturum açın Oturum zaman aşımına uğradı - & copy; 2001 - %0%
    Umbraco.com

    ]]>
    + © 2015 - %0%
    Umbraco.com

    ]]>
    Şifrenizi mi unuttunuz? Parolanızı sıfırlamak için bir bağlantıyla belirtilen adrese bir e-posta gönderilecektir Kayıtlarımızla eşleşirse, şifre sıfırlama talimatlarını içeren bir e-posta, belirtilen adrese gönderilecektir @@ -1140,7 +1140,7 @@ Web sitenizi yönetmek için, Umbraco'nun arka ofisini açın ve içerik eklemey İyi günler! - Umbraco robotunun alkışları + Umbraco robotundan teşekkürler ]]>
    Aşağıdaki diller %0% değiştirildi @@ -1204,7 +1204,7 @@ Web sitenizi yönetmek için, Umbraco'nun arka ofisini açın ve içerik eklemey

    İyi günler dilerim!

    - Umbraco robottan Alkış + Umbraco robotundan teşekkürler

    @@ -1858,7 +1858,7 @@ Web sitenizi yönetmek için, Umbraco'nun arka ofisini açın ve içerik eklemey İyi günler! - Umbraco robotunun alkışları + Umbraco robotdan teşekkürler ]]> Çevirmen kullanıcısı bulunamadı. Lütfen çeviriye içerik göndermeye başlamadan önce bir çevirmen kullanıcısı oluşturun diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh.xml index 2a97b60f63..286ab88881 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh.xml @@ -514,7 +514,7 @@ 数据库未找到!请检查数据库连接串设置。

    您可以自行编辑“web.config”文件,键名为 “UmbracoDbDSN”

    - 当自行编辑后,单击重试按钮
    。 + 当自行编辑后,单击重试按钮
    。 如何编辑web.config

    ]]>
    @@ -562,7 +562,7 @@ 我要从头开始 如何操作?) + (如何操作?) 您也可以安装晚一些安装“Runway”。 ]]> 您刚刚安装了一个干净的系统,要继续吗? @@ -630,7 +630,7 @@ 在下方登录 登录 会话超时 - © 2001 - %0%
    Umbraco.com

    ]]>
    + © 2001 - %0%
    Umbraco.com

    ]]>
    忘记密码? 电子邮件将发送到地址指定的链接, 以重置您的密码 如果电子邮件与我们的记录相符, 则将发送带有密码重置指令的邮件 diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh_tw.xml b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh_tw.xml index 8b619f6c26..0bdc79f052 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh_tw.xml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/config/lang/zh_tw.xml @@ -507,7 +507,7 @@

    請編輯檔案"web.config" (例如使用Visual Studio或您喜歡的編輯器),移動到檔案底部,並在名稱為"UmbracoDbDSN"的字串中設定資料庫連結資訊,並存檔。

    點選重試按鈕當上述步驟完成。
    - + 在此查詢更多編輯web.config的資訊。

    ]]>
    若需要時,請聯繫您的網路公司。如果您在本地機器或伺服器安裝的話,您也許需要聯絡系統管理者。]]> @@ -553,7 +553,7 @@ 我要從頭開始 學習該怎麼做) + (學習該怎麼做) 您晚點仍可以選擇安裝Runway,請至開發者區域選擇安裝。 ]]> 您剛剛安裝了一個乾淨的系統,要繼續嗎? @@ -619,7 +619,7 @@ 下方登入 登入使用 連線時間過了 - © 2001 - %0%
    Umbraco.com

    ]]>
    + © 2001 - %0%
    Umbraco.com

    ]]>
    忘記密碼? 一封內有重設密碼連結的電子郵件已經寄出給您 一封內有重設密碼連結的電子郵件已經寄到此信箱 diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index b5bfd75aad..067c0a1cf6 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -231,9 +231,9 @@ False True - 8100 + 8110 / - http://localhost:8100 + http://localhost:8110 False False diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/cy.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/cy.xml index d62680e548..eacfcde1bf 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/cy.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/cy.xml @@ -938,8 +938,8 @@

    Er mwyn parhau, newidiwch y ffeil "web.config" (gan ddefnyddio Visual Studio neu eich hoff olygydd testun), rholiwch at y gwaelod, ychwanegwch y llinyn gyswllt ar gyfer eich cronfa ddata yn yr allwedd o'r enw "UmbracoDbDSN" ac achub y ffeil.

    Cliciwch y botwm ceisio eto pan rydych wedi - gorffen.
    - Mwy o wybodaeth am newid y ffeil web.config yma.

    ]]> + gorffen.
    + Mwy o wybodaeth am newid y ffeil web.config yma.

    ]]> @@ -1004,7 +1004,7 @@ dysgwch sut) + (dysgwch sut) Gallwch ddewis i osod Runway yn hwyrach os hoffwch chi. Ewch at yr adran Datblygwr a dewiswch Pecynnau. ]]> @@ -1089,7 +1089,7 @@ Er mwyn gweinyddu eich gwefan, agorwch swyddfa gefn Umbraco a dechreuwch ychwang Mewngofnodwch isod Mewngofnodwch gyda Sesiwn wedi cyrraedd terfyn amser - © 2001 - %0%
    Umbraco.com

    ]]>
    + © 2001 - %0%
    Umbraco.com

    ]]>
    Wedi anghofio eich cyfrinair? Bydd ebost yn cael ei anfon i'r cyfeiriad darparwyd gyda dolen i ailosod eich cyfrinair Bydd ebost gyda chyfarwyddiadau ailosod cyfrinair yn cael ei anfon at y cyfeiriad darparwyd os yw'n cyfateb â'n cofnodion @@ -2438,7 +2438,7 @@ Er mwyn gweinyddu eich gwefan, agorwch swyddfa gefn Umbraco a dechreuwch ychwang Mae'r gwiriwr iechyd yn gwerthuso gwahanol rannau o'ch gwefan ar gyfer gosodiadau arfer gorau, cyfluniad, problemau posibl, ac ati. Gallwch chi drwsio problemau yn hawdd trwy wasgu botwm. - Gallwch chi ychwanegu eich gwiriadau iechyd eich hun, edrych ar y ddogfennaeth i gael mwy o wybodaeth am wiriadau iechyd arferu.

    + Gallwch chi ychwanegu eich gwiriadau iechyd eich hun, edrych ar y ddogfennaeth i gael mwy o wybodaeth am wiriadau iechyd arferu.

    ]]>
    Eich wefan gallu defnyddio y protocol gwarchodaeth TLS 1.2 wrth wneud cysylltiadau allanol i endpoints HTTPS @@ -2682,7 +2682,7 @@ Er mwyn gweinyddu eich gwefan, agorwch swyddfa gefn Umbraco a dechreuwch ychwang Oriau o fideos hyfforddiant Umbraco ddim ond un clic i fwrdd Eisiau meistroli Umbraco? Treuliwch gwpl o funudau yn dysgu rhai o'r arferion gorau gan wylio un o'r fideos hyn am sut i ddefnyddio Umbraco. Ac ymweld â umbraco.tv am fwy o fideos am Umbraco

    +

    Eisiau meistroli Umbraco? Treuliwch gwpl o funudau yn dysgu rhai o'r arferion gorau gan wylio un o'r fideos hyn am sut i ddefnyddio Umbraco. Ac ymweld â umbraco.tv am fwy o fideos am Umbraco

    ]]>
    I roi cychwyn i chi @@ -2693,27 +2693,27 @@ Er mwyn gweinyddu eich gwefan, agorwch swyddfa gefn Umbraco a dechreuwch ychwang Ddarganfod fwy fewn yr adran Dogfennaeth o Our Umbraco + Darllenwch fwy am weithio efo'r eitemau yn yr adran Gosodiadau fewn yr adran Dogfennaeth o Our Umbraco ]]> Fforwm Cymunedol + Gofynnwch gwestiwn yn y Fforwm Cymunedol ]]> fideos tiwtorial (mae rhai am ddim, ond bydd angen tanysgrifiad am rhai eraill) + Gwyliwch ein fideos tiwtorial (mae rhai am ddim, ond bydd angen tanysgrifiad am rhai eraill) ]]> hoffer hybu cynhyrchiant a chefnogaeth fasnachol + Darganfyddwch fwy am ein hoffer hybu cynhyrchiant a chefnogaeth fasnachol ]]> hyfforddi ac ardystio + Darganfyddwch fwy am gyfleoedd hyfforddi ac ardystio ]]> diff --git a/src/Umbraco.Web/AspNet/AspNetUmbracoApplicationLifetime.cs b/src/Umbraco.Web/AspNet/AspNetUmbracoApplicationLifetime.cs index 90261b1a5a..107c7e41c5 100644 --- a/src/Umbraco.Web/AspNet/AspNetUmbracoApplicationLifetime.cs +++ b/src/Umbraco.Web/AspNet/AspNetUmbracoApplicationLifetime.cs @@ -1,19 +1,16 @@ -using System; using System.Threading; using System.Web; using Umbraco.Core.Hosting; namespace Umbraco.Web.AspNet { - public class AspNetUmbracoApplicationLifetime : IUmbracoApplicationLifetime, IUmbracoApplicationLifetimeManager + public class AspNetUmbracoApplicationLifetime : IUmbracoApplicationLifetime { private readonly IHttpContextAccessor _httpContextAccessor; public AspNetUmbracoApplicationLifetime(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; - - UmbracoApplicationBase.ApplicationInit += ApplicationInit; } public bool IsRestarting { get; set; } @@ -33,11 +30,5 @@ namespace Umbraco.Web.AspNet Thread.CurrentPrincipal = null; HttpRuntime.UnloadAppDomain(); } - - public event EventHandler ApplicationInit; - public void InvokeApplicationInit() - { - ApplicationInit?.Invoke(this, EventArgs.Empty); - } } } diff --git a/src/Umbraco.Web/Security/MembershipHelper.cs b/src/Umbraco.Web/Security/MembershipHelper.cs index 65251320ca..5cee61834e 100644 --- a/src/Umbraco.Web/Security/MembershipHelper.cs +++ b/src/Umbraco.Web/Security/MembershipHelper.cs @@ -122,7 +122,7 @@ namespace Umbraco.Web.Security { pathsWithAccess.TryGetValue(path, out var hasAccess); // if it's not found it's false anyways - result[path] = hasAccess; + result[path] = !pathsWithProtection.Contains(path) || hasAccess; } return result; } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 80e8024786..24d0a95eff 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -94,6 +94,9 @@ + + + 3.5.3 runtime; build; native; contentfiles; analyzers @@ -264,5 +267,8 @@ Mvc\web.config + + + \ No newline at end of file diff --git a/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs b/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs index 477585640d..6601497a3f 100644 --- a/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs +++ b/src/Umbraco.Web/WebApi/HttpActionContextExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Net; using System.Net.Http; @@ -23,29 +23,29 @@ namespace Umbraco.Web.WebApi /// /// /// - public static T GetModelFromMultipartRequest(this HttpActionContext actionContext, MultipartFormDataStreamProvider result, string requestKey, string validationKeyPrefix = "") - { - if (result.FormData[requestKey/*"contentItem"*/] == null) - { - var response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest); - response.ReasonPhrase = $"The request was not formatted correctly and is missing the '{requestKey}' parameter"; - throw new HttpResponseException(response); - } + //public static T GetModelFromMultipartRequest(this HttpActionContext actionContext, MultipartFormDataStreamProvider result, string requestKey, string validationKeyPrefix = "") + //{ + // if (result.FormData[requestKey/*"contentItem"*/] == null) + // { + // var response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest); + // response.ReasonPhrase = $"The request was not formatted correctly and is missing the '{requestKey}' parameter"; + // throw new HttpResponseException(response); + // } - //get the string json from the request - var contentItem = result.FormData[requestKey]; + // //get the string json from the request + // var contentItem = result.FormData[requestKey]; - //deserialize into our model - var model = JsonConvert.DeserializeObject(contentItem); + // //deserialize into our model + // var model = JsonConvert.DeserializeObject(contentItem); - //get the default body validator and validate the object - var bodyValidator = actionContext.ControllerContext.Configuration.Services.GetBodyModelValidator(); - var metadataProvider = actionContext.ControllerContext.Configuration.Services.GetModelMetadataProvider(); - //by default all validation errors will not contain a prefix (empty string) unless specified - bodyValidator.Validate(model, typeof(T), metadataProvider, actionContext, validationKeyPrefix); + // //get the default body validator and validate the object + // var bodyValidator = actionContext.ControllerContext.Configuration.Services.GetBodyModelValidator(); + // var metadataProvider = actionContext.ControllerContext.Configuration.Services.GetModelMetadataProvider(); + // //by default all validation errors will not contain a prefix (empty string) unless specified + // bodyValidator.Validate(model, typeof(T), metadataProvider, actionContext, validationKeyPrefix); - return model; - } + // return model; + //} /// /// Helper method to get the from the request in a non-async manner @@ -53,54 +53,54 @@ namespace Umbraco.Web.WebApi /// /// /// - public static MultipartFormDataStreamProvider ReadAsMultipart(this HttpActionContext actionContext, string rootVirtualPath) - { - if (actionContext.Request.Content.IsMimeMultipartContent() == false) - { - throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); - } + //public static MultipartFormDataStreamProvider ReadAsMultipart(this HttpActionContext actionContext, string rootVirtualPath) + //{ + // if (actionContext.Request.Content.IsMimeMultipartContent() == false) + // { + // throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); + // } - var hostingEnvironment = Current.Factory.GetRequiredService(); - var root = hostingEnvironment.MapPathContentRoot(rootVirtualPath); - //ensure it exists - Directory.CreateDirectory(root); - var provider = new MultipartFormDataStreamProvider(root); + // var hostingEnvironment = Current.Factory.GetRequiredService(); + // var root = hostingEnvironment.MapPathContentRoot(rootVirtualPath); + // //ensure it exists + // Directory.CreateDirectory(root); + // var provider = new MultipartFormDataStreamProvider(root); - var request = actionContext.Request; - var content = request.Content; + // var request = actionContext.Request; + // var content = request.Content; - // Note: YES this is super strange, ugly, and weird. - // One would think that you could just do: - // - //var result = content.ReadAsMultipartAsync(provider).Result; - // - // But it deadlocks. See https://stackoverflow.com/questions/15201255 for details, which - // points to https://msdn.microsoft.com/en-us/magazine/jj991977.aspx which contains more - // details under "Async All the Way" - see also https://olitee.com/2015/01/c-async-await-common-deadlock-scenario/ - // which contains a simplified explanation: ReadAsMultipartAsync is meant to be awaited, - // not used in the non-async .Result way, and there is nothing we can do about it. - // - // Alas, model binders cannot be async "all the way", so we have to wrap in a task, to - // force proper threading, and then it works. + // // Note: YES this is super strange, ugly, and weird. + // // One would think that you could just do: + // // + // //var result = content.ReadAsMultipartAsync(provider).Result; + // // + // // But it deadlocks. See https://stackoverflow.com/questions/15201255 for details, which + // // points to https://msdn.microsoft.com/en-us/magazine/jj991977.aspx which contains more + // // details under "Async All the Way" - see also https://olitee.com/2015/01/c-async-await-common-deadlock-scenario/ + // // which contains a simplified explanation: ReadAsMultipartAsync is meant to be awaited, + // // not used in the non-async .Result way, and there is nothing we can do about it. + // // + // // Alas, model binders cannot be async "all the way", so we have to wrap in a task, to + // // force proper threading, and then it works. - MultipartFormDataStreamProvider result = null; - var task = Task.Run(() => content.ReadAsMultipartAsync(provider)) - .ContinueWith(x => - { - if (x.IsFaulted && x.Exception != null) - { - throw x.Exception; - } - result = x.ConfigureAwait(false).GetAwaiter().GetResult(); - }, - // Must explicitly specify this, see https://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html - TaskScheduler.Default); - task.Wait(); + // MultipartFormDataStreamProvider result = null; + // var task = Task.Run(() => content.ReadAsMultipartAsync(provider)) + // .ContinueWith(x => + // { + // if (x.IsFaulted && x.Exception != null) + // { + // throw x.Exception; + // } + // result = x.ConfigureAwait(false).GetAwaiter().GetResult(); + // }, + // // Must explicitly specify this, see https://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html + // TaskScheduler.Default); + // task.Wait(); - if (result == null) - throw new InvalidOperationException("Could not read multi-part message"); + // if (result == null) + // throw new InvalidOperationException("Could not read multi-part message"); - return result; - } + // return result; + //} } }