diff --git a/src/Umbraco.Core/Mapping/IUmbracoMapper.cs b/src/Umbraco.Core/Mapping/IUmbracoMapper.cs
index 30c7bc440f..5ca86eaab3 100644
--- a/src/Umbraco.Core/Mapping/IUmbracoMapper.cs
+++ b/src/Umbraco.Core/Mapping/IUmbracoMapper.cs
@@ -43,7 +43,7 @@ namespace Umbraco.Cms.Core.Mapping
/// The target type.
/// The source object.
/// The target object.
- TTarget? Map(object source);
+ TTarget? Map(object? source);
///
/// Maps a source object to a new target object.
@@ -52,7 +52,7 @@ namespace Umbraco.Cms.Core.Mapping
/// The source object.
/// A mapper context preparation method.
/// The target object.
- TTarget? Map(object source, Action f);
+ TTarget? Map(object? source, Action f);
///
/// Maps a source object to a new target object.
diff --git a/src/Umbraco.Core/Mapping/MapperContext.cs b/src/Umbraco.Core/Mapping/MapperContext.cs
index 6b66e63307..6cc67e115a 100644
--- a/src/Umbraco.Core/Mapping/MapperContext.cs
+++ b/src/Umbraco.Core/Mapping/MapperContext.cs
@@ -9,7 +9,7 @@ namespace Umbraco.Cms.Core.Mapping
public class MapperContext
{
private readonly IUmbracoMapper _mapper;
- private IDictionary? _items;
+ private IDictionary? _items;
///
/// Initializes a new instance of the class.
@@ -27,7 +27,7 @@ namespace Umbraco.Cms.Core.Mapping
///
/// Gets the context items.
///
- public IDictionary Items => _items ?? (_items = new Dictionary());
+ public IDictionary Items => _items ?? (_items = new Dictionary());
#region Map
diff --git a/src/Umbraco.Core/Models/ContentEditing/AssignedUserGroupPermissions.cs b/src/Umbraco.Core/Models/ContentEditing/AssignedUserGroupPermissions.cs
index 03b30b3853..b6aca05515 100644
--- a/src/Umbraco.Core/Models/ContentEditing/AssignedUserGroupPermissions.cs
+++ b/src/Umbraco.Core/Models/ContentEditing/AssignedUserGroupPermissions.cs
@@ -25,13 +25,17 @@ namespace Umbraco.Cms.Core.Models.ContentEditing
[DataMember(Name = "defaultPermissions")]
public IDictionary>? DefaultPermissions { get; set; }
- public static IDictionary> ClonePermissions(IDictionary> permissions)
+ public static IDictionary> ClonePermissions(IDictionary>? permissions)
{
var result = new Dictionary>();
- foreach (var permission in permissions)
+ if (permissions is not null)
{
- result[permission.Key] = new List(permission.Value.Select(x => (Permission)x.Clone()));
+ foreach (var permission in permissions)
+ {
+ result[permission.Key] = new List(permission.Value.Select(x => (Permission)x.Clone()));
+ }
}
+
return result;
}
}
diff --git a/src/Umbraco.Core/Models/ContentEditing/ContentItemDisplay.cs b/src/Umbraco.Core/Models/ContentEditing/ContentItemDisplay.cs
index f2088715a9..a795f85724 100644
--- a/src/Umbraco.Core/Models/ContentEditing/ContentItemDisplay.cs
+++ b/src/Umbraco.Core/Models/ContentEditing/ContentItemDisplay.cs
@@ -115,7 +115,7 @@ namespace Umbraco.Cms.Core.Models.ContentEditing
[DataMember(Name = "contentTypeAlias", IsRequired = true)]
[Required(AllowEmptyStrings = false)]
- public string? ContentTypeAlias { get; set; }
+ public string ContentTypeAlias { get; set; } = null!;
[DataMember(Name = "sortOrder")]
public int SortOrder { get; set; }
diff --git a/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs b/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs
index 7b665ebd36..4921c12058 100644
--- a/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs
+++ b/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs
@@ -65,6 +65,6 @@ namespace Umbraco.Cms.Core.Models.ContentEditing
///
[DataMember(Name = "metaData")]
[ReadOnly(true)]
- public IDictionary AdditionalData { get; private set; }
+ public IDictionary AdditionalData { get; private set; }
}
}
diff --git a/src/Umbraco.Core/Models/ContentEditing/MessagesExtensions.cs b/src/Umbraco.Core/Models/ContentEditing/MessagesExtensions.cs
index 293693b2f7..5a93ae94c9 100644
--- a/src/Umbraco.Core/Models/ContentEditing/MessagesExtensions.cs
+++ b/src/Umbraco.Core/Models/ContentEditing/MessagesExtensions.cs
@@ -29,7 +29,7 @@ namespace Umbraco.Extensions
});
}
- public static void AddErrorNotification(this INotificationModel model, string header, string msg)
+ public static void AddErrorNotification(this INotificationModel model, string? header, string msg)
{
if (model.Exists(header, msg, NotificationStyle.Error)) return;
@@ -65,6 +65,6 @@ namespace Umbraco.Extensions
});
}
- private static bool Exists(this INotificationModel model, string header, string message, NotificationStyle notificationType) => model.Notifications?.Any(x => (x.Header?.InvariantEquals(header) ?? false) && (x.Message?.InvariantEquals(message) ?? false) && x.NotificationType == notificationType) ?? false;
+ private static bool Exists(this INotificationModel model, string? header, string message, NotificationStyle notificationType) => model.Notifications?.Any(x => (x.Header?.InvariantEquals(header) ?? false) && (x.Message?.InvariantEquals(message) ?? false) && x.NotificationType == notificationType) ?? false;
}
}
diff --git a/src/Umbraco.Core/Models/ContentEditing/StylesheetRule.cs b/src/Umbraco.Core/Models/ContentEditing/StylesheetRule.cs
index 1afabb10e6..c5f827300a 100644
--- a/src/Umbraco.Core/Models/ContentEditing/StylesheetRule.cs
+++ b/src/Umbraco.Core/Models/ContentEditing/StylesheetRule.cs
@@ -6,12 +6,12 @@ namespace Umbraco.Cms.Core.Models.ContentEditing
public class StylesheetRule
{
[DataMember(Name = "name")]
- public string? Name { get; set; }
+ public string Name { get; set; } = null!;
[DataMember(Name = "selector")]
- public string? Selector { get; set; }
+ public string Selector { get; set; } = null!;
[DataMember(Name = "styles")]
- public string? Styles { get; set; }
+ public string Styles { get; set; } = null!;
}
}
diff --git a/src/Umbraco.Core/Models/CultureImpact.cs b/src/Umbraco.Core/Models/CultureImpact.cs
index 8c6be0f7ae..dea741ab01 100644
--- a/src/Umbraco.Core/Models/CultureImpact.cs
+++ b/src/Umbraco.Core/Models/CultureImpact.cs
@@ -21,7 +21,7 @@ namespace Umbraco.Cms.Core.Models
///
///
///
- public static string? GetCultureForInvariantErrors(IContent content, string[] savingCultures, string defaultCulture)
+ public static string? GetCultureForInvariantErrors(IContent? content, string[] savingCultures, string? defaultCulture)
{
if (content == null) throw new ArgumentNullException(nameof(content));
if (savingCultures == null) throw new ArgumentNullException(nameof(savingCultures));
diff --git a/src/Umbraco.Core/Persistence/Repositories/IUserGroupRepository.cs b/src/Umbraco.Core/Persistence/Repositories/IUserGroupRepository.cs
index f90596b1f8..d5cf6fd762 100644
--- a/src/Umbraco.Core/Persistence/Repositories/IUserGroupRepository.cs
+++ b/src/Umbraco.Core/Persistence/Repositories/IUserGroupRepository.cs
@@ -38,7 +38,7 @@ namespace Umbraco.Cms.Core.Persistence.Repositories
///
/// If true will include the group's default permissions if no permissions are explicitly assigned
/// Array of entity Ids, if empty will return permissions for the group for all entities
- EntityPermissionCollection GetPermissions(IReadOnlyUserGroup[] groups, bool fallbackToDefaultPermissions, params int[] nodeIds);
+ EntityPermissionCollection GetPermissions(IReadOnlyUserGroup[]? groups, bool fallbackToDefaultPermissions, params int[] nodeIds);
///
/// Replaces the same permission set for a single group to any number of entities
diff --git a/src/Umbraco.Core/Security/ContentPermissions.cs b/src/Umbraco.Core/Security/ContentPermissions.cs
index e1f8fb9e44..c26e53252d 100644
--- a/src/Umbraco.Core/Security/ContentPermissions.cs
+++ b/src/Umbraco.Core/Security/ContentPermissions.cs
@@ -243,18 +243,18 @@ namespace Umbraco.Cms.Core.Security
return startNodeIds.Any(x => formattedPath.Contains(string.Concat(",", x.ToString(CultureInfo.InvariantCulture), ",")));
}
- public static bool IsInBranchOfStartNode(string path, int[] startNodeIds, string[] startNodePaths, out bool hasPathAccess)
+ public static bool IsInBranchOfStartNode(string path, int[]? startNodeIds, string[]? startNodePaths, out bool hasPathAccess)
{
if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(path));
hasPathAccess = false;
// check for no access
- if (startNodeIds.Length == 0)
+ if (startNodeIds?.Length == 0)
return false;
// check for root access
- if (startNodeIds.Contains(Constants.System.Root))
+ if (startNodeIds?.Contains(Constants.System.Root) ?? false)
{
hasPathAccess = true;
return true;
diff --git a/src/Umbraco.Core/Services/ContentService.cs b/src/Umbraco.Core/Services/ContentService.cs
index b4fb38e872..9d5340f55d 100644
--- a/src/Umbraco.Core/Services/ContentService.cs
+++ b/src/Umbraco.Core/Services/ContentService.cs
@@ -951,7 +951,7 @@ namespace Umbraco.Cms.Core.Services
#region Save, Publish, Unpublish
///
- public OperationResult Save(IContent content, int userId = Constants.Security.SuperUserId,
+ public OperationResult Save(IContent content, int? userId = null,
ContentScheduleCollection? contentSchedule = null)
{
PublishedState publishedState = content.PublishedState;
@@ -979,13 +979,14 @@ namespace Umbraco.Cms.Core.Services
}
scope.WriteLock(Constants.Locks.ContentTree);
+ userId ??= Constants.Security.SuperUserId;
if (content.HasIdentity == false)
{
- content.CreatorId = userId;
+ content.CreatorId = userId.Value;
}
- content.WriterId = userId;
+ content.WriterId = userId.Value;
//track the cultures that have changed
List? culturesChanging = content.ContentType.VariesByCulture()
@@ -1021,12 +1022,12 @@ namespace Umbraco.Cms.Core.Services
if (languages is not null)
{
var langs = string.Join(", ", languages);
- Audit(AuditType.SaveVariant, userId, content.Id, $"Saved languages: {langs}", langs);
+ Audit(AuditType.SaveVariant, userId.Value, content.Id, $"Saved languages: {langs}", langs);
}
}
else
{
- Audit(AuditType.Save, userId, content.Id);
+ Audit(AuditType.Save, userId.Value, content.Id);
}
scope.Complete();
@@ -2752,8 +2753,12 @@ namespace Umbraco.Cms.Core.Services
/// The to send to publication
/// Optional Id of the User issuing the send to publication
/// True if sending publication was successful otherwise false
- public bool SendToPublication(IContent content, int userId = Constants.Security.SuperUserId)
+ public bool SendToPublication(IContent? content, int userId = Constants.Security.SuperUserId)
{
+ if (content is null)
+ {
+ return false;
+ }
EventMessages evtMsgs = EventMessagesFactory.Get();
using (IScope scope = ScopeProvider.CreateScope())
diff --git a/src/Umbraco.Core/Services/ContentTypeServiceBaseOfTRepositoryTItemTService.cs b/src/Umbraco.Core/Services/ContentTypeServiceBaseOfTRepositoryTItemTService.cs
index 06b0f1af76..d9eb95a4be 100644
--- a/src/Umbraco.Core/Services/ContentTypeServiceBaseOfTRepositoryTItemTService.cs
+++ b/src/Umbraco.Core/Services/ContentTypeServiceBaseOfTRepositoryTItemTService.cs
@@ -297,7 +297,7 @@ namespace Umbraco.Cms.Core.Services
}
}
- public IEnumerable GetAll(IEnumerable ids)
+ public IEnumerable GetAll(IEnumerable? ids)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
diff --git a/src/Umbraco.Core/Services/FileService.cs b/src/Umbraco.Core/Services/FileService.cs
index e943afec88..0d65ac1c2a 100644
--- a/src/Umbraco.Core/Services/FileService.cs
+++ b/src/Umbraco.Core/Services/FileService.cs
@@ -65,7 +65,7 @@ namespace Umbraco.Cms.Core.Services
}
///
- public IStylesheet? GetStylesheet(string path)
+ public IStylesheet? GetStylesheet(string? path)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -74,8 +74,13 @@ namespace Umbraco.Cms.Core.Services
}
///
- public void SaveStylesheet(IStylesheet stylesheet, int userId = Constants.Security.SuperUserId)
+ public void SaveStylesheet(IStylesheet? stylesheet, int? userId = null)
{
+ if (stylesheet is null)
+ {
+ return;
+ }
+
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
@@ -86,17 +91,17 @@ namespace Umbraco.Cms.Core.Services
return;
}
-
+ userId ??= Constants.Security.SuperUserId;
_stylesheetRepository.Save(stylesheet);
scope.Notifications.Publish(new StylesheetSavedNotification(stylesheet, eventMessages).WithStateFrom(savingNotification));
- Audit(AuditType.Save, userId, -1, "Stylesheet");
+ Audit(AuditType.Save, userId.Value, -1, "Stylesheet");
scope.Complete();
}
}
///
- public void DeleteStylesheet(string path, int userId = Constants.Security.SuperUserId)
+ public void DeleteStylesheet(string path, int? userId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
@@ -115,10 +120,11 @@ namespace Umbraco.Cms.Core.Services
return; // causes rollback
}
+ userId ??= Constants.Security.SuperUserId;
_stylesheetRepository.Delete(stylesheet);
scope.Notifications.Publish(new StylesheetDeletedNotification(stylesheet, eventMessages).WithStateFrom(deletingNotification));
- Audit(AuditType.Delete, userId, -1, "Stylesheet");
+ Audit(AuditType.Delete, userId.Value, -1, "Stylesheet");
scope.Complete();
}
@@ -186,7 +192,7 @@ namespace Umbraco.Cms.Core.Services
}
///
- public IScript? GetScript(string name)
+ public IScript? GetScript(string? name)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -195,8 +201,13 @@ namespace Umbraco.Cms.Core.Services
}
///
- public void SaveScript(IScript script, int userId = Constants.Security.SuperUserId)
+ public void SaveScript(IScript? script, int? userId = Constants.Security.SuperUserId)
{
+ if (script is null)
+ {
+ return;
+ }
+
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
@@ -210,13 +221,13 @@ namespace Umbraco.Cms.Core.Services
_scriptRepository.Save(script);
scope.Notifications.Publish(new ScriptSavedNotification(script, eventMessages).WithStateFrom(savingNotification));
- Audit(AuditType.Save, userId, -1, "Script");
+ Audit(AuditType.Save, userId.Value, -1, "Script");
scope.Complete();
}
}
///
- public void DeleteScript(string path, int userId = Constants.Security.SuperUserId)
+ public void DeleteScript(string path, int? userId = null)
{
using (IScope scope = ScopeProvider.CreateScope())
{
@@ -235,10 +246,11 @@ namespace Umbraco.Cms.Core.Services
return;
}
+ userId ??= Constants.Security.SuperUserId;
_scriptRepository.Delete(script);
scope.Notifications.Publish(new ScriptDeletedNotification(script, eventMessages).WithStateFrom(deletingNotification));
- Audit(AuditType.Delete, userId, -1, "Script");
+ Audit(AuditType.Delete, userId.Value, -1, "Script");
scope.Complete();
}
}
@@ -622,7 +634,7 @@ namespace Umbraco.Cms.Core.Services
#region Partial Views
- public IEnumerable GetPartialViewSnippetNames(params string[] filterNames)
+ public IEnumerable GetPartialViewSnippetNames(params string[] filterNames)
{
var snippetPath = _hostingEnvironment.MapPathContentRoot($"{Constants.SystemDirectories.Umbraco}/PartialViewMacros/Templates/");
var files = Directory.GetFiles(snippetPath, "*.cshtml")
@@ -635,7 +647,7 @@ namespace Umbraco.Cms.Core.Services
.OrderBy(x => x?.Length)
.ToArray();
- return empty.Union(files.Except(empty));
+ return empty.Union(files.Except(empty)).WhereNotNull();
}
public void DeletePartialViewFolder(string folderPath)
@@ -680,13 +692,13 @@ namespace Umbraco.Cms.Core.Services
}
}
- public Attempt CreatePartialView(IPartialView partialView, string? snippetName = null, int userId = Constants.Security.SuperUserId) =>
+ public Attempt CreatePartialView(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId) =>
CreatePartialViewMacro(partialView, PartialViewType.PartialView, snippetName, userId);
- public Attempt CreatePartialViewMacro(IPartialView partialView, string? snippetName = null, int userId = Constants.Security.SuperUserId) =>
+ public Attempt CreatePartialViewMacro(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId) =>
CreatePartialViewMacro(partialView, PartialViewType.PartialViewMacro, snippetName, userId);
- private Attempt CreatePartialViewMacro(IPartialView partialView, PartialViewType partialViewType, string? snippetName = null, int userId = Constants.Security.SuperUserId)
+ private Attempt CreatePartialViewMacro(IPartialView partialView, PartialViewType partialViewType, string? snippetName = null, int? userId = Constants.Security.SuperUserId)
{
string partialViewHeader;
switch (partialViewType)
@@ -735,7 +747,7 @@ namespace Umbraco.Cms.Core.Services
if (scope.Notifications.PublishCancelable(creatingNotification))
{
scope.Complete();
- return Attempt.Fail();
+ return Attempt.Fail();
}
IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
@@ -748,24 +760,25 @@ namespace Umbraco.Cms.Core.Services
scope.Notifications.Publish(new PartialViewCreatedNotification(partialView, eventMessages).WithStateFrom(creatingNotification));
- Audit(AuditType.Save, userId, -1, partialViewType.ToString());
+ Audit(AuditType.Save, userId!.Value, -1, partialViewType.ToString());
scope.Complete();
}
- return Attempt.Succeed(partialView);
+ return Attempt.Succeed(partialView);
}
- public bool DeletePartialView(string path, int userId = Constants.Security.SuperUserId) =>
+ public bool DeletePartialView(string path, int? userId = null) =>
DeletePartialViewMacro(path, PartialViewType.PartialView, userId);
- public bool DeletePartialViewMacro(string path, int userId = Constants.Security.SuperUserId) =>
+ public bool DeletePartialViewMacro(string path, int? userId = null) =>
DeletePartialViewMacro(path, PartialViewType.PartialViewMacro, userId);
- private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int userId = Constants.Security.SuperUserId)
+ private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int? userId = null)
{
using (IScope scope = ScopeProvider.CreateScope())
{
+
IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
IPartialView? partialView = repository.Get(path);
if (partialView == null)
@@ -782,9 +795,10 @@ namespace Umbraco.Cms.Core.Services
return false;
}
+ userId ??= Constants.Security.SuperUserId;
repository.Delete(partialView);
scope.Notifications.Publish(new PartialViewDeletedNotification(partialView, eventMessages).WithStateFrom(deletingNotification));
- Audit(AuditType.Delete, userId, -1, partialViewType.ToString());
+ Audit(AuditType.Delete, userId.Value, -1, partialViewType.ToString());
scope.Complete();
}
@@ -792,13 +806,13 @@ namespace Umbraco.Cms.Core.Services
return true;
}
- public Attempt SavePartialView(IPartialView partialView, int userId = Constants.Security.SuperUserId) =>
+ public Attempt SavePartialView(IPartialView partialView, int? userId = null) =>
SavePartialView(partialView, PartialViewType.PartialView, userId);
- public Attempt SavePartialViewMacro(IPartialView partialView, int userId = Constants.Security.SuperUserId) =>
+ public Attempt SavePartialViewMacro(IPartialView partialView, int? userId = null) =>
SavePartialView(partialView, PartialViewType.PartialViewMacro, userId);
- private Attempt SavePartialView(IPartialView partialView, PartialViewType partialViewType, int userId = Constants.Security.SuperUserId)
+ private Attempt SavePartialView(IPartialView partialView, PartialViewType partialViewType, int? userId = null)
{
using (IScope scope = ScopeProvider.CreateScope())
{
@@ -810,10 +824,11 @@ namespace Umbraco.Cms.Core.Services
return Attempt.Fail();
}
+ userId ??= Constants.Security.SuperUserId;
IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
repository.Save(partialView);
- Audit(AuditType.Save, userId, -1, partialViewType.ToString());
+ Audit(AuditType.Save, userId.Value, -1, partialViewType.ToString());
scope.Notifications.Publish(new PartialViewSavedNotification(partialView, eventMessages).WithStateFrom(savingNotification));
scope.Complete();
diff --git a/src/Umbraco.Core/Services/IContentService.cs b/src/Umbraco.Core/Services/IContentService.cs
index e53f091c49..9899861a18 100644
--- a/src/Umbraco.Core/Services/IContentService.cs
+++ b/src/Umbraco.Core/Services/IContentService.cs
@@ -84,7 +84,7 @@ namespace Umbraco.Cms.Core.Services
///
/// Gets documents.
///
- IEnumerable? GetByIds(IEnumerable ids);
+ IEnumerable GetByIds(IEnumerable ids);
///
/// Gets documents.
@@ -250,7 +250,7 @@ namespace Umbraco.Cms.Core.Services
///
/// Saves a document.
///
- OperationResult Save(IContent content, int userId = Constants.Security.SuperUserId, ContentScheduleCollection? contentSchedule = null);
+ OperationResult Save(IContent content, int? userId = null, ContentScheduleCollection? contentSchedule = null);
///
/// Saves documents.
@@ -460,7 +460,7 @@ namespace Umbraco.Cms.Core.Services
///
/// Saves a document and raises the "sent to publication" events.
///
- bool SendToPublication(IContent content, int userId = Constants.Security.SuperUserId);
+ bool SendToPublication(IContent? content, int userId = Constants.Security.SuperUserId);
///
/// Publishes and unpublishes scheduled documents.
diff --git a/src/Umbraco.Core/Services/IContentTypeServiceBase.cs b/src/Umbraco.Core/Services/IContentTypeServiceBase.cs
index 54e3c157f9..3835491cb4 100644
--- a/src/Umbraco.Core/Services/IContentTypeServiceBase.cs
+++ b/src/Umbraco.Core/Services/IContentTypeServiceBase.cs
@@ -45,7 +45,7 @@ namespace Umbraco.Cms.Core.Services
bool HasContentNodes(int id);
IEnumerable GetAll(params int[] ids);
- IEnumerable GetAll(IEnumerable ids);
+ IEnumerable GetAll(IEnumerable? ids);
IEnumerable GetDescendants(int id, bool andSelf); // parent-child axis
IEnumerable GetComposedOf(int id); // composition axis
diff --git a/src/Umbraco.Core/Services/IFileService.cs b/src/Umbraco.Core/Services/IFileService.cs
index e0faf5ae9a..b6b4772d0d 100644
--- a/src/Umbraco.Core/Services/IFileService.cs
+++ b/src/Umbraco.Core/Services/IFileService.cs
@@ -10,7 +10,7 @@ namespace Umbraco.Cms.Core.Services
///
public interface IFileService : IService
{
- IEnumerable GetPartialViewSnippetNames(params string[] filterNames);
+ IEnumerable GetPartialViewSnippetNames(params string[] filterNames);
void CreatePartialViewFolder(string folderPath);
void CreatePartialViewMacroFolder(string folderPath);
void DeletePartialViewFolder(string folderPath);
@@ -24,12 +24,12 @@ namespace Umbraco.Cms.Core.Services
IPartialView? GetPartialView(string path);
IPartialView? GetPartialViewMacro(string path);
- Attempt CreatePartialView(IPartialView partialView, string? snippetName = null, int userId = Constants.Security.SuperUserId);
- Attempt CreatePartialViewMacro(IPartialView partialView, string? snippetName = null, int userId = Constants.Security.SuperUserId);
- bool DeletePartialView(string path, int userId = Constants.Security.SuperUserId);
- bool DeletePartialViewMacro(string path, int userId = Constants.Security.SuperUserId);
- Attempt SavePartialView(IPartialView partialView, int userId = Constants.Security.SuperUserId);
- Attempt SavePartialViewMacro(IPartialView partialView, int userId = Constants.Security.SuperUserId);
+ Attempt CreatePartialView(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId);
+ Attempt CreatePartialViewMacro(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId);
+ bool DeletePartialView(string path, int? userId = null);
+ bool DeletePartialViewMacro(string path, int? userId = null);
+ Attempt SavePartialView(IPartialView partialView, int? userId = null);
+ Attempt SavePartialViewMacro(IPartialView partialView, int? userId = null);
///
/// Gets the content of a partial view as a stream.
@@ -84,21 +84,21 @@ namespace Umbraco.Cms.Core.Services
///
/// Path of the stylesheet incl. extension
/// A object
- IStylesheet? GetStylesheet(string path);
+ IStylesheet? GetStylesheet(string? path);
///
/// Saves a
///
/// to save
/// Optional id of the user saving the stylesheet
- void SaveStylesheet(IStylesheet stylesheet, int userId = Constants.Security.SuperUserId);
+ void SaveStylesheet(IStylesheet? stylesheet, int? userId = null);
///
/// Deletes a stylesheet by its name
///
/// Name incl. extension of the Stylesheet to delete
/// Optional id of the user deleting the stylesheet
- void DeleteStylesheet(string path, int userId = Constants.Security.SuperUserId);
+ void DeleteStylesheet(string path, int? userId = null);
///
/// Creates a folder for style sheets
@@ -145,21 +145,21 @@ namespace Umbraco.Cms.Core.Services
///
/// Name of the script incl. extension
/// A object
- IScript? GetScript(string name);
+ IScript? GetScript(string? name);
///
/// Saves a
///
/// to save
/// Optional id of the user saving the script
- void SaveScript(IScript script, int userId = Constants.Security.SuperUserId);
+ void SaveScript(IScript? script, int? userId = Constants.Security.SuperUserId);
///
/// Deletes a script by its name
///
/// Name incl. extension of the Script to delete
/// Optional id of the user deleting the script
- void DeleteScript(string path, int userId = Constants.Security.SuperUserId);
+ void DeleteScript(string path, int? userId = null);
///
/// Creates a folder for scripts
diff --git a/src/Umbraco.Core/Services/INotificationService.cs b/src/Umbraco.Core/Services/INotificationService.cs
index ecb5945f7c..cf65b1aa67 100644
--- a/src/Umbraco.Core/Services/INotificationService.cs
+++ b/src/Umbraco.Core/Services/INotificationService.cs
@@ -38,7 +38,7 @@ namespace Umbraco.Cms.Core.Services
///
/// Notifications are inherited from the parent so any child node will also have notifications assigned based on it's parent (ancestors)
///
- IEnumerable? GetUserNotifications(IUser user, string path);
+ IEnumerable? GetUserNotifications(IUser? user, string path);
///
/// Returns the notifications for an entity
@@ -75,7 +75,7 @@ namespace Umbraco.Cms.Core.Services
///
/// This performs a full replace
///
- IEnumerable SetNotifications(IUser user, IEntity entity, string[] actions);
+ IEnumerable? SetNotifications(IUser? user, IEntity entity, string[] actions);
///
/// Creates a new notification
diff --git a/src/Umbraco.Core/Services/IUserService.cs b/src/Umbraco.Core/Services/IUserService.cs
index 10f6a04020..5478a924e3 100644
--- a/src/Umbraco.Core/Services/IUserService.cs
+++ b/src/Umbraco.Core/Services/IUserService.cs
@@ -139,7 +139,7 @@ namespace Umbraco.Cms.Core.Services
///
/// This will return the default permissions for the user's groups for node ids that don't have explicitly defined permissions
///
- EntityPermissionCollection GetPermissions(IUser user, params int[] nodeIds);
+ EntityPermissionCollection GetPermissions(IUser? user, params int[] nodeIds);
///
/// Get explicitly assigned permissions for groups and optional node Ids
@@ -157,7 +157,7 @@ namespace Umbraco.Cms.Core.Services
///
/// User to check permissions for
/// Path to check permissions for
- EntityPermissionSet GetPermissionsForPath(IUser user, string? path);
+ EntityPermissionSet GetPermissionsForPath(IUser? user, string? path);
///
/// Gets the permissions for the provided groups and path
diff --git a/src/Umbraco.Core/Services/NotificationService.cs b/src/Umbraco.Core/Services/NotificationService.cs
index 7a7ad9d98a..b579f6f7f7 100644
--- a/src/Umbraco.Core/Services/NotificationService.cs
+++ b/src/Umbraco.Core/Services/NotificationService.cs
@@ -167,8 +167,13 @@ namespace Umbraco.Cms.Core.Services
///
/// Notifications are inherited from the parent so any child node will also have notifications assigned based on it's parent (ancestors)
///
- public IEnumerable? GetUserNotifications(IUser user, string path)
+ public IEnumerable? GetUserNotifications(IUser? user, string path)
{
+ if (user is null)
+ {
+ return null;
+ }
+
var userNotifications = GetUserNotifications(user);
return FilterUserNotificationsByPath(userNotifications, path);
}
@@ -246,8 +251,13 @@ namespace Umbraco.Cms.Core.Services
///
/// This performs a full replace
///
- public IEnumerable SetNotifications(IUser user, IEntity entity, string[] actions)
+ public IEnumerable? SetNotifications(IUser? user, IEntity entity, string[] actions)
{
+ if (user is null)
+ {
+ return null;
+ }
+
using (var scope = _uowProvider.CreateScope())
{
var notifications = _notificationsRepository.SetNotifications(user, entity, actions);
diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs
index 87922a5d83..680882a990 100644
--- a/src/Umbraco.Core/Services/UserService.cs
+++ b/src/Umbraco.Core/Services/UserService.cs
@@ -915,11 +915,11 @@ namespace Umbraco.Cms.Core.Services
/// User to retrieve permissions for
/// Specifying nothing will return all permissions for all nodes
/// An enumerable list of
- public EntityPermissionCollection GetPermissions(IUser user, params int[] nodeIds)
+ public EntityPermissionCollection GetPermissions(IUser? user, params int[] nodeIds)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
- return _userGroupRepository.GetPermissions(user.Groups.ToArray(), true, nodeIds);
+ return _userGroupRepository.GetPermissions(user?.Groups.ToArray(), true, nodeIds);
}
}
@@ -964,7 +964,7 @@ namespace Umbraco.Cms.Core.Services
///
/// User to check permissions for
/// Path to check permissions for
- public EntityPermissionSet GetPermissionsForPath(IUser user, string? path)
+ public EntityPermissionSet GetPermissionsForPath(IUser? user, string? path)
{
var nodeIds = path?.GetIdsFromPathReversed();
diff --git a/src/Umbraco.Core/Trees/ISearchableTree.cs b/src/Umbraco.Core/Trees/ISearchableTree.cs
index 743fd10a87..018aa88ae5 100644
--- a/src/Umbraco.Core/Trees/ISearchableTree.cs
+++ b/src/Umbraco.Core/Trees/ISearchableTree.cs
@@ -22,6 +22,6 @@ namespace Umbraco.Cms.Core.Trees
/// A starting point for the search, generally a node id, but for members this is a member type alias
///
///
- IEnumerable Search(string query, int pageSize, long pageIndex, out long totalFound, string? searchFrom = null);
+ IEnumerable Search(string query, int pageSize, long pageIndex, out long totalFound, string? searchFrom = null);
}
}
diff --git a/src/Umbraco.Core/Trees/ITree.cs b/src/Umbraco.Core/Trees/ITree.cs
index b114b83d22..106b3eef37 100644
--- a/src/Umbraco.Core/Trees/ITree.cs
+++ b/src/Umbraco.Core/Trees/ITree.cs
@@ -19,7 +19,7 @@
///
/// Gets the tree group.
///
- string TreeGroup { get; }
+ string? TreeGroup { get; }
///
/// Gets the tree alias.
@@ -29,7 +29,7 @@
///
/// Gets or sets the tree title (fallback if the tree alias isn't localized)
///
- string TreeTitle { get; }
+ string? TreeTitle { get; }
///
/// Gets the tree use.
diff --git a/src/Umbraco.Core/Trees/Tree.cs b/src/Umbraco.Core/Trees/Tree.cs
index 7ba01880d7..f229dd8019 100644
--- a/src/Umbraco.Core/Trees/Tree.cs
+++ b/src/Umbraco.Core/Trees/Tree.cs
@@ -11,7 +11,7 @@ namespace Umbraco.Cms.Core.Trees
[DebuggerDisplay("Tree - {SectionAlias}/{TreeAlias}")]
public class Tree : ITree
{
- public Tree(int sortOrder, string applicationAlias, string group, string alias, string title, TreeUse use, Type treeControllerType, bool isSingleNodeTree)
+ public Tree(int sortOrder, string applicationAlias, string? group, string alias, string? title, TreeUse use, Type treeControllerType, bool isSingleNodeTree)
{
SortOrder = sortOrder;
SectionAlias = applicationAlias ?? throw new ArgumentNullException(nameof(applicationAlias));
@@ -30,13 +30,13 @@ namespace Umbraco.Cms.Core.Trees
public string SectionAlias { get; set; }
///
- public string TreeGroup { get; }
+ public string? TreeGroup { get; }
///
public string TreeAlias { get; }
///
- public string TreeTitle { get; set; }
+ public string? TreeTitle { get; set; }
///
public TreeUse TreeUse { get; set; }
diff --git a/src/Umbraco.Core/Trees/TreeNode.cs b/src/Umbraco.Core/Trees/TreeNode.cs
index ba856b6d3a..3c166c9fdd 100644
--- a/src/Umbraco.Core/Trees/TreeNode.cs
+++ b/src/Umbraco.Core/Trees/TreeNode.cs
@@ -22,7 +22,7 @@ namespace Umbraco.Cms.Core.Trees
/// The parent id for the current node
///
///
- public TreeNode(string nodeId, string? parentId, string getChildNodesUrl, string menuUrl)
+ public TreeNode(string nodeId, string? parentId, string? getChildNodesUrl, string? menuUrl)
{
if (nodeId == null) throw new ArgumentNullException(nameof(nodeId));
if (string.IsNullOrWhiteSpace(nodeId)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(nodeId));
@@ -65,13 +65,13 @@ namespace Umbraco.Cms.Core.Trees
/// The JSON URL to load the nodes children
///
[DataMember(Name = "childNodesUrl")]
- public string ChildNodesUrl { get; set; }
+ public string? ChildNodesUrl { get; set; }
///
/// The JSON URL to load the menu from
///
[DataMember(Name = "menuUrl")]
- public string MenuUrl { get; set; }
+ public string? MenuUrl { get; set; }
///
/// Returns true if the icon represents a CSS class instead of a file path
diff --git a/src/Umbraco.Infrastructure/Mapping/UmbracoMapper.cs b/src/Umbraco.Infrastructure/Mapping/UmbracoMapper.cs
index 9b4406ea83..9d24c8a6e5 100644
--- a/src/Umbraco.Infrastructure/Mapping/UmbracoMapper.cs
+++ b/src/Umbraco.Infrastructure/Mapping/UmbracoMapper.cs
@@ -133,7 +133,7 @@ namespace Umbraco.Cms.Core.Mapping
/// The target type.
/// The source object.
/// The target object.
- public TTarget? Map(object source)
+ public TTarget? Map(object? source)
=> Map(source, new MapperContext(this));
///
@@ -143,7 +143,7 @@ namespace Umbraco.Cms.Core.Mapping
/// The source object.
/// A mapper context preparation method.
/// The target object.
- public TTarget? Map(object source, Action f)
+ public TTarget? Map(object? source, Action f)
{
var context = new MapperContext(this);
f(context);
diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs
index d19c896690..7a3ca69db1 100644
--- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs
+++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserGroupRepository.cs
@@ -110,7 +110,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
///
/// If true will include the group's default permissions if no permissions are explicitly assigned
/// Array of entity Ids, if empty will return permissions for the group for all entities
- public EntityPermissionCollection GetPermissions(IReadOnlyUserGroup[] groups, bool fallbackToDefaultPermissions, params int[] nodeIds)
+ public EntityPermissionCollection GetPermissions(IReadOnlyUserGroup[]? groups, bool fallbackToDefaultPermissions, params int[] nodeIds)
{
if (groups == null) throw new ArgumentNullException(nameof(groups));
diff --git a/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs b/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs
index f426441192..79887c1c0f 100644
--- a/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs
+++ b/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs
@@ -61,7 +61,7 @@ namespace Umbraco.Cms.Infrastructure.Search
///
/// If set to true, user and group start node permissions will be ignored.
///
- public IEnumerable? ExamineSearch(
+ public IEnumerable ExamineSearch(
string query,
UmbracoEntityTypes entityType,
int pageSize,
@@ -145,8 +145,8 @@ namespace Umbraco.Cms.Infrastructure.Search
///
///
///
- private IEnumerable? MediaFromSearchResults(IEnumerable results)
- => _mapper.Map>(results);
+ private IEnumerable MediaFromSearchResults(IEnumerable results)
+ => _mapper.Map>(results) ?? Enumerable.Empty();
///
/// Returns a collection of entities for content based on search results
diff --git a/src/Umbraco.Infrastructure/Security/IUmbracoUserManager.cs b/src/Umbraco.Infrastructure/Security/IUmbracoUserManager.cs
index ec364eb850..5c46308cb1 100644
--- a/src/Umbraco.Infrastructure/Security/IUmbracoUserManager.cs
+++ b/src/Umbraco.Infrastructure/Security/IUmbracoUserManager.cs
@@ -59,7 +59,7 @@ namespace Umbraco.Cms.Core.Security
///
/// The that represents the asynchronous operation, containing the user matching the specified if it exists.
///
- Task FindByIdAsync(string userId);
+ Task FindByIdAsync(string? userId);
///
/// Generates a password reset token for the specified , using
@@ -88,7 +88,7 @@ namespace Umbraco.Cms.Core.Security
/// The that represents the asynchronous operation, containing the
/// of the operation.
///
- Task ConfirmEmailAsync(TUser user, string token);
+ Task ConfirmEmailAsync(TUser user, string? token);
///
/// Gets the user, if any, associated with the normalized value of the specified email address.
@@ -112,7 +112,7 @@ namespace Umbraco.Cms.Core.Security
/// The that represents the asynchronous operation, containing the
/// of the operation.
///
- Task ResetPasswordAsync(TUser user, string token, string newPassword);
+ Task ResetPasswordAsync(TUser user, string? token, string? newPassword);
///
/// Override to check the user approval value as well as the user lock out date, by default this only checks the user's locked out date
@@ -258,7 +258,7 @@ namespace Umbraco.Cms.Core.Security
///
/// A generated password
string GeneratePassword();
-
+
///
/// Used to validate the password without an identity user
/// Validation code is based on the default ValidatePasswordAsync code
@@ -345,7 +345,7 @@ namespace Umbraco.Cms.Core.Security
/// The login provide whose information should be removed.
/// The key given by the external login provider for the specified user.
/// The System.Threading.Tasks.Task that represents the asynchronous operation, containing the Microsoft.AspNetCore.Identity.IdentityResult of the operation.
- Task RemoveLoginAsync(TUser user, string loginProvider, string providerKey);
+ Task RemoveLoginAsync(TUser user, string? loginProvider, string? providerKey);
///
/// Resets the access failed count for the user
diff --git a/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs b/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs
index 7f006a056d..8cd596558f 100644
--- a/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs
+++ b/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs
@@ -89,7 +89,7 @@ namespace Umbraco.Cms.Core.Models.Trees
///
///
///
- public static TreeRootNode CreateSingleTreeRoot(string nodeId, string getChildNodesUrl, string menuUrl, string title, TreeNodeCollection children, bool isSingleNodeTree = false)
+ public static TreeRootNode CreateSingleTreeRoot(string nodeId, string? getChildNodesUrl, string? menuUrl, string? title, TreeNodeCollection? children, bool isSingleNodeTree = false)
{
return new TreeRootNode(nodeId, getChildNodesUrl, menuUrl)
{
@@ -105,7 +105,7 @@ namespace Umbraco.Cms.Core.Models.Trees
///
///
///
- private TreeRootNode(string nodeId, string getChildNodesUrl, string menuUrl)
+ private TreeRootNode(string nodeId, string? getChildNodesUrl, string? menuUrl)
: base(nodeId, null, getChildNodesUrl, menuUrl)
{
//default to false
diff --git a/src/Umbraco.Web.BackOffice/ActionResults/JavaScriptResult.cs b/src/Umbraco.Web.BackOffice/ActionResults/JavaScriptResult.cs
index 2d9b87b680..c092c57897 100644
--- a/src/Umbraco.Web.BackOffice/ActionResults/JavaScriptResult.cs
+++ b/src/Umbraco.Web.BackOffice/ActionResults/JavaScriptResult.cs
@@ -4,7 +4,7 @@ namespace Umbraco.Cms.Web.BackOffice.ActionResults
{
public class JavaScriptResult : ContentResult
{
- public JavaScriptResult(string script)
+ public JavaScriptResult(string? script)
{
this.Content = script;
this.ContentType = "application/javascript";
diff --git a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs
index d478784fa3..2d1e9198a2 100644
--- a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs
+++ b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs
@@ -145,7 +145,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
///
[ValidateAngularAntiForgeryToken]
[Authorize(Policy = AuthorizationPolicies.DenyLocalLoginIfConfigured)]
- public async Task> PostVerifyInvite([FromQuery] int id, [FromQuery] string token)
+ public async Task> PostVerifyInvite([FromQuery] int id, [FromQuery] string token)
{
if (string.IsNullOrWhiteSpace(token))
return NotFound();
@@ -158,7 +158,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
if (identityUser == null)
return NotFound();
- var result = await _userManager.ConfirmEmailAsync(identityUser, decoded);
+ var result = await _userManager.ConfirmEmailAsync(identityUser, decoded!);
if (result.Succeeded == false)
{
@@ -178,7 +178,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[ValidateAngularAntiForgeryToken]
public async Task PostUnLinkLogin(UnLinkLoginModel unlinkLoginModel)
{
- var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());
+ var user = await _userManager.FindByIdAsync(User.Identity?.GetUserId());
if (user == null) throw new InvalidOperationException("Could not find user");
var authType = (await _signInManager.GetExternalAuthenticationSchemesAsync())
@@ -275,13 +275,16 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
[SetAngularAntiForgeryTokens]
[CheckIfUserTicketDataIsStale]
- public UserDetail GetCurrentUser()
+ public UserDetail? GetCurrentUser()
{
- var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser;
+ var user = _backofficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;
var result = _umbracoMapper.Map(user);
- //set their remaining seconds
- result.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds();
+ if (result is not null)
+ {
+ //set their remaining seconds
+ result.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds();
+ }
return result;
}
@@ -297,11 +300,11 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccessWithoutApproval)]
[SetAngularAntiForgeryTokens]
[Authorize(Policy = AuthorizationPolicies.DenyLocalLoginIfConfigured)]
- public ActionResult GetCurrentInvitedUser()
+ public ActionResult GetCurrentInvitedUser()
{
- var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser;
+ var user = _backofficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;
- if (user.IsApproved)
+ if (user?.IsApproved ?? false)
{
// if they are approved, than they are no longer invited and we can return an error
return Forbid();
@@ -309,8 +312,11 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
var result = _umbracoMapper.Map(user);
- // set their remaining seconds
- result.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds();
+ if (result is not null)
+ {
+ // set their remaining seconds
+ result.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds();
+ }
return result;
}
@@ -321,7 +327,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
///
[SetAngularAntiForgeryTokens]
[Authorize(Policy = AuthorizationPolicies.DenyLocalLoginIfConfigured)]
- public async Task> PostLogin(LoginModel loginModel)
+ public async Task> PostLogin(LoginModel loginModel)
{
// Sign the user in with username/password, this also gives a chance for developers to
// custom verify the credentials and auto-link user accounts with a custom IBackOfficePasswordChecker
@@ -342,13 +348,13 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return new ValidationErrorResult($"The registered {typeof(IBackOfficeTwoFactorOptions)} of type {_backOfficeTwoFactorOptions.GetType()} did not return a view for two factor auth ");
}
- IUser attemptedUser = _userService.GetByUsername(loginModel.Username);
+ IUser? attemptedUser = _userService.GetByUsername(loginModel.Username);
// create a with information to display a custom two factor send code view
var verifyResponse = new ObjectResult(new
{
twoFactorView = twofactorView,
- userId = attemptedUser.Id
+ userId = attemptedUser?.Id
})
{
StatusCode = StatusCodes.Status402PaymentRequired
@@ -388,7 +394,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
var user = _userService.GetByEmail(model.Email);
if (user != null)
{
- var from = _globalSettings.Smtp.From;
+ var from = _globalSettings.Smtp?.From;
var code = await _userManager.GeneratePasswordResetTokenAsync(identityUser);
var callbackUrl = ConstructCallbackUrl(identityUser.Id, code);
@@ -445,7 +451,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return NotFound();
}
- var from = _globalSettings.Smtp.From;
+ var from = _globalSettings.Smtp?.From;
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, provider);
if (string.IsNullOrWhiteSpace(code))
@@ -479,7 +485,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[SetAngularAntiForgeryTokens]
[AllowAnonymous]
- public async Task> PostVerify2FACode(Verify2FACodeModel model)
+ public async Task> PostVerify2FACode(Verify2FACodeModel model)
{
if (ModelState.IsValid == false)
{
@@ -561,7 +567,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
{
var user = _userService.GetByUsername(identityUser.UserName);
// also check InvitedDate and never logged in, otherwise this would allow a disabled user to reactivate their account with a forgot password
- if (user.LastLoginDate == default && user.InvitedDate != null)
+ if (user?.LastLoginDate == default && user?.InvitedDate != null)
{
user.IsApproved = true;
user.InvitedDate = null;
diff --git a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs
index f85da612ab..e01759791d 100644
--- a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs
+++ b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs
@@ -184,7 +184,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return RedirectToAction(nameof(Default));
}
- var result = await _userManager.ConfirmEmailAsync(identityUser, decoded);
+ var result = await _userManager.ConfirmEmailAsync(identityUser, decoded!);
if (result.Succeeded == false)
{
@@ -249,9 +249,9 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
///
[HttpGet]
[AllowAnonymous]
- public async Task>> LocalizedText(string culture = null)
+ public async Task>> LocalizedText(string? culture = null)
{
- CultureInfo cultureInfo;
+ CultureInfo? cultureInfo;
if (string.IsNullOrWhiteSpace(culture))
{
// Force authentication to occur since this is not an authorized endpoint, we need this to get a user.
@@ -269,7 +269,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
cultureInfo = CultureInfo.GetCultureInfo(culture);
}
- var allValues = _textService.GetAllStoredValues(cultureInfo);
+ var allValues = _textService.GetAllStoredValues(cultureInfo!);
var pathedValues = allValues.Select(kv =>
{
var slashIndex = kv.Key.IndexOf('/');
@@ -320,7 +320,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[HttpPost]
[AllowAnonymous]
- public ActionResult ExternalLogin(string provider, string redirectUrl = null)
+ public ActionResult ExternalLogin(string provider, string? redirectUrl = null)
{
if (redirectUrl == null)
{
@@ -511,13 +511,13 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
}
else if (result == SignInResult.LockedOut)
{
- errors.Add($"The local user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} is locked out.");
+ errors.Add($"The local user {loginInfo.Principal.Identity?.Name} for the external provider {loginInfo.ProviderDisplayName} is locked out.");
}
else if (result == SignInResult.NotAllowed)
{
// This occurs when SignInManager.CanSignInAsync fails which is when RequireConfirmedEmail , RequireConfirmedPhoneNumber or RequireConfirmedAccount fails
// however since we don't enforce those rules (yet) this shouldn't happen.
- errors.Add($"The user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not confirmed their details and cannot sign in.");
+ errors.Add($"The user {loginInfo.Principal.Identity?.Name} for the external provider {loginInfo.ProviderDisplayName} has not confirmed their details and cannot sign in.");
}
else if (result == SignInResult.Failed)
{
@@ -527,7 +527,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
else if (result == ExternalLoginSignInResult.NotAllowed)
{
// This occurs when the external provider has approved the login but custom logic in OnExternalLogin has denined it.
- errors.Add($"The user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not been accepted and cannot sign in.");
+ errors.Add($"The user {loginInfo.Principal.Identity?.Name} for the external provider {loginInfo.ProviderDisplayName} has not been accepted and cannot sign in.");
}
else if (result == AutoLinkSignInResult.FailedNotLinked)
{
@@ -558,7 +558,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return response();
}
- private IActionResult RedirectToLocal(string returnUrl)
+ private IActionResult RedirectToLocal(string? returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
diff --git a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeNotificationsController.cs b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeNotificationsController.cs
index 27be8ec263..ad65941cbf 100644
--- a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeNotificationsController.cs
+++ b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeNotificationsController.cs
@@ -38,7 +38,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
///
///
///
- protected override ActionResult ValidationProblem(string errorMessage)
+ protected override ActionResult ValidationProblem(string? errorMessage)
=> ValidationProblem(errorMessage, string.Empty);
///
@@ -47,7 +47,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
///
///
///
- protected ActionResult ValidationProblem(string errorHeader, string errorMessage)
+ protected ActionResult ValidationProblem(string? errorHeader, string errorMessage)
{
var notificationModel = new SimpleNotificationModel
{
@@ -66,6 +66,6 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
// returning an object of INotificationModel will ensure that any pending
// notification messages are added to the response.
=> new ValidationErrorResult(new SimpleNotificationModel());
-
+
}
}
diff --git a/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs b/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs
index e5f82cc0e1..a302edc56b 100644
--- a/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs
+++ b/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs
@@ -78,34 +78,34 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
if (display == null) throw new ArgumentNullException("display");
if (string.IsNullOrWhiteSpace(type)) throw new ArgumentException("Value cannot be null or whitespace.", "type");
- var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser;
+ var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;
switch (type)
{
case Constants.Trees.PartialViews:
- var view = new PartialView(PartialViewType.PartialView, display.VirtualPath);
+ var view = new PartialView(PartialViewType.PartialView, display.VirtualPath ?? string.Empty);
view.Content = display.Content;
- var result = _fileService.CreatePartialView(view, display.Snippet, currentUser.Id);
+ var result = _fileService.CreatePartialView(view, display.Snippet, currentUser?.Id);
if (result.Success)
{
return Ok();
}
else
{
- return ValidationProblem(result.Exception.Message);
+ return ValidationProblem(result.Exception?.Message);
}
case Constants.Trees.PartialViewMacros:
- var viewMacro = new PartialView(PartialViewType.PartialViewMacro, display.VirtualPath);
+ var viewMacro = new PartialView(PartialViewType.PartialViewMacro, display.VirtualPath ?? string.Empty);
viewMacro.Content = display.Content;
- var resultMacro = _fileService.CreatePartialViewMacro(viewMacro, display.Snippet, currentUser.Id);
+ var resultMacro = _fileService.CreatePartialViewMacro(viewMacro, display.Snippet, currentUser?.Id);
if (resultMacro.Success)
return Ok();
else
- return ValidationProblem(resultMacro.Exception.Message);
+ return ValidationProblem(resultMacro.Exception?.Message);
case Constants.Trees.Scripts:
- var script = new Script(display.VirtualPath);
- _fileService.SaveScript(script, currentUser.Id);
+ var script = new Script(display.VirtualPath ?? string.Empty);
+ _fileService.SaveScript(script, currentUser?.Id);
return Ok();
default:
@@ -180,7 +180,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
/// This is a string but will be 'scripts' 'partialViews', 'partialViewMacros' or 'stylesheets'
/// The filename or URL encoded path of the file to open
/// The file and its contents from the virtualPath
- public ActionResult GetByPath(string type, string virtualPath)
+ public ActionResult GetByPath(string type, string virtualPath)
{
if (string.IsNullOrWhiteSpace(type)) throw new ArgumentException("Value cannot be null or whitespace.", "type");
if (string.IsNullOrWhiteSpace(virtualPath)) throw new ArgumentException("Value cannot be null or whitespace.", "virtualPath");
@@ -194,9 +194,14 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
if (view != null)
{
var display = _umbracoMapper.Map(view);
- display.FileType = Constants.Trees.PartialViews;
- display.Path = Url.GetTreePathFromFilePath(view.Path);
- display.Id = System.Web.HttpUtility.UrlEncode(view.Path);
+
+ if (display is not null)
+ {
+ display.FileType = Constants.Trees.PartialViews;
+ display.Path = Url.GetTreePathFromFilePath(view.Path);
+ display.Id = System.Web.HttpUtility.UrlEncode(view.Path);
+ }
+
return display;
}
@@ -206,9 +211,14 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
if (viewMacro != null)
{
var display = _umbracoMapper.Map(viewMacro);
- display.FileType = Constants.Trees.PartialViewMacros;
- display.Path = Url.GetTreePathFromFilePath(viewMacro.Path);
- display.Id = System.Web.HttpUtility.UrlEncode(viewMacro.Path);
+
+ if (display is not null)
+ {
+ display.FileType = Constants.Trees.PartialViewMacros;
+ display.Path = Url.GetTreePathFromFilePath(viewMacro.Path);
+ display.Id = System.Web.HttpUtility.UrlEncode(viewMacro.Path);
+ }
+
return display;
}
break;
@@ -217,9 +227,14 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
if (script != null)
{
var display = _umbracoMapper.Map(script);
- display.FileType = Constants.Trees.Scripts;
- display.Path = Url.GetTreePathFromFilePath(script.Path);
- display.Id = System.Web.HttpUtility.UrlEncode(script.Path);
+
+ if (display is not null)
+ {
+ display.FileType = Constants.Trees.Scripts;
+ display.Path = Url.GetTreePathFromFilePath(script.Path);
+ display.Id = System.Web.HttpUtility.UrlEncode(script.Path);
+ }
+
return display;
}
break;
@@ -228,9 +243,14 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
if (stylesheet != null)
{
var display = _umbracoMapper.Map(stylesheet);
- display.FileType = Constants.Trees.Stylesheets;
- display.Path = Url.GetTreePathFromFilePath(stylesheet.Path);
- display.Id = System.Web.HttpUtility.UrlEncode(stylesheet.Path);
+
+ if (display is not null)
+ {
+ display.FileType = Constants.Trees.Stylesheets;
+ display.Path = Url.GetTreePathFromFilePath(stylesheet.Path);
+ display.Id = System.Web.HttpUtility.UrlEncode(stylesheet.Path);
+ }
+
return display;
}
break;
@@ -276,41 +296,65 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
///
///
///
- public ActionResult GetScaffold(string type, string id, string snippetName = null)
+ public ActionResult GetScaffold(string type, string id, string? snippetName = null)
{
if (string.IsNullOrWhiteSpace(type)) throw new ArgumentException("Value cannot be null or whitespace.", "type");
if (string.IsNullOrWhiteSpace(id)) throw new ArgumentException("Value cannot be null or whitespace.", "id");
- CodeFileDisplay codeFileDisplay;
+ CodeFileDisplay? codeFileDisplay;
switch (type)
{
case Constants.Trees.PartialViews:
codeFileDisplay = _umbracoMapper.Map(new PartialView(PartialViewType.PartialView, string.Empty));
- codeFileDisplay.VirtualPath = Constants.SystemDirectories.PartialViews;
- if (snippetName.IsNullOrWhiteSpace() == false)
- codeFileDisplay.Content = _fileService.GetPartialViewSnippetContent(snippetName);
+ if (codeFileDisplay is not null)
+ {
+ codeFileDisplay.VirtualPath = Constants.SystemDirectories.PartialViews;
+ if (snippetName.IsNullOrWhiteSpace() == false)
+ {
+ codeFileDisplay.Content = _fileService.GetPartialViewSnippetContent(snippetName!);
+ }
+ }
+
break;
case Constants.Trees.PartialViewMacros:
codeFileDisplay = _umbracoMapper.Map(new PartialView(PartialViewType.PartialViewMacro, string.Empty));
- codeFileDisplay.VirtualPath = Constants.SystemDirectories.MacroPartials;
- if (snippetName.IsNullOrWhiteSpace() == false)
- codeFileDisplay.Content = _fileService.GetPartialViewMacroSnippetContent(snippetName);
+ if (codeFileDisplay is not null)
+ {
+ codeFileDisplay.VirtualPath = Constants.SystemDirectories.MacroPartials;
+ if (snippetName.IsNullOrWhiteSpace() == false)
+ {
+ codeFileDisplay.Content = _fileService.GetPartialViewMacroSnippetContent(snippetName!);
+ }
+ }
+
break;
case Constants.Trees.Scripts:
codeFileDisplay = _umbracoMapper.Map