diff --git a/src/Umbraco.Cms.Api.Management/Controllers/Indexer/RebuildIndexerController.cs b/src/Umbraco.Cms.Api.Management/Controllers/Indexer/RebuildIndexerController.cs index b64c252a1ab8..97131adcb904 100644 --- a/src/Umbraco.Cms.Api.Management/Controllers/Indexer/RebuildIndexerController.cs +++ b/src/Umbraco.Cms.Api.Management/Controllers/Indexer/RebuildIndexerController.cs @@ -1,4 +1,4 @@ -using Asp.Versioning; +using Asp.Versioning; using Examine; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -38,7 +38,7 @@ public RebuildIndexerController( [ProducesResponseType(StatusCodes.Status200OK)] public async Task Rebuild(CancellationToken cancellationToken, string indexName) { - if (!_examineManager.TryGetIndex(indexName, out var index)) + if (!_examineManager.TryGetIndex(indexName, out IIndex? index)) { var invalidModelProblem = new ProblemDetails { diff --git a/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs b/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs index fd6d9116c5c8..5a247a647c6a 100644 --- a/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs +++ b/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs @@ -1,4 +1,4 @@ -using System.Security.Claims; +using System.Security.Claims; using Asp.Versioning; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Authentication; @@ -217,7 +217,7 @@ public async Task LinkLoginKey(string provider) /// /// Called when a user links an external login provider in the back office /// - /// + /// /// // This method is marked as AllowAnonymous and protected with a secret (linkKey) inside the model for the following reasons // - when a js client uses the fetch api (or old ajax requests) they can send a bearer token diff --git a/src/Umbraco.Cms.Api.Management/Factories/MediaTypeEditingPresentationFactory.cs b/src/Umbraco.Cms.Api.Management/Factories/MediaTypeEditingPresentationFactory.cs index 11b2d1813411..c5cd70ed4995 100644 --- a/src/Umbraco.Cms.Api.Management/Factories/MediaTypeEditingPresentationFactory.cs +++ b/src/Umbraco.Cms.Api.Management/Factories/MediaTypeEditingPresentationFactory.cs @@ -1,5 +1,4 @@ -using Umbraco.Cms.Api.Management.ViewModels.MediaType; -using Umbraco.Cms.Core.Models; +using Umbraco.Cms.Api.Management.ViewModels.MediaType; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.ContentTypeEditing; using Umbraco.Cms.Core.Services; diff --git a/src/Umbraco.Cms.Persistence.EFCore/Locking/SqliteEFCoreDistributedLockingMechanism.cs b/src/Umbraco.Cms.Persistence.EFCore/Locking/SqliteEFCoreDistributedLockingMechanism.cs index 23b3d8d41054..8308ae4d3a11 100644 --- a/src/Umbraco.Cms.Persistence.EFCore/Locking/SqliteEFCoreDistributedLockingMechanism.cs +++ b/src/Umbraco.Cms.Persistence.EFCore/Locking/SqliteEFCoreDistributedLockingMechanism.cs @@ -115,12 +115,7 @@ public override string ToString() // Mostly no-op just check that we didn't end up ReadUncommitted for real. private void ObtainReadLock() { - IEfCoreScope? efCoreScope = _parent._efCoreScopeAccessor.Value.AmbientScope; - - if (efCoreScope is null) - { - throw new PanicException("No current ambient scope"); - } + IEfCoreScope? efCoreScope = _parent._efCoreScopeAccessor.Value.AmbientScope ?? throw new PanicException("No current ambient scope"); efCoreScope.ExecuteWithContextAsync(async database => { @@ -136,12 +131,7 @@ private void ObtainReadLock() // lock occurs for entire database as opposed to row/table. private void ObtainWriteLock() { - IEfCoreScope? efCoreScope = _parent._efCoreScopeAccessor.Value.AmbientScope; - - if (efCoreScope is null) - { - throw new PanicException("No ambient scope"); - } + IEfCoreScope? efCoreScope = _parent._efCoreScopeAccessor.Value.AmbientScope ?? throw new PanicException("No ambient scope"); efCoreScope.ExecuteWithContextAsync(async database => { diff --git a/src/Umbraco.Cms.Persistence.SqlServer/LocalDb.cs b/src/Umbraco.Cms.Persistence.SqlServer/LocalDb.cs index 6fcdfca76a64..a8a6480c89fc 100644 --- a/src/Umbraco.Cms.Persistence.SqlServer/LocalDb.cs +++ b/src/Umbraco.Cms.Persistence.SqlServer/LocalDb.cs @@ -420,7 +420,13 @@ public bool DatabaseExists(string databaseName) /// public bool CreateDatabase(string databaseName, string filesPath) { - GetDatabaseFiles(databaseName, filesPath, out var logName, out _, out _, out var mdfFilename, + GetDatabaseFiles( + databaseName, + filesPath, + out var logName, + out _, + out _, + out var mdfFilename, out var ldfFilename); using (var conn = new SqlConnection(_masterCstr)) @@ -463,7 +469,9 @@ public bool DropDatabase(string databaseName) { conn.Open(); - SetCommand(cmd, @" + SetCommand( + cmd, + @" SELECT name, filename FROM master.dbo.sysdatabases WHERE ('[' + name + ']' = @0 OR name = @0)", databaseName); @@ -554,11 +562,7 @@ public int DropDatabases(bool staleOnly = false) { conn.Open(); - var mdf = GetDatabase(cmd, databaseName); - if (mdf == null) - { - throw new InvalidOperationException("Database does not exist."); - } + var mdf = GetDatabase(cmd, databaseName) ?? throw new InvalidOperationException("Database does not exist."); DetachDatabase(cmd, databaseName); @@ -597,9 +601,12 @@ public void AttachDatabase(string databaseName, string filesPath) /// The LDF logical name. /// The MDF filename. /// The LDF filename. - public void GetFilenames(string databaseName, - out string? mdfName, out string? ldfName, - out string? mdfFilename, out string? ldfFilename) + public void GetFilenames( + string databaseName, + out string? mdfName, + out string? ldfName, + out string? mdfFilename, + out string? ldfFilename) { using (var conn = new SqlConnection(_masterCstr)) using (SqlCommand? cmd = conn.CreateCommand()) @@ -621,7 +628,9 @@ public void KillConnections(string databaseName) { conn.Open(); - SetCommand(cmd, @" + SetCommand( + cmd, + @" DECLARE @sql VARCHAR(MAX); SELECT @sql = COALESCE(@sql,'') + 'kill ' + CONVERT(VARCHAR, SPId) + ';' FROM master.sys.sysprocesses @@ -640,7 +649,9 @@ FROM master.sys.sysprocesses /// The full filename of the MDF file, if the database exists, otherwise null. private static string? GetDatabase(SqlCommand cmd, string databaseName) { - SetCommand(cmd, @" + SetCommand( + cmd, + @" SELECT name, filename FROM master.dbo.sysdatabases WHERE ('[' + name + ']' = @0 OR name = @0)", databaseName); @@ -707,7 +718,7 @@ private static void ExecuteDropDatabase(SqlCommand cmd, string databaseName, str File.Delete(mdf); } - ldf = ldf ?? GetLogFilename(mdf); + ldf ??= GetLogFilename(mdf); if (File.Exists(ldf)) { File.Delete(ldf); @@ -726,7 +737,7 @@ private static string GetLogFilename(string mdfFilename) throw new ArgumentException("Not a valid MDF filename (no .mdf extension).", nameof(mdfFilename)); } - return mdfFilename.Substring(0, mdfFilename.Length - ".mdf".Length) + "_log.ldf"; + return mdfFilename[..^".mdf".Length] + "_log.ldf"; } /// @@ -743,7 +754,9 @@ private static void DetachDatabase(SqlCommand cmd, string databaseName) var unused1 = cmd.ExecuteNonQuery(); - SetCommand(cmd, @" + SetCommand( + cmd, + @" EXEC sp_detach_db @dbname=@0", databaseName); @@ -758,8 +771,14 @@ private static void DetachDatabase(SqlCommand cmd, string databaseName) /// The directory containing database files. private static void AttachDatabase(SqlCommand cmd, string databaseName, string filesPath) { - GetDatabaseFiles(databaseName, filesPath, - out var logName, out _, out _, out var mdfFilename, out var ldfFilename); + GetDatabaseFiles( + databaseName, + filesPath, + out var logName, + out _, + out _, + out var mdfFilename, + out var ldfFilename); // cannot use parameters on CREATE DATABASE // ie "CREATE DATABASE @0 ..." does not work @@ -802,13 +821,19 @@ private static void SetCommand(SqlCommand cmd, string sql, params object[] args) /// The LDF logical name. /// The MDF filename. /// The LDF filename. - private void GetFilenames(SqlCommand cmd, string databaseName, - out string? mdfName, out string? ldfName, - out string? mdfFilename, out string? ldfFilename) + private void GetFilenames( + SqlCommand cmd, + string databaseName, + out string? mdfName, + out string? ldfName, + out string? mdfFilename, + out string? ldfFilename) { mdfName = ldfName = mdfFilename = ldfFilename = null; - SetCommand(cmd, @" + SetCommand( + cmd, + @" SELECT DB_NAME(database_id), type_desc, name, physical_name FROM master.sys.master_files WHERE database_id=DB_ID(@0)", @@ -854,21 +879,32 @@ FROM master.sys.master_files /// . /// Extensions are used eg to copy MyDatabase.mdf to MyDatabase.mdf.temp. /// - public void CopyDatabaseFiles(string databaseName, string filesPath, - string? targetDatabaseName = null, string? targetFilesPath = null, - string? sourceExtension = null, string? targetExtension = null, - bool overwrite = false, bool delete = false) + public void CopyDatabaseFiles( + string databaseName, + string filesPath, + string? targetDatabaseName = null, + string? targetFilesPath = null, + string? sourceExtension = null, + string? targetExtension = null, + bool overwrite = false, + bool delete = false) { var nop = (targetFilesPath == null || targetFilesPath == filesPath) && (targetDatabaseName == null || targetDatabaseName == databaseName) - && (sourceExtension == null && targetExtension == null || sourceExtension == targetExtension); + && ((sourceExtension == null && targetExtension == null) || sourceExtension == targetExtension); if (nop && delete == false) { return; } - GetDatabaseFiles(databaseName, filesPath, - out _, out _, out _, out var mdfFilename, out var ldfFilename); + GetDatabaseFiles( + databaseName, + filesPath, + out _, + out _, + out _, + out var mdfFilename, + out var ldfFilename); if (sourceExtension != null) { @@ -892,8 +928,14 @@ public void CopyDatabaseFiles(string databaseName, string filesPath, else { // copy or copy+delete ie move - GetDatabaseFiles(targetDatabaseName ?? databaseName, targetFilesPath ?? filesPath, - out _, out _, out _, out var targetMdfFilename, out var targetLdfFilename); + GetDatabaseFiles( + targetDatabaseName ?? databaseName, + targetFilesPath ?? filesPath, + out _, + out _, + out _, + out var targetMdfFilename, + out var targetLdfFilename); if (targetExtension != null) { @@ -936,8 +978,14 @@ public void CopyDatabaseFiles(string databaseName, string filesPath, /// public bool DatabaseFilesExist(string databaseName, string filesPath, string? extension = null) { - GetDatabaseFiles(databaseName, filesPath, - out _, out _, out _, out var mdfFilename, out var ldfFilename); + GetDatabaseFiles( + databaseName, + filesPath, + out _, + out _, + out _, + out var mdfFilename, + out var ldfFilename); if (extension != null) { @@ -958,10 +1006,14 @@ public bool DatabaseFilesExist(string databaseName, string filesPath, string? ex /// The base log filename (the LDF filename without the .ldf extension). /// The MDF filename. /// The LDF filename. - private static void GetDatabaseFiles(string databaseName, string filesPath, + private static void GetDatabaseFiles( + string databaseName, + string filesPath, out string logName, - out string baseFilename, out string baseLogFilename, - out string mdfFilename, out string ldfFilename) + out string baseFilename, + out string baseLogFilename, + out string mdfFilename, + out string ldfFilename) { logName = databaseName + "_log"; baseFilename = Path.Combine(filesPath, databaseName); diff --git a/src/Umbraco.Core/Logging/DisposableTimer.cs b/src/Umbraco.Core/Logging/DisposableTimer.cs index 087ae7adb625..7db20a006852 100644 --- a/src/Umbraco.Core/Logging/DisposableTimer.cs +++ b/src/Umbraco.Core/Logging/DisposableTimer.cs @@ -44,7 +44,7 @@ internal DisposableTimer( _endMessageArgs = endMessageArgs; _failMessageArgs = failMessageArgs; _thresholdMilliseconds = thresholdMilliseconds < 0 ? 0 : thresholdMilliseconds; - _timingId = Guid.NewGuid().ToString("N").Substring(0, 7); // keep it short-ish + _timingId = Guid.NewGuid().ToString("N")[..7]; // keep it short-ish if (thresholdMilliseconds == 0) { @@ -63,7 +63,7 @@ internal DisposableTimer( var args = new object[startMessageArgs.Length + 1]; startMessageArgs.CopyTo(args, 0); args[^1] = _timingId; - + if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { logger.LogDebug(startMessage + " [Timing {TimingId}]", args); diff --git a/src/Umbraco.Core/Models/Membership/UserGroup.cs b/src/Umbraco.Core/Models/Membership/UserGroup.cs index c512702d54df..95f8dee7b854 100644 --- a/src/Umbraco.Core/Models/Membership/UserGroup.cs +++ b/src/Umbraco.Core/Models/Membership/UserGroup.cs @@ -58,8 +58,6 @@ public UserGroup(IShortStringHelper shortStringHelper) /// /// /// - /// - /// /// /// public UserGroup( diff --git a/src/Umbraco.Core/Persistence/Repositories/ITrackedReferencesRepository.cs b/src/Umbraco.Core/Persistence/Repositories/ITrackedReferencesRepository.cs index fda745c2f68b..4442e5ecf2dd 100644 --- a/src/Umbraco.Core/Persistence/Repositories/ITrackedReferencesRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/ITrackedReferencesRepository.cs @@ -54,7 +54,7 @@ public interface ITrackedReferencesRepository /// Gets a page of items which are in relation with the current item. /// Basically, shows the items which depend on the current item. /// - /// The identifier of the entity to retrieve relations for. + /// The identifier of the entity to retrieve relations for. /// The amount of items to skip. /// The amount of items to take. /// @@ -81,7 +81,7 @@ IEnumerable GetPagedRelationsForItem( /// /// Gets a page of items used in any kind of relation from selected integer ids. /// - /// The identifiers of the entities to check for relations. + /// The identifiers of the entities to check for relations. /// The amount of items to skip. /// The amount of items to take. /// diff --git a/src/Umbraco.Core/PropertyEditors/JsonPropertyIndexValueFactoryBase.cs b/src/Umbraco.Core/PropertyEditors/JsonPropertyIndexValueFactoryBase.cs index a6f3b5739b2a..e4a7492c5da1 100644 --- a/src/Umbraco.Core/PropertyEditors/JsonPropertyIndexValueFactoryBase.cs +++ b/src/Umbraco.Core/PropertyEditors/JsonPropertyIndexValueFactoryBase.cs @@ -2,7 +2,6 @@ using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Serialization; -using Umbraco.Cms.Core.Serialization; using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors; diff --git a/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs b/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs index 39fc468ceec9..200a7d71438e 100644 --- a/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs +++ b/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs @@ -77,8 +77,8 @@ public override Task TryFindContent(IPublishedRequestBuilder frequest) // look for template in last position var pos = path.LastIndexOf('/'); - var templateAlias = path.Substring(pos + 1); - path = pos == 0 ? "/" : path.Substring(0, pos);; + var templateAlias = path[(pos + 1)..]; + path = pos == 0 ? "/" : path[..pos]; ITemplate? template = _fileService.GetTemplate(templateAlias); diff --git a/src/Umbraco.Core/Routing/DefaultUrlProvider.cs b/src/Umbraco.Core/Routing/DefaultUrlProvider.cs index c30d5453aa3f..4a5d5d282655 100644 --- a/src/Umbraco.Core/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Core/Routing/DefaultUrlProvider.cs @@ -98,7 +98,7 @@ public virtual IEnumerable GetOtherUrls(int id, Uri current) // need to strip off the leading ID for the route if it exists (occurs if the route is for a node with a domain assigned) var pos = route.IndexOf('/'); - var path = pos == 0 ? route : route.Substring(pos); + var path = pos == 0 ? route : route[pos..]; var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); uri = _uriUtility.UriFromUmbraco(uri, _requestSettings); diff --git a/src/Umbraco.Core/Services/ContentService.cs b/src/Umbraco.Core/Services/ContentService.cs index dd6158520354..cd005b576c06 100644 --- a/src/Umbraco.Core/Services/ContentService.cs +++ b/src/Umbraco.Core/Services/ContentService.cs @@ -582,10 +582,7 @@ public IEnumerable GetPagedOfType( throw new ArgumentOutOfRangeException(nameof(pageSize)); } - if (ordering == null) - { - ordering = Ordering.By("sortOrder"); - } + ordering ??= Ordering.By("sortOrder"); using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) { @@ -613,10 +610,7 @@ public IEnumerable GetPagedOfTypes(int[] contentTypeIds, long pageInde throw new ArgumentOutOfRangeException(nameof(pageSize)); } - if (ordering == null) - { - ordering = Ordering.By("sortOrder"); - } + ordering ??= Ordering.By("sortOrder"); using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) { @@ -773,10 +767,7 @@ public IEnumerable GetPagedChildren(int id, long pageIndex, int pageSi throw new ArgumentOutOfRangeException(nameof(pageSize)); } - if (ordering == null) - { - ordering = Ordering.By("sortOrder"); - } + ordering ??= Ordering.By("sortOrder"); using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) { @@ -790,10 +781,7 @@ public IEnumerable GetPagedChildren(int id, long pageIndex, int pageSi /// public IEnumerable GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalChildren, IQuery? filter = null, Ordering? ordering = null) { - if (ordering == null) - { - ordering = Ordering.By("Path"); - } + ordering ??= Ordering.By("Path"); using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) { @@ -931,10 +919,7 @@ public IEnumerable GetPagedContentInRecycleBin(long pageIndex, int pag { using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) { - if (ordering == null) - { - ordering = Ordering.By("Path"); - } + ordering ??= Ordering.By("Path"); scope.ReadLock(Constants.Locks.ContentTree); IQuery? query = Query()? @@ -1361,6 +1346,7 @@ internal PublishResult CommitDocumentChanges(IContent content, int userId = Cons /// /// /// + /// /// /// /// @@ -1831,7 +1817,7 @@ private void PerformScheduledPublishingRelease(DateTime date, List 0) @@ -1913,7 +1899,7 @@ private bool PublishBranch_PublishCultures(IContent content, HashSet cul { return culturesToPublish.All(culture => { - var impact = _cultureImpactFactory.Create(culture, IsDefaultCulture(allLangs, culture), content); + CultureImpact? impact = _cultureImpactFactory.Create(culture, IsDefaultCulture(allLangs, culture), content); return content.PublishCulture(impact) && _propertyValidationService.Value.IsPropertyDataValid(content, out _, impact); }); @@ -1929,10 +1915,7 @@ private bool PublishBranch_PublishCultures(IContent content, HashSet cul // if published, republish if (published) { - if (cultures == null) - { - cultures = new HashSet(); // empty means 'already published' - } + cultures ??= new HashSet(); // empty means 'already published' if (edited) { @@ -1948,10 +1931,7 @@ private bool PublishBranch_PublishCultures(IContent content, HashSet cul return cultures; // null means 'nothing to do' } - if (cultures == null) - { - cultures = new HashSet(); - } + cultures ??= new HashSet(); cultures.Add(c); // means 'publish this culture' return cultures; @@ -2654,7 +2634,6 @@ public bool RecycleBinSmells() /// /// The to copy /// Id of the Content's new Parent - /// Key of the Content's new Parent /// Boolean indicating whether the copy should be related to the original /// A value indicating whether to recursively copy children. /// Optional Id of the User copying the Content @@ -3300,6 +3279,7 @@ private PublishResult StrategyPublish( /// /// /// + /// /// private PublishResult StrategyCanUnpublish( ICoreScope scope, @@ -3308,7 +3288,7 @@ private PublishResult StrategyCanUnpublish( IDictionary? notificationState) { // raise Unpublishing notification - var notification = new ContentUnpublishingNotification(content, evtMsgs).WithState(notificationState); + ContentUnpublishingNotification notification = new ContentUnpublishingNotification(content, evtMsgs).WithState(notificationState); var notificationResult = scope.Notifications.PublishCancelable(notification); if (notificationResult) diff --git a/src/Umbraco.Core/Services/DataTypeService.cs b/src/Umbraco.Core/Services/DataTypeService.cs index 382238d58326..7797a300159a 100644 --- a/src/Umbraco.Core/Services/DataTypeService.cs +++ b/src/Umbraco.Core/Services/DataTypeService.cs @@ -330,7 +330,7 @@ public Task> GetByEditorAliasAsync(string propertyEditorA return Task.FromResult(dataTypes); } - + /// public async Task> GetByEditorAliasAsync(string[] propertyEditorAlias) { @@ -555,7 +555,7 @@ public async Task> CreateAsync(IData return Attempt.FailWithStatus(DataTypeOperationStatus.DuplicateKey, dataType); } - var result = await SaveAsync(dataType, () => DataTypeOperationStatus.Success, userKey, AuditType.New); + Attempt result = await SaveAsync(dataType, () => DataTypeOperationStatus.Success, userKey, AuditType.New); scope.Complete(); diff --git a/src/Umbraco.Core/Services/IAuditService.cs b/src/Umbraco.Core/Services/IAuditService.cs index e4c973ced056..7481a5e613f4 100644 --- a/src/Umbraco.Core/Services/IAuditService.cs +++ b/src/Umbraco.Core/Services/IAuditService.cs @@ -105,10 +105,9 @@ Task> GetItemsByKeyAsync( /// /// Returns paged items in the audit trail for a given user /// - /// - /// - /// - /// + /// + /// + /// /// /// By default this will always be ordered descending (newest first) /// @@ -117,9 +116,7 @@ Task> GetItemsByKeyAsync( /// or the custom filter /// so we need to do that here /// - /// - /// Optional filter to be applied - /// + /// /// Task> GetPagedItemsByUserAsync( Guid userKey, diff --git a/src/Umbraco.Core/Services/IContentPublishingService.cs b/src/Umbraco.Core/Services/IContentPublishingService.cs index 0d60da7313e9..701aba31666e 100644 --- a/src/Umbraco.Core/Services/IContentPublishingService.cs +++ b/src/Umbraco.Core/Services/IContentPublishingService.cs @@ -1,4 +1,4 @@ -using Umbraco.Cms.Core.Models.ContentPublishing; +using Umbraco.Cms.Core.Models.ContentPublishing; using Umbraco.Cms.Core.Services.OperationStatus; namespace Umbraco.Cms.Core.Services; @@ -9,7 +9,7 @@ public interface IContentPublishingService /// Publishes a single content item. /// /// The key of the root content. - /// The cultures to publish. + /// The cultures to publish and their publishing schedules. /// The identifier of the user performing the operation. /// Result of the publish operation. Task> PublishAsync(Guid key, CultureAndScheduleModel cultureAndSchedule, Guid userKey); diff --git a/src/Umbraco.Core/Services/IRelationService.cs b/src/Umbraco.Core/Services/IRelationService.cs index 04e99528b591..676e7ea17c8e 100644 --- a/src/Umbraco.Core/Services/IRelationService.cs +++ b/src/Umbraco.Core/Services/IRelationService.cs @@ -177,9 +177,8 @@ public interface IRelationService : IService /// Gets a paged result of /// /// - /// - /// - /// + /// + /// /// /// Task, RelationOperationStatus>> GetPagedByRelationTypeKeyAsync(Guid key, int skip, int take, Ordering? ordering = null); @@ -403,6 +402,8 @@ public interface IRelationService : IService /// Gets the Relation types in a paged manner. /// Currently implements the paging in memory on the name attribute because the underlying repository does not support paging yet /// + /// + /// /// /// Task> GetPagedRelationTypesAsync(int skip, int take, params int[] ids); diff --git a/src/Umbraco.Core/Services/ITrackedReferencesService.cs b/src/Umbraco.Core/Services/ITrackedReferencesService.cs index 2b5dcfb83323..7cfcd1c117d8 100644 --- a/src/Umbraco.Core/Services/ITrackedReferencesService.cs +++ b/src/Umbraco.Core/Services/ITrackedReferencesService.cs @@ -54,7 +54,7 @@ public interface ITrackedReferencesService /// Gets a paged result of items which are in relation with the current item. /// Basically, shows the items which depend on the current item. /// - /// The identifier of the entity to retrieve relations for. + /// The identifier of the entity to retrieve relations for. /// The amount of items to skip /// The amount of items to take. /// diff --git a/src/Umbraco.Core/Services/ImportExport/ContentTypeImportService.cs b/src/Umbraco.Core/Services/ImportExport/ContentTypeImportService.cs index ec9cc5a5ce60..c1f97d8d40a4 100644 --- a/src/Umbraco.Core/Services/ImportExport/ContentTypeImportService.cs +++ b/src/Umbraco.Core/Services/ImportExport/ContentTypeImportService.cs @@ -32,7 +32,7 @@ public ContentTypeImportService( /// Imports the contentType /// /// - /// + /// /// the id of the contentType to overwrite, null if a new contentType should be created /// public async Task> Import( diff --git a/src/Umbraco.Core/Services/LocalizationService.cs b/src/Umbraco.Core/Services/LocalizationService.cs index e1fcfab2203d..989b8f8206db 100644 --- a/src/Umbraco.Core/Services/LocalizationService.cs +++ b/src/Umbraco.Core/Services/LocalizationService.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Events; @@ -220,7 +220,7 @@ public bool DictionaryItemExists(string key) /// Optional id of the user saving the dictionary item [Obsolete("Please use IDictionaryItemService for dictionary item operations. Will be removed in V15.")] public void Save(IDictionaryItem dictionaryItem, int userId = Constants.Security.SuperUserId) - { ; + { Guid currentUserKey = _userIdKeyResolver.GetAsync(userId).GetAwaiter().GetResult(); if (dictionaryItem.Id > 0) { diff --git a/src/Umbraco.Core/Services/Querying/RecycleBin/RecycleBinQueryResultType.cs b/src/Umbraco.Core/Services/Querying/RecycleBin/RecycleBinQueryResultType.cs index e864020a150f..f9f0a34a7547 100644 --- a/src/Umbraco.Core/Services/Querying/RecycleBin/RecycleBinQueryResultType.cs +++ b/src/Umbraco.Core/Services/Querying/RecycleBin/RecycleBinQueryResultType.cs @@ -1,7 +1,7 @@ namespace Umbraco.Cms.Core.Services.Querying.RecycleBin; /// -/// < 10 = Success +/// <10 = Success. /// public enum RecycleBinQueryResultType { diff --git a/src/Umbraco.Core/Services/RedirectUrlService.cs b/src/Umbraco.Core/Services/RedirectUrlService.cs index 07646de3de0c..0944b2a6a1b6 100644 --- a/src/Umbraco.Core/Services/RedirectUrlService.cs +++ b/src/Umbraco.Core/Services/RedirectUrlService.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; @@ -84,7 +84,7 @@ public void DeleteAll() public async Task GetMostRecentRedirectUrlAsync(string url) { - using (var scope = ScopeProvider.CreateCoreScope(autoComplete: true)) + using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) { return await _redirectUrlRepository.GetMostRecentUrlAsync(url); } @@ -142,9 +142,9 @@ public IEnumerable SearchRedirectUrls(string searchTerm, long page return await GetMostRecentRedirectUrlAsync(url); } - using (var scope = ScopeProvider.CreateCoreScope(autoComplete: true)) + using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) { return await _redirectUrlRepository.GetMostRecentUrlAsync(url, culture); } - } + } } diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index dd25791d131e..0167dc6d929f 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -4,14 +4,12 @@ using Microsoft.Extensions.DependencyInjection; using System.Security.Claims; using System.Security.Cryptography; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Editors; -using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Exceptions; using Umbraco.Cms.Core.IO; @@ -156,7 +154,7 @@ public static bool TryGetAssignedPermissionsForNode( if (permissions.Any(x => x.EntityId == nodeId)) { EntityPermission found = permissions.First(x => x.EntityId == nodeId); - var assignedPermissionsArray = found.AssignedPermissions; + ISet assignedPermissionsArray = found.AssignedPermissions; // Working with permissions assigned directly to a user AND to their groups, so maybe several per node // and we need to get the most permissive set @@ -668,7 +666,7 @@ public async Task> CreateAsync( return Attempt.FailWithStatus(UserOperationStatus.MissingUser, new UserCreationResult()); } - var userGroups = _userGroupRepository.GetMany().Where(x=>model.UserGroupKeys.Contains(x.Key)).ToArray(); + IUserGroup[] userGroups = _userGroupRepository.GetMany().Where(x=>model.UserGroupKeys.Contains(x.Key)).ToArray(); if (userGroups.Length != model.UserGroupKeys.Count) { @@ -789,7 +787,7 @@ public async Task> InviteAsyn return Attempt.FailWithStatus(UserOperationStatus.MissingUser, new UserInvitationResult()); } - var userGroups = _userGroupRepository.GetMany().Where(x=>model.UserGroupKeys.Contains(x.Key)).ToArray(); + IUserGroup[] userGroups = _userGroupRepository.GetMany().Where(x => model.UserGroupKeys.Contains(x.Key)).ToArray(); if (userGroups.Length != model.UserGroupKeys.Count) { @@ -2298,7 +2296,7 @@ private async Task, UserOperationStatus>> G var results = new List(); foreach (KeyValuePair node in nodes) { - var permissions = permissionsCollection.GetAllPermissions(node.Value); + ISet permissions = permissionsCollection.GetAllPermissions(node.Value); results.Add(new NodePermissions { NodeKey = node.Key, Permissions = permissions }); } @@ -2361,7 +2359,7 @@ public async Task, UserOperationStatus>> Ge var results = new List(); foreach (int nodeId in idKeyMap.Keys) { - var permissions = permissionCollection.GetAllPermissions(nodeId); + ISet permissions = permissionCollection.GetAllPermissions(nodeId); results.Add(new NodePermissions { NodeKey = idKeyMap[nodeId], Permissions = permissions }); } diff --git a/src/Umbraco.Core/Services/WebProfilerService.cs b/src/Umbraco.Core/Services/WebProfilerService.cs index 026c2afd38e6..e895bba6e7a7 100644 --- a/src/Umbraco.Core/Services/WebProfilerService.cs +++ b/src/Umbraco.Core/Services/WebProfilerService.cs @@ -46,7 +46,11 @@ private Attempt GetExecutingUserId() //FIXME when we can get current user return Attempt.Succeed(-1); +#pragma warning disable CS0162 // Unreachable code detected +#pragma warning disable CS0618 // Type or member is obsolete Attempt? userIdAttempt = _backOfficeSecurityAccessor?.BackOfficeSecurity?.GetUserId(); +#pragma warning restore CS0618 // Type or member is obsolete +#pragma warning restore CS0162 // Unreachable code detected return (userIdAttempt.HasValue && userIdAttempt.Value.Success) ? Attempt.Succeed(userIdAttempt.Value.Result) diff --git a/src/Umbraco.Infrastructure/BackgroundJobs/IRecurringBackgroundJob.cs b/src/Umbraco.Infrastructure/BackgroundJobs/IRecurringBackgroundJob.cs index c6be3dcec5d4..db57d026656c 100644 --- a/src/Umbraco.Infrastructure/BackgroundJobs/IRecurringBackgroundJob.cs +++ b/src/Umbraco.Infrastructure/BackgroundJobs/IRecurringBackgroundJob.cs @@ -8,15 +8,17 @@ namespace Umbraco.Cms.Infrastructure.BackgroundJobs; public interface IRecurringBackgroundJob { static readonly TimeSpan DefaultDelay = System.TimeSpan.FromMinutes(3); - static readonly ServerRole[] DefaultServerRoles = new[] { ServerRole.Single, ServerRole.SchedulingPublisher }; + static readonly ServerRole[] DefaultServerRoles = new[] { ServerRole.Single, ServerRole.SchedulingPublisher }; - /// Timespan representing how often the task should recur. + /// + /// Timespan representing how often the task should recur. + /// TimeSpan Period { get; } - /// - /// Timespan representing the initial delay after application start-up before the first run of the task - /// occurs. - /// + /// + /// Timespan representing the initial delay after application start-up before the first run of the task + /// occurs. + /// TimeSpan Delay { get => DefaultDelay; } ServerRole[] ServerRoles { get => DefaultServerRoles; } diff --git a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/HealthCheckNotifierJob.cs b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/HealthCheckNotifierJob.cs index cf99583fc45b..c79a1a0866b7 100644 --- a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/HealthCheckNotifierJob.cs +++ b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/HealthCheckNotifierJob.cs @@ -47,6 +47,7 @@ public event EventHandler PeriodChanged /// The typed logger. /// The profiling logger. /// Parser of crontab expressions. + /// public HealthCheckNotifierJob( IOptionsMonitor healthChecksSettings, HealthCheckCollection healthChecks, diff --git a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/LogScrubberJob.cs b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/LogScrubberJob.cs index 1c745661cb44..3fcbe8d3d656 100644 --- a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/LogScrubberJob.cs +++ b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/LogScrubberJob.cs @@ -30,7 +30,7 @@ public event EventHandler PeriodChanged { add { } remove { } } private readonly IAuditService _auditService; private readonly ILogger _logger; private readonly IProfilingLogger _profilingLogger; - private readonly ICoreScopeProvider _scopeProvider; + private readonly ICoreScopeProvider _scopeProvider; private LoggingSettings _settings; /// @@ -41,14 +41,14 @@ public event EventHandler PeriodChanged { add { } remove { } } /// Provides scopes for database operations. /// The typed logger. /// The profiling logger. - public LogScrubberJob( + public LogScrubberJob( IAuditService auditService, IOptionsMonitor settings, ICoreScopeProvider scopeProvider, ILogger logger, IProfilingLogger profilingLogger) { - + _auditService = auditService; _settings = settings.CurrentValue; _scopeProvider = scopeProvider; @@ -59,7 +59,7 @@ public LogScrubberJob( public Task RunJobAsync() { - + // Ensure we use an explicit scope since we are running on a background thread. using (ICoreScope scope = _scopeProvider.CreateCoreScope()) using (_profilingLogger.DebugDuration("Log scrubbing executing", "Log scrubbing complete")) diff --git a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJob.cs b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJob.cs index cc6e35bf835f..87b459d69fc7 100644 --- a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJob.cs +++ b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJob.cs @@ -55,5 +55,5 @@ public Task RunJobAsync() } return Task.CompletedTask; - } + } } diff --git a/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs b/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs index ccb3e4a0da85..aab9c71acdf9 100644 --- a/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs +++ b/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs @@ -92,10 +92,7 @@ private bool EnsureDirectories(string[] dirs, out IEnumerable errors, bo continue; } - if (temp == null) - { - temp = new List(); - } + temp ??= new List(); temp.Add(dir.TrimStart(_basePath)); success = false; @@ -117,10 +114,7 @@ private bool EnsureFiles(string[] files, out IEnumerable errors) continue; } - if (temp == null) - { - temp = new List(); - } + temp ??= new List(); temp.Add(file.TrimStart(_basePath)); success = false; @@ -145,10 +139,7 @@ private bool EnsureCanCreateSubDirectories(IEnumerable dirs, out IEnumer continue; } - if (temp == null) - { - temp = new List(); - } + temp ??= new List(); temp.Add(dir); success = false; diff --git a/src/Umbraco.Infrastructure/Logging/Viewer/LogViewerConfig.cs b/src/Umbraco.Infrastructure/Logging/Viewer/LogViewerConfig.cs index 3e4b0b793171..3bd18bc1ac33 100644 --- a/src/Umbraco.Infrastructure/Logging/Viewer/LogViewerConfig.cs +++ b/src/Umbraco.Infrastructure/Logging/Viewer/LogViewerConfig.cs @@ -49,7 +49,5 @@ public IReadOnlyList DeleteSavedSearch(string name) IReadOnlyList result = GetSavedSearches()!; scope.Complete(); return result; - scope.Complete(); - return result; } } diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs index 23f4aa108c64..c9d23acb90f1 100644 --- a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPremigrationPlan.cs @@ -12,7 +12,6 @@ public class UmbracoPremigrationPlan : MigrationPlan /// /// Initializes a new instance of the class. /// - /// The Umbraco version. public UmbracoPremigrationPlan() : base(Constants.Conventions.Migrations.UmbracoUpgradePlanPremigrationsName) => DefinePlan(); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs index 332339e49c8f..892fa78ae470 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs @@ -411,8 +411,8 @@ private void PerformGetReferencedDtos(List dtos) List userIds = dtos.Count == 1 ? new List {dtos[0].Id} : dtos.Select(x => x.Id).ToList(); Dictionary? xUsers = dtos.Count == 1 ? null : dtos.ToDictionary(x => x.Id, x => x); - List groupIds = new List(); - List groupKeys = new List(); + var groupIds = new List(); + var groupKeys = new List(); Sql sql; try { @@ -595,9 +595,9 @@ private void PerformGetReferencedDtos(List dtos) // map languages - foreach (var group in groups.Values) + foreach (UserGroupDto group in groups.Values) { - if (groups2languages.TryGetValue(group.Id, out var list)) + if (groups2languages.TryGetValue(group.Id, out IGrouping? list)) { group.UserGroup2LanguageDtos = list.ToList(); // groups2apps is distinct } diff --git a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs index 449d59ba4295..46f02863a90d 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs @@ -197,7 +197,6 @@ private IEnumerable GetFilePathsFromPropertyValues(IProperty prop) /// Returns the "src" property from the json structure if the value is formatted correctly /// /// - /// The deserialized value /// Should the path returned be the application relative path /// private string? GetFileSrcFromPropertyValue(object? propVal, bool relative = true) diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs b/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs index eeac48801d3c..32a554aff0a4 100644 --- a/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs +++ b/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs @@ -17,6 +17,7 @@ public class BackOfficeClaimsPrincipalFactory : UserClaimsPrincipalFactory /// The user manager /// The + /// public BackOfficeClaimsPrincipalFactory( UserManager userManager, IOptions optionsAccessor, diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs b/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs index 4c7943c69c63..4341b01b7906 100644 --- a/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs +++ b/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs @@ -62,10 +62,7 @@ public int[] StartContentIds get => _startContentIds; set { - if (value == null) - { - value = new int[0]; - } + value ??= new int[0]; BeingDirty.SetPropertyValueAndDetectChanges(value, ref _startContentIds!, nameof(StartContentIds), _startIdsComparer); } @@ -79,10 +76,7 @@ public int[] StartMediaIds get => _startMediaIds; set { - if (value == null) - { - value = new int[0]; - } + value ??= Array.Empty(); BeingDirty.SetPropertyValueAndDetectChanges(value, ref _startMediaIds!, nameof(StartMediaIds), _startIdsComparer); } @@ -123,6 +117,7 @@ public Guid Key /// This is allowed to be null (but would need to be filled in if trying to persist this instance) /// /// + /// public static BackOfficeIdentityUser CreateNew(GlobalSettings globalSettings, string? username, string email, string culture, string? name = null, Guid? id = null) { if (string.IsNullOrWhiteSpace(username)) diff --git a/src/Umbraco.Web.Common/ModelsBuilder/DependencyInjection/UmbracoBuilderDependencyInjectionExtensions.cs b/src/Umbraco.Web.Common/ModelsBuilder/DependencyInjection/UmbracoBuilderDependencyInjectionExtensions.cs index 20cd35d0d191..3784781413e2 100644 --- a/src/Umbraco.Web.Common/ModelsBuilder/DependencyInjection/UmbracoBuilderDependencyInjectionExtensions.cs +++ b/src/Umbraco.Web.Common/ModelsBuilder/DependencyInjection/UmbracoBuilderDependencyInjectionExtensions.cs @@ -126,7 +126,7 @@ public static IUmbracoBuilder AddModelsBuilder(this IUmbracoBuilder builder) builder.AddNotificationHandler(); builder.AddNotificationHandler(); builder.AddNotificationHandler(); - + builder.AddNotificationHandler(); builder.AddNotificationHandler(); } @@ -135,7 +135,7 @@ public static IUmbracoBuilder AddModelsBuilder(this IUmbracoBuilder builder) // Register required services for ModelsBuilderDashboardController builder.Services.AddSingleton(); - + // TODO: Remove in v13 - this is only here in case someone is already using this generator directly builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -165,7 +165,7 @@ private static IUmbracoBuilder AddInMemoryModelsRazorEngine(this IUmbracoBuilder // This is what the community MB would replace, all of the above services are fine to be registered builder.Services.AddSingleton(factory => factory.CreateDefaultPublishedModelFactory()); - + return builder; } } diff --git a/src/Umbraco.Web.Website/DependencyInjection/UmbracoBuilderExtensions.cs b/src/Umbraco.Web.Website/DependencyInjection/UmbracoBuilderExtensions.cs index f182bda7b6f2..400b288786f3 100644 --- a/src/Umbraco.Web.Website/DependencyInjection/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Web.Website/DependencyInjection/UmbracoBuilderExtensions.cs @@ -57,8 +57,7 @@ public static IUmbracoBuilder AddWebsite(this IUmbracoBuilder builder) x.GetRequiredService(), x.GetRequiredService(), x.GetRequiredService(), - x.GetRequiredService>() - )); + x.GetRequiredService>())); builder.Services.AddSingleton(); builder.Services.TryAddEnumerable(Singleton()); builder.Services.AddSingleton(); diff --git a/src/Umbraco.Web.Website/Routing/PublicAccessRequestHandler.cs b/src/Umbraco.Web.Website/Routing/PublicAccessRequestHandler.cs index b7c751d28c9e..801e4af08fc6 100644 --- a/src/Umbraco.Web.Website/Routing/PublicAccessRequestHandler.cs +++ b/src/Umbraco.Web.Website/Routing/PublicAccessRequestHandler.cs @@ -148,9 +148,10 @@ public PublicAccessRequestHandler( _logger.LogDebug("EnsurePublishedContentAccess: Page is not protected"); } } + } - // loop until we have access or reached max loops - } while (publicAccessStatus != PublicAccessStatus.AccessAccepted && i++ < maxLoop); + // loop until we have access or reached max loops + while (publicAccessStatus != PublicAccessStatus.AccessAccepted && i++ < maxLoop); if (i == maxLoop) { diff --git a/src/Umbraco.Web.Website/Routing/UmbracoRouteValuesFactory.cs b/src/Umbraco.Web.Website/Routing/UmbracoRouteValuesFactory.cs index c46bb890b147..714024a1bc28 100644 --- a/src/Umbraco.Web.Website/Routing/UmbracoRouteValuesFactory.cs +++ b/src/Umbraco.Web.Website/Routing/UmbracoRouteValuesFactory.cs @@ -45,13 +45,8 @@ public UmbracoRouteValuesFactory( ControllerActionDescriptor? descriptor = _controllerActionSearcher.Find( new DefaultHttpContext(), // this actually makes no difference for this method DefaultControllerName, - UmbracoRouteValues.DefaultActionName); - - if (descriptor == null) - { - throw new InvalidOperationException( + UmbracoRouteValues.DefaultActionName) ?? throw new InvalidOperationException( $"No controller/action found by name {DefaultControllerName}.{UmbracoRouteValues.DefaultActionName}"); - } return descriptor; }); @@ -151,8 +146,8 @@ private async Task CheckNoTemplateAsync( $"The call to {nameof(IPublishedRouter.UpdateRequestAsync)} cannot return null"); } - string? customActionName = GetTemplateName(request); - + string? customActionName = GetTemplateName(request); + def = new UmbracoRouteValues( request, def.ControllerActionDescriptor, @@ -167,7 +162,7 @@ private async Task CheckNoTemplateAsync( return def; } - + private string? GetTemplateName(IPublishedRequest request) { // check that a template is defined), if it doesn't and there is a hijacked route it will just route diff --git a/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj b/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj index 8ee1e80bb2a0..0e8d47572564 100644 --- a/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj +++ b/src/Umbraco.Web.Website/Umbraco.Web.Website.csproj @@ -6,8 +6,11 @@ Umbraco.Cms.Web.Website - - false + + ASP0019,CS0618,SA1401,SA1649,IDE0270,IDE1006 diff --git a/src/Umbraco.Web.Website/ViewEngines/ProfilingViewEngine.cs b/src/Umbraco.Web.Website/ViewEngines/ProfilingViewEngine.cs index 5862f90d6476..33ec4acb33c4 100644 --- a/src/Umbraco.Web.Website/ViewEngines/ProfilingViewEngine.cs +++ b/src/Umbraco.Web.Website/ViewEngines/ProfilingViewEngine.cs @@ -8,6 +8,8 @@ public class ProfilingViewEngine : IViewEngine { private readonly string _name; private readonly IProfiler _profiler; + + //TODO: can this be made private and with underscore? internal readonly IViewEngine Inner; public ProfilingViewEngine(IViewEngine inner, IProfiler profiler) diff --git a/tests/Umbraco.Tests.Benchmarks/EnumeratorBenchmarks.cs b/tests/Umbraco.Tests.Benchmarks/EnumeratorBenchmarks.cs index 05db4034dd55..460e819f187e 100644 --- a/tests/Umbraco.Tests.Benchmarks/EnumeratorBenchmarks.cs +++ b/tests/Umbraco.Tests.Benchmarks/EnumeratorBenchmarks.cs @@ -11,7 +11,7 @@ public void WithArray() { foreach (var t in EnumerateOneWithArray(1)) { - ; + } } @@ -20,7 +20,7 @@ public void WithYield() { foreach (var t in EnumerateOneWithYield(1)) { - ; + } } diff --git a/tests/Umbraco.Tests.Benchmarks/HashFromStreams.cs b/tests/Umbraco.Tests.Benchmarks/HashFromStreams.cs index cc8ad908775e..7b291b88b8d4 100644 --- a/tests/Umbraco.Tests.Benchmarks/HashFromStreams.cs +++ b/tests/Umbraco.Tests.Benchmarks/HashFromStreams.cs @@ -18,7 +18,7 @@ public class HashFromStreams // the SHA1CryptoServiceProvider is faster, but that is not reflected in these benchmarks. /* - + BenchmarkDotNet=v0.13.0, OS=Windows 10.0.19042.1052 (20H2/October2020Update) Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores .NET SDK=5.0.300-preview.21258.4 diff --git a/tests/Umbraco.Tests.Integration/Implementations/TestHelper.cs b/tests/Umbraco.Tests.Integration/Implementations/TestHelper.cs index 1a4ccacdd1bd..47d095c02a8d 100644 --- a/tests/Umbraco.Tests.Integration/Implementations/TestHelper.cs +++ b/tests/Umbraco.Tests.Integration/Implementations/TestHelper.cs @@ -174,16 +174,13 @@ public void AssertPropertyValuesAreEqual(object actual, object expected, Func sorter = null, int dateDeltaMilliseconds = 0) { - if (sorter == null) + // this is pretty hackerific but saves us some code to write + sorter ??= enumerable => { - // this is pretty hackerific but saves us some code to write - sorter = enumerable => - { - // semi-generic way of ensuring any collection of IEntity are sorted by Ids for comparison - var entities = enumerable.OfType().ToList(); - return entities.Count > 0 ? entities.OrderBy(x => x.Id) : entities; - }; - } + // semi-generic way of ensuring any collection of IEntity are sorted by Ids for comparison + var entities = enumerable.OfType().ToList(); + return entities.Count > 0 ? entities.OrderBy(x => x.Id) : entities; + }; var expectedListEx = sorter(expected).Cast().ToList(); var actualListEx = sorter(actual).Cast().ToList(); diff --git a/tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs b/tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs index cf321d9498cf..34445e244649 100644 --- a/tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs +++ b/tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs @@ -298,7 +298,7 @@ protected void ConfigureServices(IServiceCollection services) protected virtual void CustomMvcSetup(IMvcBuilder mvcBuilder) { - + } /// diff --git a/tests/Umbraco.Tests.Integration/Testing/TestWebProfilerRepository.cs b/tests/Umbraco.Tests.Integration/Testing/TestWebProfilerRepository.cs index 3d5dbb2e2b1c..a3c572ad047d 100644 --- a/tests/Umbraco.Tests.Integration/Testing/TestWebProfilerRepository.cs +++ b/tests/Umbraco.Tests.Integration/Testing/TestWebProfilerRepository.cs @@ -5,7 +5,7 @@ namespace Umbraco.Cms.Tests.Integration.Testing; public class TestWebProfilerRepository : IWebProfilerRepository { private bool _status = false; - + public void SetStatus(int userId, bool status) => _status = status; public bool GetStatus(int userId) => _status; diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs index 1644a3b1e4aa..51ade838c666 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs @@ -404,7 +404,7 @@ public void Can_Perform_Query_On_ContentTypeRepository_Sort_By_Name() var repository = ContentTypeRepository; // Act - var contentTypes = repository.Get(provider.CreateQuery().Where(x => x.ParentId == contentType.Id)).ToArray();; + var contentTypes = repository.Get(provider.CreateQuery().Where(x => x.ParentId == contentType.Id)).ToArray(); // Assert Assert.That(contentTypes.Count(), Is.EqualTo(3)); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LanguageServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LanguageServiceTests.cs index 043ce3d2f4e9..b04dcdb379b4 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LanguageServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LanguageServiceTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Services; @@ -262,7 +262,7 @@ public async Task Cannot_Create_Language_With_Invalid_Fallback_Language() Assert.IsFalse(result.Success); Assert.AreEqual(LanguageOperationStatus.InvalidFallbackIsoCode, result.Status); } - + [Test] public async Task Cannot_Create_Language_With_NonExisting_Fallback_Language() { @@ -332,7 +332,7 @@ public async Task Cannot_Update_Language_With_Invalid_Fallback_Language() Assert.IsFalse(result.Success); Assert.AreEqual(LanguageOperationStatus.InvalidFallbackIsoCode, result.Status); } - + [Test] public async Task Cannot_Create_Direct_Cyclic_Fallback_Language() { diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs index ca47bfbd9707..dd4c46f0a4b8 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs @@ -157,7 +157,7 @@ public void Boot1A() { return Mock.Of>(); } - + if (type == typeof(ILogger)) { return Mock.Of>(); @@ -324,7 +324,7 @@ public void Initialize() { return Mock.Of>(); } - + if (type == typeof(IServiceProviderIsService)) { return Mock.Of(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJobTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJobTests.cs index f2e6e574ef86..14311afbe292 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJobTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/ServerRegistration/InstructionProcessJobTests.cs @@ -30,7 +30,7 @@ public async Task Executes_And_Touches_Server() private InstructionProcessJob CreateInstructionProcessJob() { - + var mockLogger = new Mock>(); _mockDatabaseServerMessenger = new Mock(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/TempFileCleanupJobTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/TempFileCleanupJobTests.cs index c37094e6ac81..9c76c7b799fe 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/TempFileCleanupJobTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackgroundJobs/Jobs/TempFileCleanupJobTests.cs @@ -29,7 +29,7 @@ public async Task Executes_And_Cleans_Files() private TempFileCleanupJob CreateTempFileCleanupJob() { - + _mockIOHelper = new Mock(); _mockIOHelper.Setup(x => x.GetTempFolders()) .Returns(new DirectoryInfo[] { new(_testPath) });