diff --git a/src/Umbraco.Core/Extensions/ClaimsIdentityExtensions.cs b/src/Umbraco.Core/Extensions/ClaimsIdentityExtensions.cs
index c850583834..d1d71a9ca1 100644
--- a/src/Umbraco.Core/Extensions/ClaimsIdentityExtensions.cs
+++ b/src/Umbraco.Core/Extensions/ClaimsIdentityExtensions.cs
@@ -150,8 +150,8 @@ namespace Umbraco.Extensions
/// Allowed apps
/// Roles
public static void AddRequiredClaims(this ClaimsIdentity identity, string userId, string username,
- string realName, IEnumerable startContentNodes, IEnumerable startMediaNodes, string culture,
- string securityStamp, IEnumerable allowedApps, IEnumerable roles)
+ string? realName, IEnumerable? startContentNodes, IEnumerable? startMediaNodes, string culture,
+ string securityStamp, IEnumerable allowedApps, IEnumerable roles)
{
//This is the id that 'identity' uses to check for the user id
if (identity.HasClaim(x => x.Type == ClaimTypes.NameIdentifier) == false)
diff --git a/src/Umbraco.Core/IO/MediaFileManager.cs b/src/Umbraco.Core/IO/MediaFileManager.cs
index b7e30c3b19..c3462913ff 100644
--- a/src/Umbraco.Core/IO/MediaFileManager.cs
+++ b/src/Umbraco.Core/IO/MediaFileManager.cs
@@ -102,7 +102,7 @@ namespace Umbraco.Cms.Core.IO
/// The unique identifier of the property type owning the file.
/// The filesystem-relative path to the media file.
/// With the old media path scheme, this CREATES a new media path each time it is invoked.
- public string GetMediaPath(string filename, Guid cuid, Guid puid)
+ public string GetMediaPath(string? filename, Guid cuid, Guid puid)
{
filename = Path.GetFileName(filename);
if (filename == null)
diff --git a/src/Umbraco.Core/Media/UploadAutoFillProperties.cs b/src/Umbraco.Core/Media/UploadAutoFillProperties.cs
index a3c0f1347a..16d5381d9b 100644
--- a/src/Umbraco.Core/Media/UploadAutoFillProperties.cs
+++ b/src/Umbraco.Core/Media/UploadAutoFillProperties.cs
@@ -38,7 +38,7 @@ namespace Umbraco.Cms.Core.Media
/// The auto-fill configuration.
/// Variation language.
/// Variation segment.
- public void Reset(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string culture, string segment)
+ public void Reset(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string? culture, string? segment)
{
if (content == null) throw new ArgumentNullException(nameof(content));
if (autoFillConfig == null) throw new ArgumentNullException(nameof(autoFillConfig));
@@ -55,7 +55,7 @@ namespace Umbraco.Cms.Core.Media
/// The parameter is the path relative to the filesystem.
/// Variation language.
/// Variation segment.
- public void Populate(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string filepath, string culture, string segment)
+ public void Populate(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string filepath, string? culture, string? segment)
{
if (content == null) throw new ArgumentNullException(nameof(content));
if (autoFillConfig == null) throw new ArgumentNullException(nameof(autoFillConfig));
@@ -112,7 +112,7 @@ namespace Umbraco.Cms.Core.Media
}
}
- private void SetProperties(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string filepath, Stream? filestream, string culture, string segment)
+ private void SetProperties(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string filepath, Stream? filestream, string? culture, string? segment)
{
var extension = (Path.GetExtension(filepath) ?? string.Empty).TrimStart(Constants.CharArrays.Period);
@@ -123,7 +123,7 @@ namespace Umbraco.Cms.Core.Media
SetProperties(content, autoFillConfig, size, filestream?.Length, extension, culture, segment);
}
- private static void SetProperties(IContentBase content, ImagingAutoFillUploadField autoFillConfig, Size? size, long? length, string extension, string culture, string segment)
+ private static void SetProperties(IContentBase content, ImagingAutoFillUploadField autoFillConfig, Size? size, long? length, string extension, string? culture, string? segment)
{
if (content == null) throw new ArgumentNullException(nameof(content));
if (autoFillConfig == null) throw new ArgumentNullException(nameof(autoFillConfig));
@@ -141,7 +141,7 @@ namespace Umbraco.Cms.Core.Media
content.Properties[autoFillConfig.ExtensionFieldAlias]!.SetValue(extension, culture, segment);
}
- private static void ResetProperties(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string culture, string segment)
+ private static void ResetProperties(IContentBase content, ImagingAutoFillUploadField autoFillConfig, string? culture, string? segment)
{
if (content == null) throw new ArgumentNullException(nameof(content));
if (autoFillConfig == null) throw new ArgumentNullException(nameof(autoFillConfig));
diff --git a/src/Umbraco.Core/Models/Blocks/ContentAndSettingsReference.cs b/src/Umbraco.Core/Models/Blocks/ContentAndSettingsReference.cs
index 3cfcbf9122..f8677490ee 100644
--- a/src/Umbraco.Core/Models/Blocks/ContentAndSettingsReference.cs
+++ b/src/Umbraco.Core/Models/Blocks/ContentAndSettingsReference.cs
@@ -5,7 +5,7 @@ namespace Umbraco.Cms.Core.Models.Blocks
{
public struct ContentAndSettingsReference : IEquatable
{
- public ContentAndSettingsReference(Udi contentUdi, Udi settingsUdi)
+ public ContentAndSettingsReference(Udi? contentUdi, Udi? settingsUdi)
{
ContentUdi = contentUdi ?? throw new ArgumentNullException(nameof(contentUdi));
SettingsUdi = settingsUdi;
@@ -13,7 +13,7 @@ namespace Umbraco.Cms.Core.Models.Blocks
public Udi ContentUdi { get; }
- public Udi SettingsUdi { get; }
+ public Udi? SettingsUdi { get; }
public override bool Equals(object? obj) => obj is ContentAndSettingsReference reference && Equals(reference);
diff --git a/src/Umbraco.Core/Models/Editors/ContentPropertyData.cs b/src/Umbraco.Core/Models/Editors/ContentPropertyData.cs
index 2b3e38ad13..0255cfd40e 100644
--- a/src/Umbraco.Core/Models/Editors/ContentPropertyData.cs
+++ b/src/Umbraco.Core/Models/Editors/ContentPropertyData.cs
@@ -11,7 +11,7 @@ namespace Umbraco.Cms.Core.Models.Editors
///
public class ContentPropertyData
{
- public ContentPropertyData(object value, object dataTypeConfiguration)
+ public ContentPropertyData(object? value, object? dataTypeConfiguration)
{
Value = value;
DataTypeConfiguration = dataTypeConfiguration;
@@ -20,12 +20,12 @@ namespace Umbraco.Cms.Core.Models.Editors
///
/// The value submitted for the property
///
- public object Value { get; }
+ public object? Value { get; }
///
/// The data type configuration for the property.
///
- public object DataTypeConfiguration { get; }
+ public object? DataTypeConfiguration { get; }
///
/// Gets or sets the unique identifier of the content owning the property.
diff --git a/src/Umbraco.Core/Models/Editors/ContentPropertyFile.cs b/src/Umbraco.Core/Models/Editors/ContentPropertyFile.cs
index 6d008bc74f..d1bc9127ce 100644
--- a/src/Umbraco.Core/Models/Editors/ContentPropertyFile.cs
+++ b/src/Umbraco.Core/Models/Editors/ContentPropertyFile.cs
@@ -38,6 +38,6 @@
///
/// Gets or sets the temporary path where the file has been uploaded.
///
- public string? TempFilePath { get; set; }
+ public string TempFilePath { get; set; } = string.Empty;
}
}
diff --git a/src/Umbraco.Core/Models/IDataValueEditor.cs b/src/Umbraco.Core/Models/IDataValueEditor.cs
index e3f7100241..8d4841a114 100644
--- a/src/Umbraco.Core/Models/IDataValueEditor.cs
+++ b/src/Umbraco.Core/Models/IDataValueEditor.cs
@@ -54,7 +54,7 @@ namespace Umbraco.Cms.Core.Models
///
/// Converts a value posted by the editor to a property value.
///
- object? FromEditor(ContentPropertyData editorValue, object currentValue);
+ object? FromEditor(ContentPropertyData editorValue, object? currentValue);
///
/// Converts a property value to a value for the editor.
@@ -80,6 +80,6 @@ namespace Umbraco.Cms.Core.Models
///
XNode ConvertDbToXml(IPropertyType propertyType, object value);
- string ConvertDbToString(IPropertyType propertyType, object value);
+ string ConvertDbToString(IPropertyType propertyType, object? value);
}
}
diff --git a/src/Umbraco.Core/Models/Membership/IMembershipUser.cs b/src/Umbraco.Core/Models/Membership/IMembershipUser.cs
index 40acb05a55..517416341b 100644
--- a/src/Umbraco.Core/Models/Membership/IMembershipUser.cs
+++ b/src/Umbraco.Core/Models/Membership/IMembershipUser.cs
@@ -15,7 +15,7 @@ namespace Umbraco.Cms.Core.Models.Membership
///
/// Gets or sets the raw password value
///
- string RawPasswordValue { get; set; }
+ string? RawPasswordValue { get; set; }
///
/// The user's specific password config (i.e. algorithm type, etc...)
@@ -25,8 +25,8 @@ namespace Umbraco.Cms.Core.Models.Membership
string? Comments { get; set; }
bool IsApproved { get; set; }
bool IsLockedOut { get; set; }
- DateTime LastLoginDate { get; set; }
- DateTime LastPasswordChangeDate { get; set; }
+ DateTime? LastLoginDate { get; set; }
+ DateTime? LastPasswordChangeDate { get; set; }
DateTime LastLockoutDate { get; set; }
///
diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs
index 11b4ec2139..f5a4a87db7 100644
--- a/src/Umbraco.Core/Models/Membership/User.cs
+++ b/src/Umbraco.Core/Models/Membership/User.cs
@@ -41,7 +41,7 @@ namespace Umbraco.Cms.Core.Models.Membership
///
///
///
- public User(GlobalSettings globalSettings, string name, string email, string username, string rawPasswordValue)
+ public User(GlobalSettings globalSettings, string? name, string email, string username, string rawPasswordValue)
: this(globalSettings)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(name));
diff --git a/src/Umbraco.Core/Notifications/IStatefulNotification.cs b/src/Umbraco.Core/Notifications/IStatefulNotification.cs
index 87d2b58cde..7fa2382038 100644
--- a/src/Umbraco.Core/Notifications/IStatefulNotification.cs
+++ b/src/Umbraco.Core/Notifications/IStatefulNotification.cs
@@ -4,6 +4,6 @@ namespace Umbraco.Cms.Core.Notifications
{
public interface IStatefulNotification : INotification
{
- IDictionary? State { get; set; }
+ IDictionary State { get; set; }
}
}
diff --git a/src/Umbraco.Core/Notifications/StatefulNotification.cs b/src/Umbraco.Core/Notifications/StatefulNotification.cs
index 2ff89578f2..940e8ac45f 100644
--- a/src/Umbraco.Core/Notifications/StatefulNotification.cs
+++ b/src/Umbraco.Core/Notifications/StatefulNotification.cs
@@ -12,7 +12,7 @@ namespace Umbraco.Cms.Core.Notifications
/// This can be used by event subscribers to store state in the notification so they easily deal with custom state data between
/// a starting ("ing") and an ending ("ed") notification
///
- public IDictionary? State
+ public IDictionary State
{
get => _state ??= new Dictionary();
set => _state = value;
diff --git a/src/Umbraco.Core/Packaging/IPackageInstallation.cs b/src/Umbraco.Core/Packaging/IPackageInstallation.cs
index 8dbba39133..9a744a91fa 100644
--- a/src/Umbraco.Core/Packaging/IPackageInstallation.cs
+++ b/src/Umbraco.Core/Packaging/IPackageInstallation.cs
@@ -25,6 +25,6 @@ namespace Umbraco.Cms.Core.Packaging
///
///
///
- CompiledPackage ReadPackage(XDocument packageXmlFile);
+ CompiledPackage ReadPackage(XDocument? packageXmlFile);
}
}
diff --git a/src/Umbraco.Core/Persistence/Repositories/IAuditRepository.cs b/src/Umbraco.Core/Persistence/Repositories/IAuditRepository.cs
index 37394c9898..6d28a86b64 100644
--- a/src/Umbraco.Core/Persistence/Repositories/IAuditRepository.cs
+++ b/src/Umbraco.Core/Persistence/Repositories/IAuditRepository.cs
@@ -30,8 +30,8 @@ namespace Umbraco.Cms.Core.Persistence.Repositories
IQuery query,
long pageIndex, int pageSize, out long totalRecords,
Direction orderDirection,
- AuditType[] auditTypeFilter,
- IQuery customFilter);
+ AuditType[]? auditTypeFilter,
+ IQuery? customFilter);
IEnumerable Get(AuditType type, IQuery query);
}
diff --git a/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs
index 108a0d5dc2..e9063416af 100644
--- a/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs
+++ b/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs
@@ -6,7 +6,7 @@ namespace Umbraco.Cms.Core.Persistence.Repositories
{
public interface IDataTypeRepository : IReadWriteQueryRepository
{
- IEnumerable> Move(IDataType toMove, EntityContainer container);
+ IEnumerable> Move(IDataType toMove, EntityContainer? container);
///
/// Returns a dictionary of content type s and the property type aliases that use a
diff --git a/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs b/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs
index 639985e7c6..5384ef0813 100644
--- a/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs
+++ b/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs
@@ -86,7 +86,7 @@ namespace Umbraco.Cms.Core.PropertyEditors
: configurationEditorJsonSerializer.Deserialize>(configurationJson);
///
- public virtual object FromConfigurationEditor(IDictionary editorValues, object configuration)
+ public virtual object? FromConfigurationEditor(IDictionary editorValues, object configuration)
{
// by default, return the posted dictionary
// but only keep entries that have a non-null/empty value
@@ -124,7 +124,7 @@ namespace Umbraco.Cms.Core.PropertyEditors
}
///
- public virtual IDictionary? ToValueEditor(object? configuration)
+ public virtual IDictionary ToValueEditor(object? configuration)
=> ToConfigurationEditor(configuration);
}
diff --git a/src/Umbraco.Core/PropertyEditors/IConfigurationEditor.cs b/src/Umbraco.Core/PropertyEditors/IConfigurationEditor.cs
index 2d5653f394..d243bb79bf 100644
--- a/src/Umbraco.Core/PropertyEditors/IConfigurationEditor.cs
+++ b/src/Umbraco.Core/PropertyEditors/IConfigurationEditor.cs
@@ -59,7 +59,7 @@ namespace Umbraco.Cms.Core.PropertyEditors
///
/// The values posted by the configuration editor.
/// The current configuration object.
- object FromConfigurationEditor(IDictionary editorValues, object configuration);
+ object? FromConfigurationEditor(IDictionary editorValues, object configuration);
///
/// Converts the configuration object to values for the configuration editor.
diff --git a/src/Umbraco.Core/PublishedCache/PublishedElement.cs b/src/Umbraco.Core/PublishedCache/PublishedElement.cs
index de6eb1b316..1972e8a7f4 100644
--- a/src/Umbraco.Core/PublishedCache/PublishedElement.cs
+++ b/src/Umbraco.Core/PublishedCache/PublishedElement.cs
@@ -18,7 +18,7 @@ namespace Umbraco.Cms.Core.PublishedCache
{
// initializes a new instance of the PublishedElement class
// within the context of a published snapshot service (eg a published content property value)
- public PublishedElement(IPublishedContentType contentType, Guid key, Dictionary? values, bool previewing,
+ public PublishedElement(IPublishedContentType contentType, Guid key, Dictionary? values, bool previewing,
PropertyCacheLevel referenceCacheLevel, IPublishedSnapshotAccessor? publishedSnapshotAccessor)
{
if (key == Guid.Empty) throw new ArgumentException("Empty guid.");
@@ -50,12 +50,12 @@ namespace Umbraco.Cms.Core.PublishedCache
: this(contentType, key, values, previewing, PropertyCacheLevel.None, null)
{ }
- private static Dictionary GetCaseInsensitiveValueDictionary(Dictionary values)
+ private static Dictionary GetCaseInsensitiveValueDictionary(Dictionary values)
{
// ensure we ignore case for property aliases
var comparer = values.Comparer;
var ignoreCase = Equals(comparer, StringComparer.OrdinalIgnoreCase) || Equals(comparer, StringComparer.InvariantCultureIgnoreCase) || Equals(comparer, StringComparer.CurrentCultureIgnoreCase);
- return ignoreCase ? values : new Dictionary(values, StringComparer.OrdinalIgnoreCase);
+ return ignoreCase ? values : new Dictionary(values, StringComparer.OrdinalIgnoreCase);
}
#region ContentType
diff --git a/src/Umbraco.Core/Scoping/IScopeContext.cs b/src/Umbraco.Core/Scoping/IScopeContext.cs
index 1814486c0e..72523be9e2 100644
--- a/src/Umbraco.Core/Scoping/IScopeContext.cs
+++ b/src/Umbraco.Core/Scoping/IScopeContext.cs
@@ -37,7 +37,7 @@ namespace Umbraco.Cms.Core.Scoping
/// and action with the same key but only the first one is used, the others are ignored.
/// The action boolean parameter indicates whether the scope completed or not.
///
- T Enlist(string key, Func creator, Action? action = null, int priority = 100);
+ T? Enlist(string key, Func creator, Action? action = null, int priority = 100);
///
/// Gets an enlisted object.
@@ -45,7 +45,7 @@ namespace Umbraco.Cms.Core.Scoping
/// The type of the object.
/// The object unique identifier.
/// The enlisted object, if any, else the default value.
- T GetEnlisted(string key);
+ T? GetEnlisted(string key);
void ScopeExit(bool completed);
}
diff --git a/src/Umbraco.Core/Scoping/IScopeProvider.cs b/src/Umbraco.Core/Scoping/IScopeProvider.cs
index ab32ee3645..c9c30662b4 100644
--- a/src/Umbraco.Core/Scoping/IScopeProvider.cs
+++ b/src/Umbraco.Core/Scoping/IScopeProvider.cs
@@ -80,7 +80,7 @@ namespace Umbraco.Cms.Core.Scoping
///
/// Gets the scope context.
///
- IScopeContext Context { get; }
+ IScopeContext? Context { get; }
///
/// Creates an instance of
diff --git a/src/Umbraco.Core/Security/IIdentityUserToken.cs b/src/Umbraco.Core/Security/IIdentityUserToken.cs
index d7d3af6adf..0e7f22d72f 100644
--- a/src/Umbraco.Core/Security/IIdentityUserToken.cs
+++ b/src/Umbraco.Core/Security/IIdentityUserToken.cs
@@ -10,7 +10,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Gets or sets user Id for the user who owns this token
///
- string UserId { get; set; }
+ string? UserId { get; set; }
///
/// Gets or sets the login provider for the login (i.e. Facebook, Google)
diff --git a/src/Umbraco.Core/Security/IdentityUserToken.cs b/src/Umbraco.Core/Security/IdentityUserToken.cs
index 4a3c0f21cf..014001a3a9 100644
--- a/src/Umbraco.Core/Security/IdentityUserToken.cs
+++ b/src/Umbraco.Core/Security/IdentityUserToken.cs
@@ -8,7 +8,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Initializes a new instance of the class.
///
- public IdentityUserToken(string loginProvider, string name, string value, string userId)
+ public IdentityUserToken(string loginProvider, string? name, string? value, string? userId)
{
LoginProvider = loginProvider ?? throw new ArgumentNullException(nameof(loginProvider));
Name = name ?? throw new ArgumentNullException(nameof(name));
@@ -19,7 +19,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Initializes a new instance of the class.
///
- public IdentityUserToken(int id, string loginProvider, string name, string value, string userId, DateTime createDate)
+ public IdentityUserToken(int id, string? loginProvider, string? name, string? value, string userId, DateTime createDate)
{
Id = id;
LoginProvider = loginProvider ?? throw new ArgumentNullException(nameof(loginProvider));
@@ -39,6 +39,6 @@ namespace Umbraco.Cms.Core.Security
public string Value { get; set; }
///
- public string UserId { get; set; }
+ public string? UserId { get; set; }
}
}
diff --git a/src/Umbraco.Core/Serialization/IJsonSerializer.cs b/src/Umbraco.Core/Serialization/IJsonSerializer.cs
index ef2e712b9a..051055b564 100644
--- a/src/Umbraco.Core/Serialization/IJsonSerializer.cs
+++ b/src/Umbraco.Core/Serialization/IJsonSerializer.cs
@@ -4,8 +4,8 @@
{
string Serialize(object? input);
- T Deserialize(string input);
+ T? Deserialize(string input);
- T DeserializeSubset(string input, string key);
+ T? DeserializeSubset(string input, string key);
}
}
diff --git a/src/Umbraco.Core/Services/IContentService.cs b/src/Umbraco.Core/Services/IContentService.cs
index e16ef8cfa3..35fdb1f4d9 100644
--- a/src/Umbraco.Core/Services/IContentService.cs
+++ b/src/Umbraco.Core/Services/IContentService.cs
@@ -216,7 +216,7 @@ namespace Umbraco.Cms.Core.Services
/// Search text filter.
/// Ordering infos.
IEnumerable GetPagedOfTypes(int[] contentTypeIds, long pageIndex, int pageSize, out long totalRecords,
- IQuery filter, Ordering? ordering = null);
+ IQuery? filter, Ordering? ordering = null);
///
/// Counts documents of a given document type.
diff --git a/src/Umbraco.Core/Services/IDataTypeService.cs b/src/Umbraco.Core/Services/IDataTypeService.cs
index 727851ef02..f7c222925c 100644
--- a/src/Umbraco.Core/Services/IDataTypeService.cs
+++ b/src/Umbraco.Core/Services/IDataTypeService.cs
@@ -17,36 +17,36 @@ namespace Umbraco.Cms.Core.Services
///
IReadOnlyDictionary> GetReferences(int id);
- Attempt> CreateContainer(int parentId, Guid key, string name, int userId = Constants.Security.SuperUserId);
- Attempt SaveContainer(EntityContainer container, int userId = Constants.Security.SuperUserId);
- EntityContainer GetContainer(int containerId);
+ Attempt?> CreateContainer(int parentId, Guid key, string name, int userId = Constants.Security.SuperUserId);
+ Attempt SaveContainer(EntityContainer container, int userId = Constants.Security.SuperUserId);
+ EntityContainer? GetContainer(int containerId);
EntityContainer GetContainer(Guid containerId);
IEnumerable GetContainers(string folderName, int level);
IEnumerable GetContainers(IDataType dataType);
IEnumerable GetContainers(int[] containerIds);
- Attempt DeleteContainer(int containerId, int userId = Constants.Security.SuperUserId);
- Attempt> RenameContainer(int id, string name, int userId = Constants.Security.SuperUserId);
+ Attempt DeleteContainer(int containerId, int userId = Constants.Security.SuperUserId);
+ Attempt?> RenameContainer(int id, string name, int userId = Constants.Security.SuperUserId);
///
/// Gets a by its Name
///
/// Name of the
///
- IDataType GetDataType(string name);
+ IDataType? GetDataType(string name);
///
/// Gets a by its Id
///
/// Id of the
///
- IDataType GetDataType(int id);
+ IDataType? GetDataType(int id);
///
/// Gets a by its unique guid Id
///
/// Unique guid Id of the DataType
///
- IDataType GetDataType(Guid id);
+ IDataType? GetDataType(Guid id);
///
/// Gets all objects or those with the ids passed in
@@ -87,6 +87,6 @@ namespace Umbraco.Cms.Core.Services
/// Collection of objects with a matching control id
IEnumerable GetByEditorAlias(string propertyEditorAlias);
- Attempt> Move(IDataType toMove, int parentId);
+ Attempt?> Move(IDataType toMove, int parentId);
}
}
diff --git a/src/Umbraco.Core/Services/IEntityService.cs b/src/Umbraco.Core/Services/IEntityService.cs
index cb72735c02..6d43e37ac5 100644
--- a/src/Umbraco.Core/Services/IEntityService.cs
+++ b/src/Umbraco.Core/Services/IEntityService.cs
@@ -116,7 +116,7 @@ namespace Umbraco.Cms.Core.Services
/// The object type of the entities.
/// The unique identifiers of the entities.
/// If is empty, returns all entities.
- IEnumerable GetAll(UmbracoObjectTypes objectType, Guid[] keys);
+ IEnumerable GetAll(UmbracoObjectTypes objectType, Guid?[] keys);
///
/// Gets entities of a given object type.
diff --git a/src/Umbraco.Core/Services/IIdKeyMap.cs b/src/Umbraco.Core/Services/IIdKeyMap.cs
index 56be36c5fa..199ee23813 100644
--- a/src/Umbraco.Core/Services/IIdKeyMap.cs
+++ b/src/Umbraco.Core/Services/IIdKeyMap.cs
@@ -7,7 +7,7 @@ namespace Umbraco.Cms.Core.Services
{
Attempt GetIdForKey(Guid key, UmbracoObjectTypes umbracoObjectType);
Attempt GetIdForUdi(Udi udi);
- Attempt GetUdiForId(int id, UmbracoObjectTypes umbracoObjectType);
+ Attempt GetUdiForId(int id, UmbracoObjectTypes umbracoObjectType);
Attempt GetKeyForId(int id, UmbracoObjectTypes umbracoObjectType);
void ClearCache();
void ClearCache(int id);
diff --git a/src/Umbraco.Core/Services/IPackagingService.cs b/src/Umbraco.Core/Services/IPackagingService.cs
index 719f8e3396..8429898354 100644
--- a/src/Umbraco.Core/Services/IPackagingService.cs
+++ b/src/Umbraco.Core/Services/IPackagingService.cs
@@ -30,20 +30,20 @@ namespace Umbraco.Cms.Core.Services
///
IEnumerable GetAllInstalledPackages();
- InstalledPackage GetInstalledPackageByName(string packageName);
+ InstalledPackage? GetInstalledPackageByName(string packageName);
///
/// Returns the created packages
///
///
- IEnumerable GetAllCreatedPackages();
+ IEnumerable GetAllCreatedPackages();
///
/// Returns a created package by id
///
///
///
- PackageDefinition GetCreatedPackageById(int id);
+ PackageDefinition? GetCreatedPackageById(int id);
void DeleteCreatedPackage(int id, int userId = Constants.Security.SuperUserId);
diff --git a/src/Umbraco.Core/Services/IPropertyValidationService.cs b/src/Umbraco.Core/Services/IPropertyValidationService.cs
index 466eb39c66..8c7aee93df 100644
--- a/src/Umbraco.Core/Services/IPropertyValidationService.cs
+++ b/src/Umbraco.Core/Services/IPropertyValidationService.cs
@@ -34,6 +34,6 @@ namespace Umbraco.Cms.Core.Services
///
IEnumerable ValidatePropertyValue(
IPropertyType propertyType,
- object postedValue);
+ object? postedValue);
}
}
diff --git a/src/Umbraco.Core/Services/IRuntimeState.cs b/src/Umbraco.Core/Services/IRuntimeState.cs
index 2b72149042..3c765a0748 100644
--- a/src/Umbraco.Core/Services/IRuntimeState.cs
+++ b/src/Umbraco.Core/Services/IRuntimeState.cs
@@ -38,17 +38,17 @@ namespace Umbraco.Cms.Core.Services
///
/// Gets the current migration state.
///
- string CurrentMigrationState { get; }
+ string? CurrentMigrationState { get; }
///
/// Gets the final migration state.
///
- string FinalMigrationState { get; }
+ string? FinalMigrationState { get; }
///
/// Gets the exception that caused the boot to fail.
///
- BootFailedException BootFailedException { get; }
+ BootFailedException? BootFailedException { get; }
///
/// Determines the runtime level.
diff --git a/src/Umbraco.Core/Services/ITwoFactorLoginService.cs b/src/Umbraco.Core/Services/ITwoFactorLoginService.cs
index 33a96ad751..f30e371d6a 100644
--- a/src/Umbraco.Core/Services/ITwoFactorLoginService.cs
+++ b/src/Umbraco.Core/Services/ITwoFactorLoginService.cs
@@ -23,7 +23,7 @@ namespace Umbraco.Cms.Core.Services
///
/// Gets the secret for user or member and a specific provider.
///
- Task GetSecretForUserAndProviderAsync(Guid userOrMemberKey, string providerName);
+ Task GetSecretForUserAndProviderAsync(Guid userOrMemberKey, string providerName);
///
/// Gets the setup info for a specific user or member and a specific provider.
@@ -31,7 +31,7 @@ namespace Umbraco.Cms.Core.Services
///
/// The returned type can be anything depending on the setup providers. You will need to cast it to the type handled by the provider.
///
- Task
///
- internal Dictionary> GetReadLocks()
+ internal Dictionary>? GetReadLocks()
{
EnsureDbLocks();
// always delegate to root/parent scope.
@@ -547,7 +547,7 @@ namespace Umbraco.Cms.Core.Scoping
/// Used for testing. Ensures and gets and queued write locks.
///
///
- internal Dictionary> GetWriteLocks()
+ internal Dictionary>? GetWriteLocks()
{
EnsureDbLocks();
// always delegate to root/parent scope.
@@ -594,6 +594,10 @@ namespace Umbraco.Cms.Core.Scoping
}
else
{
+ if (_database is null)
+ {
+ return;
+ }
lock (_lockQueueLocker)
{
if (_queuedLocks?.Count > 0)
@@ -702,7 +706,7 @@ namespace Umbraco.Cms.Core.Scoping
/// Lock dictionary to report on.
/// String builder to write to.
/// The name to report the dictionary as.
- private void WriteLockDictionaryToString(Dictionary> dict, StringBuilder builder,
+ private void WriteLockDictionaryToString(Dictionary>? dict, StringBuilder builder,
string dictName)
{
if (dict?.Count > 0)
@@ -785,10 +789,10 @@ namespace Umbraco.Cms.Core.Scoping
{
if (completed)
{
- _fscope.Complete();
+ _fscope?.Complete();
}
- _fscope.Dispose();
+ _fscope?.Dispose();
_fscope = null;
}
}
@@ -808,7 +812,7 @@ namespace Umbraco.Cms.Core.Scoping
{
try
{
- _scopeProvider.AmbientContext.ScopeExit(completed);
+ _scopeProvider.AmbientContext?.ScopeExit(completed);
}
finally
{
@@ -879,17 +883,17 @@ namespace Umbraco.Cms.Core.Scoping
/// Lock ID to increment.
/// Instance ID of the scope requesting the lock.
/// Reference to the dictionary to increment on
- private void IncrementLock(int lockId, Guid instanceId, ref Dictionary> locks)
+ private void IncrementLock(int lockId, Guid instanceId, ref Dictionary>? locks)
{
// Since we've already checked that we're the parent in the WriteLockInner method, we don't need to check again.
// If it's the very first time a lock has been requested the WriteLocks dict hasn't been instantiated yet.
locks ??= new Dictionary>();
// Try and get the dict associated with the scope id.
- var locksDictFound = locks.TryGetValue(instanceId, out Dictionary locksDict);
+ var locksDictFound = locks.TryGetValue(instanceId, out Dictionary? locksDict);
if (locksDictFound)
{
- locksDict.TryGetValue(lockId, out var value);
+ locksDict!.TryGetValue(lockId, out var value);
locksDict[lockId] = value + 1;
}
else
@@ -1066,8 +1070,8 @@ namespace Umbraco.Cms.Core.Scoping
/// Delegate used to request the lock from the database with a timeout.
/// Optional timeout parameter to specify a timeout.
/// Lock identifiers to lock on.
- private void LockInner(IUmbracoDatabase db, Guid instanceId, ref Dictionary> locks,
- ref HashSet locksSet,
+ private void LockInner(IUmbracoDatabase db, Guid instanceId, ref Dictionary>? locks,
+ ref HashSet? locksSet,
Action obtainLock, Action obtainLockTimeout,
TimeSpan? timeout,
params int[] lockIds)
@@ -1099,7 +1103,7 @@ namespace Umbraco.Cms.Core.Scoping
{
// Something went wrong and we didn't get the lock
// Since we at this point have determined that we haven't got any lock with an ID of LockID, it's safe to completely remove it instead of decrementing.
- locks[instanceId].Remove(lockId);
+ locks?[instanceId].Remove(lockId);
// It needs to be removed from the HashSet as well, because that's how we determine to acquire a lock.
locksSet.Remove(lockId);
throw;
diff --git a/src/Umbraco.Infrastructure/Scoping/ScopeContext.cs b/src/Umbraco.Infrastructure/Scoping/ScopeContext.cs
index 9880bfa556..0522f6385f 100644
--- a/src/Umbraco.Infrastructure/Scoping/ScopeContext.cs
+++ b/src/Umbraco.Infrastructure/Scoping/ScopeContext.cs
@@ -8,7 +8,7 @@ namespace Umbraco.Cms.Core.Scoping
{
internal class ScopeContext : IScopeContext, IInstanceIdentifiable
{
- private Dictionary _enlisted;
+ private Dictionary? _enlisted;
public void ScopeExit(bool completed)
{
@@ -16,7 +16,7 @@ namespace Umbraco.Cms.Core.Scoping
return;
// TODO: can we create infinite loops? - what about nested events? will they just be plainly ignored = really bad?
- List exceptions = null;
+ List? exceptions = null;
List orderedEnlisted;
while ((orderedEnlisted = _enlisted.Values.OrderBy(x => x.Priority).ToList()).Count > 0)
{
@@ -55,22 +55,25 @@ namespace Umbraco.Cms.Core.Scoping
private class EnlistedObject : IEnlistedObject
{
- private readonly Action _action;
+ private readonly Action? _action;
- public EnlistedObject(T item, Action action, int priority)
+ public EnlistedObject(T? item, Action? action, int priority)
{
Item = item;
Priority = priority;
_action = action;
}
- public T Item { get; }
+ public T? Item { get; }
public int Priority { get; }
public void Execute(bool completed)
{
- _action(completed, Item);
+ if (_action is not null)
+ {
+ _action(completed, Item);
+ }
}
}
@@ -79,7 +82,7 @@ namespace Umbraco.Cms.Core.Scoping
Enlist(key, null, (completed, item) => action(completed), priority);
}
- public T Enlist(string key, Func creator, Action? action = null, int priority = 100)
+ public T? Enlist(string key, Func? creator, Action? action = null, int priority = 100)
{
var enlistedObjects = _enlisted ?? (_enlisted = new Dictionary());
@@ -96,7 +99,7 @@ namespace Umbraco.Cms.Core.Scoping
return enlistedOfT.Item;
}
- public T GetEnlisted(string key)
+ public T? GetEnlisted(string key)
{
var enlistedObjects = _enlisted;
if (enlistedObjects == null) return default;
diff --git a/src/Umbraco.Infrastructure/Scoping/ScopeContextualBase.cs b/src/Umbraco.Infrastructure/Scoping/ScopeContextualBase.cs
index bde8f79012..19a25f8d8f 100644
--- a/src/Umbraco.Infrastructure/Scoping/ScopeContextualBase.cs
+++ b/src/Umbraco.Infrastructure/Scoping/ScopeContextualBase.cs
@@ -25,7 +25,7 @@ namespace Umbraco.Cms.Core.Scoping
///
///
///
- public static T Get(IScopeProvider scopeProvider, string key, Func ctor)
+ public static T? Get(IScopeProvider scopeProvider, string key, Func ctor)
where T : ScopeContextualBase
{
// no scope context = create a non-scoped object
@@ -36,9 +36,12 @@ namespace Umbraco.Cms.Core.Scoping
// create & enlist the scoped object
var w = scopeContext.Enlist("ScopeContextualBase_" + key,
() => ctor(true),
- (completed, item) => { item.Release(completed); });
+ (completed, item) => { item?.Release(completed); });
- w._scoped = true;
+ if (w is not null)
+ {
+ w._scoped = true;
+ }
return w;
}
diff --git a/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs b/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs
index 0f5fba4d4a..a453b3fcbd 100644
--- a/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs
+++ b/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs
@@ -33,8 +33,8 @@ namespace Umbraco.Cms.Core.Scoping
private CoreDebugSettings _coreDebugSettings;
private static readonly AsyncLocal> s_scopeStack = new AsyncLocal>();
private static readonly AsyncLocal> s_scopeContextStack = new AsyncLocal>();
- private static readonly string s_scopeItemKey = typeof(Scope).FullName;
- private static readonly string s_contextItemKey = typeof(ScopeProvider).FullName;
+ private static readonly string s_scopeItemKey = typeof(Scope).FullName!;
+ private static readonly string s_contextItemKey = typeof(ScopeProvider).FullName!;
private readonly IEventAggregator _eventAggregator;
public ScopeProvider(
@@ -68,33 +68,33 @@ namespace Umbraco.Cms.Core.Scoping
private void MoveHttpContextScopeToCallContext()
{
- var source = (ConcurrentStack)_requestCache.Get(s_scopeItemKey);
- ConcurrentStack stack = s_scopeStack.Value;
+ var source = (ConcurrentStack?)_requestCache.Get(s_scopeItemKey);
+ ConcurrentStack? stack = s_scopeStack.Value;
MoveContexts(s_scopeItemKey, source, stack, (_, v) => s_scopeStack.Value = v);
}
private void MoveHttpContextScopeContextToCallContext()
{
- var source = (ConcurrentStack)_requestCache.Get(s_contextItemKey);
- ConcurrentStack stack = s_scopeContextStack.Value;
+ var source = (ConcurrentStack?)_requestCache.Get(s_contextItemKey);
+ ConcurrentStack? stack = s_scopeContextStack.Value;
MoveContexts(s_contextItemKey, source, stack, (_, v) => s_scopeContextStack.Value = v);
}
private void MoveCallContextScopeToHttpContext()
{
- ConcurrentStack source = s_scopeStack.Value;
- var stack = (ConcurrentStack)_requestCache.Get(s_scopeItemKey);
+ ConcurrentStack? source = s_scopeStack.Value;
+ var stack = (ConcurrentStack?)_requestCache.Get(s_scopeItemKey);
MoveContexts(s_scopeItemKey, source, stack, (k, v) => _requestCache.Set(k, v));
}
private void MoveCallContextScopeContextToHttpContext()
{
- ConcurrentStack source = s_scopeContextStack.Value;
- var stack = (ConcurrentStack)_requestCache.Get(s_contextItemKey);
+ ConcurrentStack? source = s_scopeContextStack.Value;
+ var stack = (ConcurrentStack?)_requestCache.Get(s_contextItemKey);
MoveContexts(s_contextItemKey, source, stack, (k, v) => _requestCache.Set(k, v));
}
- private void MoveContexts(string key, ConcurrentStack source, ConcurrentStack stack, Action> setter)
+ private void MoveContexts(string key, ConcurrentStack? source, ConcurrentStack? stack, Action> setter)
where T : class, IInstanceIdentifiable
{
if (source == null)
@@ -124,9 +124,9 @@ namespace Umbraco.Cms.Core.Scoping
source.Clear();
}
- private void SetCallContextScope(IScope value)
+ private void SetCallContextScope(IScope? value)
{
- ConcurrentStack stack = s_scopeStack.Value;
+ ConcurrentStack? stack = s_scopeStack.Value;
#if DEBUG_SCOPES
// first, null-register the existing value
@@ -164,9 +164,9 @@ namespace Umbraco.Cms.Core.Scoping
}
}
- private void SetCallContextScopeContext(IScopeContext value)
+ private void SetCallContextScopeContext(IScopeContext? value)
{
- ConcurrentStack stack = s_scopeContextStack.Value;
+ ConcurrentStack? stack = s_scopeContextStack.Value;
if (value == null)
{
@@ -187,7 +187,7 @@ namespace Umbraco.Cms.Core.Scoping
}
- private T GetHttpContextObject(string key, bool required = true)
+ private T? GetHttpContextObject(string key, bool required = true)
where T : class
{
if (!_requestCache.IsAvailable && required)
@@ -195,11 +195,11 @@ namespace Umbraco.Cms.Core.Scoping
throw new Exception("Request cache is unavailable.");
}
- var stack = (ConcurrentStack)_requestCache.Get(key);
- return stack != null && stack.TryPeek(out T peek) ? peek : null;
+ var stack = (ConcurrentStack?)_requestCache.Get(key);
+ return stack != null && stack.TryPeek(out T? peek) ? peek : null;
}
- private bool SetHttpContextObject(string key, T value, bool required = true)
+ private bool SetHttpContextObject(string key, T? value, bool required = true)
{
if (!_requestCache.IsAvailable)
{
@@ -230,7 +230,7 @@ namespace Umbraco.Cms.Core.Scoping
}
}
#endif
- var stack = (ConcurrentStack)_requestCache.Get(key);
+ var stack = (ConcurrentStack?)_requestCache.Get(key);
if (value == null)
{
@@ -262,19 +262,19 @@ namespace Umbraco.Cms.Core.Scoping
///
/// The current execution context may be request based (HttpContext) or on a background thread (AsyncLocal)
///
- public IScopeContext AmbientContext
+ public IScopeContext? AmbientContext
{
get
{
// try http context, fallback onto call context
- IScopeContext value = GetHttpContextObject(s_contextItemKey, false);
+ IScopeContext? value = GetHttpContextObject(s_contextItemKey, false);
if (value != null)
{
return value;
}
- ConcurrentStack stack = s_scopeContextStack.Value;
- if (stack == null || !stack.TryPeek(out IScopeContext peek))
+ ConcurrentStack? stack = s_scopeContextStack.Value;
+ if (stack == null || !stack.TryPeek(out IScopeContext? peek))
{
return null;
}
@@ -287,7 +287,7 @@ namespace Umbraco.Cms.Core.Scoping
#region Ambient Scope
- IDatabaseScope IScopeAccessor.AmbientScope => AmbientScope;
+ IDatabaseScope? IScopeAccessor.AmbientScope => AmbientScope;
///
/// Gets or set the Ambient (Current) for the current execution context.
@@ -295,19 +295,19 @@ namespace Umbraco.Cms.Core.Scoping
///
/// The current execution context may be request based (HttpContext) or on a background thread (AsyncLocal)
///
- public Scope AmbientScope
+ public Scope? AmbientScope
{
get
{
// try http context, fallback onto call context
- IScope value = GetHttpContextObject(s_scopeItemKey, false);
+ IScope? value = GetHttpContextObject(s_scopeItemKey, false);
if (value != null)
{
return (Scope)value;
}
- ConcurrentStack stack = s_scopeStack.Value;
- if (stack == null || !stack.TryPeek(out IScope peek))
+ ConcurrentStack? stack = s_scopeStack.Value;
+ if (stack == null || !stack.TryPeek(out IScope? peek))
{
return null;
}
@@ -316,7 +316,7 @@ namespace Umbraco.Cms.Core.Scoping
}
}
- public void PopAmbientScope(Scope scope)
+ public void PopAmbientScope(Scope? scope)
{
// pop the stack from all contexts
SetHttpContextObject(s_scopeItemKey, null, false);
@@ -327,13 +327,13 @@ namespace Umbraco.Cms.Core.Scoping
// if creating a child scope with callContext: true (thus forcing CallContext)
// when there is actually a current HttpContext available.
// It's weird but is required for Deploy somehow.
- bool parentScopeCallContext = (scope.ParentScope?.CallContext ?? false);
- if (scope.CallContext && !parentScopeCallContext)
+ bool parentScopeCallContext = (scope?.ParentScope?.CallContext ?? false);
+ if ((scope?.CallContext ?? false) && !parentScopeCallContext)
{
MoveCallContextScopeToHttpContext();
MoveCallContextScopeContextToHttpContext();
}
- else if (!scope.CallContext && parentScopeCallContext)
+ else if ((!scope?.CallContext ?? false) && parentScopeCallContext)
{
MoveHttpContextScopeToCallContext();
MoveHttpContextScopeContextToCallContext();
@@ -367,7 +367,7 @@ namespace Umbraco.Cms.Core.Scoping
}
}
- public void PushAmbientScopeContext(IScopeContext scopeContext)
+ public void PushAmbientScopeContext(IScopeContext? scopeContext)
{
if (scopeContext is null)
{
@@ -389,7 +389,7 @@ namespace Umbraco.Cms.Core.Scoping
public IScope CreateDetachedScope(
IsolationLevel isolationLevel = IsolationLevel.Unspecified,
RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified,
- IScopedNotificationPublisher scopedNotificationPublisher = null,
+ IScopedNotificationPublisher? scopedNotificationPublisher = null,
bool? scopeFileSystems = null)
=> new Scope(this, _coreDebugSettings, _eventAggregator, _loggerFactory.CreateLogger(), _fileSystems, true, null, isolationLevel, repositoryCacheMode, scopedNotificationPublisher, scopeFileSystems);
@@ -425,7 +425,7 @@ namespace Umbraco.Cms.Core.Scoping
///
public IScope DetachScope()
{
- Scope ambientScope = AmbientScope;
+ Scope? ambientScope = AmbientScope;
if (ambientScope == null)
{
throw new InvalidOperationException("There is no ambient scope.");
@@ -439,12 +439,12 @@ namespace Umbraco.Cms.Core.Scoping
PopAmbientScope(ambientScope);
PopAmbientScopeContext();
- Scope originalScope = AmbientScope;
+ Scope? originalScope = AmbientScope;
if (originalScope != ambientScope.OrigScope)
{
- throw new InvalidOperationException($"The detatched scope ({ambientScope.GetDebugInfo()}) does not match the original ({originalScope.GetDebugInfo()})");
+ throw new InvalidOperationException($"The detatched scope ({ambientScope.GetDebugInfo()}) does not match the original ({originalScope?.GetDebugInfo()})");
}
- IScopeContext originalScopeContext = AmbientContext;
+ IScopeContext? originalScopeContext = AmbientContext;
if (originalScopeContext != ambientScope.OrigContext)
{
throw new InvalidOperationException($"The detatched scope context does not match the original");
@@ -460,16 +460,16 @@ namespace Umbraco.Cms.Core.Scoping
public IScope CreateScope(
IsolationLevel isolationLevel = IsolationLevel.Unspecified,
RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified,
- IScopedNotificationPublisher notificationPublisher = null,
+ IScopedNotificationPublisher? notificationPublisher = null,
bool? scopeFileSystems = null,
bool callContext = false,
bool autoComplete = false)
{
- Scope ambientScope = AmbientScope;
+ Scope? ambientScope = AmbientScope;
if (ambientScope == null)
{
- IScopeContext ambientContext = AmbientContext;
- ScopeContext newContext = ambientContext == null ? new ScopeContext() : null;
+ IScopeContext? ambientContext = AmbientContext;
+ ScopeContext? newContext = ambientContext == null ? new ScopeContext() : null;
var scope = new Scope(this, _coreDebugSettings, _eventAggregator, _loggerFactory.CreateLogger(), _fileSystems, false, newContext, isolationLevel, repositoryCacheMode, notificationPublisher, scopeFileSystems, callContext, autoComplete);
// assign only if scope creation did not throw!
PushAmbientScope(scope);
@@ -486,10 +486,10 @@ namespace Umbraco.Cms.Core.Scoping
}
///
- public IScopeContext Context => AmbientContext;
+ public IScopeContext? Context => AmbientContext;
// for testing
- internal ConcurrentStack GetCallContextScopeValue() => s_scopeStack.Value;
+ internal ConcurrentStack? GetCallContextScopeValue() => s_scopeStack.Value;
#if DEBUG_SCOPES
// this code needs TLC
diff --git a/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Content.cs b/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Content.cs
index c80e61af0e..8e9840d448 100644
--- a/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Content.cs
+++ b/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Content.cs
@@ -47,7 +47,7 @@ namespace Umbraco.Cms.Infrastructure.Search
// Used to track permanent deletions so we can bulk delete from the index
// when needed. For example, when emptying the recycle bin, else it will
// individually update the index which will be much slower.
- HashSet deleteBatch = null;
+ HashSet? deleteBatch = null;
foreach (var payload in (ContentCacheRefresher.JsonPayload[])args.MessageObject)
{
@@ -90,7 +90,7 @@ namespace Umbraco.Cms.Infrastructure.Search
continue;
}
- IContent published = null;
+ IContent? published = null;
if (content.Published && _contentService.IsPathPublished(content))
{
published = content;
diff --git a/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Media.cs b/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Media.cs
index 4ac1d1ca09..aee7ea30b8 100644
--- a/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Media.cs
+++ b/src/Umbraco.Infrastructure/Search/IndexingNotificationHandler.Media.cs
@@ -41,7 +41,7 @@ namespace Umbraco.Cms.Infrastructure.Search
// Used to track permanent deletions so we can bulk delete from the index
// when needed. For example, when emptying the recycle bin, else it will
// individually update the index which will be much slower.
- HashSet deleteBatch = null;
+ HashSet? deleteBatch = null;
foreach (var payload in (MediaCacheRefresher.JsonPayload[])args.MessageObject)
{
@@ -102,7 +102,7 @@ namespace Umbraco.Cms.Infrastructure.Search
}
}
}
- }
+ }
}
if (deleteBatch != null)
diff --git a/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs b/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs
index 98dabd22b8..190819f1ef 100644
--- a/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs
+++ b/src/Umbraco.Infrastructure/Search/UmbracoTreeSearcher.cs
@@ -61,11 +61,11 @@ 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,
- long pageIndex, out long totalFound, string? culture = null, string searchFrom = null, bool ignoreUserStartNodes = false)
+ long pageIndex, out long totalFound, string? culture = null, string? searchFrom = null, bool ignoreUserStartNodes = false)
{
var pagedResult = _backOfficeExamineSearcher.Search(query, entityType, pageSize, pageIndex, out totalFound, searchFrom, ignoreUserStartNodes);
@@ -92,7 +92,7 @@ namespace Umbraco.Cms.Infrastructure.Search
///
///
///
- public IEnumerable EntitySearch(UmbracoObjectTypes objectType, string query, int pageSize, long pageIndex, out long totalFound, string searchFrom = null)
+ public IEnumerable EntitySearch(UmbracoObjectTypes objectType, string query, int pageSize, long pageIndex, out long totalFound, string? searchFrom = null)
{
//if it's a GUID, match it
Guid.TryParse(query, out var g);
@@ -114,6 +114,10 @@ namespace Umbraco.Cms.Infrastructure.Search
{
var m = _mapper.Map(result);
+ if (m is null)
+ {
+ continue;
+ }
//if no icon could be mapped, it will be set to document, so change it to picture
if (m.Icon == Constants.Icons.DefaultIcon)
{
@@ -141,7 +145,7 @@ namespace Umbraco.Cms.Infrastructure.Search
///
///
///
- private IEnumerable MediaFromSearchResults(IEnumerable results)
+ private IEnumerable? MediaFromSearchResults(IEnumerable results)
=> _mapper.Map>(results);
///
@@ -163,7 +167,11 @@ namespace Umbraco.Cms.Infrastructure.Search
}
);
- if (int.TryParse(entity.Id.ToString(),NumberStyles.Integer, CultureInfo.InvariantCulture, out var intId))
+ if (entity is null)
+ {
+ continue;
+ }
+ if (int.TryParse(entity.Id?.ToString(),NumberStyles.Integer, CultureInfo.InvariantCulture, out var intId))
{
//if it varies by culture, return the default language URL
if (result.Values.TryGetValue(UmbracoExamineFieldNames.VariesByCultureFieldName, out var varies) && varies == "y")
diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs b/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs
index c86bda44e0..ca8234164c 100644
--- a/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs
+++ b/src/Umbraco.Infrastructure/Security/BackOfficeClaimsPrincipalFactory.cs
@@ -32,7 +32,7 @@ namespace Umbraco.Cms.Core.Security
// since it's setting an authentication type which is not what we want.
// so we override this method to change it.
- // get the base
+ // get the base
ClaimsIdentity baseIdentity = await base.GenerateClaimsAsync(user);
// now create a new one with the correct authentication type
@@ -46,7 +46,7 @@ namespace Umbraco.Cms.Core.Security
// ensure our required claims are there
id.AddRequiredClaims(
- user.Id,
+ user.Id!,
user.UserName,
user.Name,
user.CalculatedContentStartNodeIds,
diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs b/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs
index df4d704781..9f948716c6 100644
--- a/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs
+++ b/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs
@@ -15,8 +15,8 @@ namespace Umbraco.Cms.Core.Security
public class BackOfficeIdentityUser : UmbracoIdentityUser
{
private string _culture;
- private IReadOnlyCollection _groups;
- private string[] _allowedSections;
+ private IReadOnlyCollection _groups = null!;
+ private string[]? _allowedSections;
private int[] _startMediaIds;
private int[] _startContentIds;
private DateTime? _inviteDateUtc;
@@ -29,7 +29,7 @@ namespace Umbraco.Cms.Core.Security
/// Used to construct a new instance without an identity
///
/// 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)
+ public static BackOfficeIdentityUser CreateNew(GlobalSettings globalSettings, string username, string email, string culture, string? name = null)
{
if (string.IsNullOrWhiteSpace(username))
{
@@ -46,7 +46,7 @@ namespace Umbraco.Cms.Core.Security
user.UserName = username;
user.Email = email;
- user.Id = null;
+ user.Id = string.Empty;
user.HasIdentity = false;
user._culture = culture;
user.Name = name;
@@ -74,8 +74,8 @@ namespace Umbraco.Cms.Core.Security
Id = UserIdToString(userId);
}
- public int[] CalculatedMediaStartNodeIds { get; set; }
- public int[] CalculatedContentStartNodeIds { get; set; }
+ public int[]? CalculatedMediaStartNodeIds { get; set; }
+ public int[]? CalculatedContentStartNodeIds { get; set; }
///
/// Gets or sets invite date
@@ -99,7 +99,7 @@ namespace Umbraco.Cms.Core.Security
value = new int[0];
}
- BeingDirty.SetPropertyValueAndDetectChanges(value, ref _startContentIds, nameof(StartContentIds), s_startIdsComparer);
+ BeingDirty.SetPropertyValueAndDetectChanges(value, ref _startContentIds!, nameof(StartContentIds), s_startIdsComparer);
}
}
@@ -116,7 +116,7 @@ namespace Umbraco.Cms.Core.Security
value = new int[0];
}
- BeingDirty.SetPropertyValueAndDetectChanges(value, ref _startMediaIds, nameof(StartMediaIds), s_startIdsComparer);
+ BeingDirty.SetPropertyValueAndDetectChanges(value, ref _startMediaIds!, nameof(StartMediaIds), s_startIdsComparer);
}
}
@@ -131,7 +131,7 @@ namespace Umbraco.Cms.Core.Security
public string Culture
{
get => _culture;
- set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _culture, nameof(Culture));
+ set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _culture!, nameof(Culture));
}
///
@@ -148,7 +148,7 @@ namespace Umbraco.Cms.Core.Security
foreach (IdentityUserRole identityUserRole in _groups.Select(x => new IdentityUserRole
{
RoleId = x.Alias,
- UserId = Id?.ToString()
+ UserId = Id.ToString()
}))
{
roles.Add(identityUserRole);
@@ -163,7 +163,7 @@ namespace Umbraco.Cms.Core.Security
public Guid Key => UserIdToInt(Id).ToGuid();
- private static int UserIdToInt(string userId)
+ private static int UserIdToInt(string? userId)
{
if(int.TryParse(userId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
{
diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs b/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs
index 4fff80ced6..25f39cca07 100644
--- a/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs
+++ b/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs
@@ -144,7 +144,7 @@ namespace Umbraco.Cms.Core.Security
using (IScope scope = _scopeProvider.CreateScope())
{
- IUser found = _userService.GetUserById(asInt);
+ IUser? found = _userService.GetUserById(asInt);
if (found != null)
{
// we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it.
@@ -194,7 +194,7 @@ namespace Umbraco.Cms.Core.Security
}
var userId = UserIdToInt(user.Id);
- IUser found = _userService.GetUserById(userId);
+ IUser? found = _userService.GetUserById(userId);
if (found != null)
{
_userService.Delete(found);
@@ -211,13 +211,13 @@ namespace Umbraco.Cms.Core.Security
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
- IUser user = _userService.GetUserById(UserIdToInt(userId));
+ IUser? user = _userService.GetUserById(UserIdToInt(userId));
if (user == null)
{
- return Task.FromResult((BackOfficeIdentityUser)null);
+ return Task.FromResult((BackOfficeIdentityUser?)null)!;
}
- return Task.FromResult(AssignLoginsCallback(_mapper.Map(user)));
+ return Task.FromResult(AssignLoginsCallback(_mapper.Map(user)))!;
}
///
@@ -228,12 +228,12 @@ namespace Umbraco.Cms.Core.Security
IUser user = _userService.GetByUsername(userName);
if (user == null)
{
- return Task.FromResult((BackOfficeIdentityUser)null);
+ return Task.FromResult((BackOfficeIdentityUser)null!);
}
- BackOfficeIdentityUser result = AssignLoginsCallback(_mapper.Map(user));
+ BackOfficeIdentityUser? result = AssignLoginsCallback(_mapper.Map(user));
- return Task.FromResult(result);
+ return Task.FromResult(result)!;
}
///
@@ -241,12 +241,12 @@ namespace Umbraco.Cms.Core.Security
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
- IUser user = _userService.GetByEmail(email);
- BackOfficeIdentityUser result = user == null
+ IUser? user = _userService.GetByEmail(email);
+ BackOfficeIdentityUser? result = user == null
? null
: _mapper.Map(user);
- return Task.FromResult(AssignLoginsCallback(result));
+ return Task.FromResult(AssignLoginsCallback(result))!;
}
///
@@ -274,9 +274,12 @@ namespace Umbraco.Cms.Core.Security
}
ICollection logins = user.Logins;
- var instance = new IdentityUserLogin(login.LoginProvider, login.ProviderKey, user.Id.ToString());
- IdentityUserLogin userLogin = instance;
- logins.Add(userLogin);
+ if (user.Id is not null)
+ {
+ var instance = new IdentityUserLogin(login.LoginProvider, login.ProviderKey, user.Id.ToString());
+ IdentityUserLogin userLogin = instance;
+ logins.Add(userLogin);
+ }
return Task.CompletedTask;
}
@@ -291,7 +294,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(user));
}
- IIdentityUserLogin userLogin = user.Logins.SingleOrDefault(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey);
+ IIdentityUserLogin? userLogin = user.Logins.SingleOrDefault(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey);
if (userLogin != null)
{
user.Logins.Remove(userLogin);
@@ -320,16 +323,16 @@ namespace Umbraco.Cms.Core.Security
ThrowIfDisposed();
BackOfficeIdentityUser user = await FindUserAsync(userId, cancellationToken);
- if (user == null)
+ if (user is null || user.Id is null)
{
- return null;
+ return null!;
}
IList logins = await GetLoginsAsync(user, cancellationToken);
- UserLoginInfo found = logins.FirstOrDefault(x => x.ProviderKey == providerKey && x.LoginProvider == loginProvider);
+ UserLoginInfo? found = logins.FirstOrDefault(x => x.ProviderKey == providerKey && x.LoginProvider == loginProvider);
if (found == null)
{
- return null;
+ return null!;
}
return new IdentityUserLogin
@@ -350,7 +353,7 @@ namespace Umbraco.Cms.Core.Security
var logins = _externalLoginService.Find(loginProvider, providerKey).ToList();
if (logins.Count == 0)
{
- return Task.FromResult((IdentityUserLogin)null);
+ return Task.FromResult((IdentityUserLogin)null!);
}
IIdentityUserLogin found = logins[0];
@@ -378,10 +381,10 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(normalizedRoleName));
}
- IUserGroup userGroup = _userService.GetUserGroupByAlias(normalizedRoleName);
+ IUserGroup? userGroup = _userService.GetUserGroupByAlias(normalizedRoleName);
- IEnumerable users = _userService.GetAllInGroup(userGroup.Id);
- IList backOfficeIdentityUsers = users.Select(x => _mapper.Map(x)).ToList();
+ IEnumerable users = _userService.GetAllInGroup(userGroup?.Id);
+ IList backOfficeIdentityUsers = users.Select(x => _mapper.Map(x)).Where(x => x != null).ToList()!;
return Task.FromResult(backOfficeIdentityUsers);
}
@@ -389,10 +392,10 @@ namespace Umbraco.Cms.Core.Security
///
protected override Task> FindRoleAsync(string normalizedRoleName, CancellationToken cancellationToken)
{
- IUserGroup group = _userService.GetUserGroupByAlias(normalizedRoleName);
+ IUserGroup? group = _userService.GetUserGroupByAlias(normalizedRoleName);
if (group == null)
{
- return Task.FromResult((IdentityRole)null);
+ return Task.FromResult((IdentityRole)null!);
}
return Task.FromResult(new IdentityRole(group.Name)
@@ -407,14 +410,14 @@ namespace Umbraco.Cms.Core.Security
BackOfficeIdentityUser user = await FindUserAsync(userId, cancellationToken);
if (user == null)
{
- return null;
+ return null!;
}
- IdentityUserRole found = user.Roles.FirstOrDefault(x => x.RoleId.InvariantEquals(roleId));
- return found;
+ IdentityUserRole? found = user.Roles.FirstOrDefault(x => x.RoleId.InvariantEquals(roleId));
+ return found!;
}
- private BackOfficeIdentityUser AssignLoginsCallback(BackOfficeIdentityUser user)
+ private BackOfficeIdentityUser? AssignLoginsCallback(BackOfficeIdentityUser? user)
{
if (user != null)
{
@@ -433,12 +436,12 @@ namespace Umbraco.Cms.Core.Security
// don't assign anything if nothing has changed as this will trigger the track changes of the model
if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.LastLoginDateUtc))
|| (user.LastLoginDate != default && identityUser.LastLoginDateUtc.HasValue == false)
- || (identityUser.LastLoginDateUtc.HasValue && user.LastLoginDate.ToUniversalTime() != identityUser.LastLoginDateUtc.Value))
+ || (identityUser.LastLoginDateUtc.HasValue && user.LastLoginDate?.ToUniversalTime() != identityUser.LastLoginDateUtc.Value))
{
anythingChanged = true;
// if the LastLoginDate is being set to MinValue, don't convert it ToLocalTime
- DateTime dt = identityUser.LastLoginDateUtc == DateTime.MinValue ? DateTime.MinValue : identityUser.LastLoginDateUtc.Value.ToLocalTime();
+ DateTime? dt = identityUser.LastLoginDateUtc == DateTime.MinValue ? DateTime.MinValue : identityUser.LastLoginDateUtc?.ToLocalTime();
user.LastLoginDate = dt;
}
@@ -451,10 +454,10 @@ namespace Umbraco.Cms.Core.Security
if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.LastPasswordChangeDateUtc))
|| (user.LastPasswordChangeDate != default && identityUser.LastPasswordChangeDateUtc.HasValue == false)
- || (identityUser.LastPasswordChangeDateUtc.HasValue && user.LastPasswordChangeDate.ToUniversalTime() != identityUser.LastPasswordChangeDateUtc.Value))
+ || (identityUser.LastPasswordChangeDateUtc.HasValue && user.LastPasswordChangeDate?.ToUniversalTime() != identityUser.LastPasswordChangeDateUtc.Value))
{
anythingChanged = true;
- user.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc.Value.ToLocalTime();
+ user.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc?.ToLocalTime();
}
if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.EmailConfirmed))
@@ -548,7 +551,7 @@ namespace Umbraco.Cms.Core.Security
if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.Roles)))
{
- var identityUserRoles = identityUser.Roles.Select(x => x.RoleId).ToArray();
+ var identityUserRoles = identityUser.Roles.Select(x => x.RoleId).Where(x => x is not null).ToArray();
anythingChanged = true;
@@ -556,7 +559,7 @@ namespace Umbraco.Cms.Core.Security
user.ClearGroups();
// go lookup all these groups
- IReadOnlyUserGroup[] groups = _userService.GetUserGroupsByAlias(identityUserRoles).Select(x => x.ToReadOnlyGroup()).ToArray();
+ IReadOnlyUserGroup[] groups = _userService.GetUserGroupsByAlias(identityUserRoles!).Select(x => x.ToReadOnlyGroup()).ToArray();
// use all of the ones assigned and add them
foreach (IReadOnlyUserGroup group in groups)
@@ -608,7 +611,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(user));
}
- IIdentityUserToken token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
+ IIdentityUserToken? token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
if (token == null)
{
user.LoginTokens.Add(new IdentityUserToken(loginProvider, name, value, user.Id));
@@ -639,7 +642,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(user));
}
- IIdentityUserToken token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
+ IIdentityUserToken? token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
if (token != null)
{
user.LoginTokens.Remove(token);
@@ -656,7 +659,7 @@ namespace Umbraco.Cms.Core.Security
/// tracking ORMs like EFCore.
///
///
- public override Task GetTokenAsync(BackOfficeIdentityUser user, string loginProvider, string name, CancellationToken cancellationToken)
+ public override Task GetTokenAsync(BackOfficeIdentityUser user, string loginProvider, string name, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -665,7 +668,7 @@ namespace Umbraco.Cms.Core.Security
{
throw new ArgumentNullException(nameof(user));
}
- IIdentityUserToken token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
+ IIdentityUserToken? token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
return Task.FromResult(token?.Value);
}
diff --git a/src/Umbraco.Infrastructure/Security/IMemberManager.cs b/src/Umbraco.Infrastructure/Security/IMemberManager.cs
index f851b205d5..d7558e163f 100644
--- a/src/Umbraco.Infrastructure/Security/IMemberManager.cs
+++ b/src/Umbraco.Infrastructure/Security/IMemberManager.cs
@@ -30,9 +30,9 @@ namespace Umbraco.Cms.Core.Security
/// Allowed individual members.
/// True or false if the currently logged in member is authorized
Task IsMemberAuthorizedAsync(
- IEnumerable allowTypes = null,
- IEnumerable allowGroups = null,
- IEnumerable allowMembers = null);
+ IEnumerable? allowTypes = null,
+ IEnumerable? allowGroups = null,
+ IEnumerable? allowMembers = null);
///
/// Check if a member is logged in
diff --git a/src/Umbraco.Infrastructure/Security/IMemberUserStore.cs b/src/Umbraco.Infrastructure/Security/IMemberUserStore.cs
index 578b2f2860..7ecddac3ba 100644
--- a/src/Umbraco.Infrastructure/Security/IMemberUserStore.cs
+++ b/src/Umbraco.Infrastructure/Security/IMemberUserStore.cs
@@ -8,6 +8,6 @@ namespace Umbraco.Cms.Core.Security
///
public interface IMemberUserStore : IUserStore
{
- IPublishedContent GetPublishedMember(MemberIdentityUser user);
+ IPublishedContent? GetPublishedMember(MemberIdentityUser user);
}
}
diff --git a/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs b/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs
index 3b51233f61..d3c616af0a 100644
--- a/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs
+++ b/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs
@@ -72,16 +72,16 @@ namespace Umbraco.Cms.Core.Security
target.CalculatedContentStartNodeIds = source.CalculateContentStartNodeIds(_entityService, _appCaches);
target.Email = source.Email;
target.UserName = source.Username;
- target.LastPasswordChangeDateUtc = source.LastPasswordChangeDate.ToUniversalTime();
- target.LastLoginDateUtc = source.LastLoginDate.ToUniversalTime();
+ target.LastPasswordChangeDateUtc = source.LastPasswordChangeDate?.ToUniversalTime();
+ target.LastLoginDateUtc = source.LastLoginDate?.ToUniversalTime();
target.InviteDateUtc = source.InvitedDate?.ToUniversalTime();
target.EmailConfirmed = source.EmailConfirmedDate.HasValue;
target.Name = source.Name;
target.AccessFailedCount = source.FailedPasswordAttempts;
target.PasswordHash = GetPasswordHash(source.RawPasswordValue);
target.PasswordConfig = source.PasswordConfiguration;
- target.StartContentIds = source.StartContentIds;
- target.StartMediaIds = source.StartMediaIds;
+ target.StartContentIds = source.StartContentIds ?? Array.Empty();
+ target.StartMediaIds = source.StartMediaIds ?? Array.Empty();
target.Culture = source.GetUserCulture(_textService, _globalSettings).ToString(); // project CultureInfo to string
target.IsApproved = source.IsApproved;
target.SecurityStamp = source.SecurityStamp;
@@ -93,8 +93,8 @@ namespace Umbraco.Cms.Core.Security
{
target.Email = source.Email;
target.UserName = source.Username;
- target.LastPasswordChangeDateUtc = source.LastPasswordChangeDate.ToUniversalTime();
- target.LastLoginDateUtc = source.LastLoginDate.ToUniversalTime();
+ target.LastPasswordChangeDateUtc = source.LastPasswordChangeDate?.ToUniversalTime();
+ target.LastLoginDateUtc = source.LastLoginDate?.ToUniversalTime();
target.EmailConfirmed = source.EmailConfirmedDate.HasValue;
target.Name = source.Name;
target.AccessFailedCount = source.FailedPasswordAttempts;
@@ -112,6 +112,6 @@ namespace Umbraco.Cms.Core.Security
// NB: same comments re AutoMapper as per BackOfficeUser
}
- private static string GetPasswordHash(string storedPass) => storedPass.StartsWith(Constants.Security.EmptyPasswordPrefix) ? null : storedPass;
+ private static string? GetPasswordHash(string? storedPass) => storedPass?.StartsWith(Constants.Security.EmptyPasswordPrefix) ?? false ? null : storedPass;
}
}
diff --git a/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs b/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs
index 9e29316056..a2c29ed99f 100644
--- a/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs
+++ b/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs
@@ -12,11 +12,11 @@ namespace Umbraco.Cms.Core.Security
///
public class MemberIdentityUser : UmbracoIdentityUser
{
- private string _comments;
+ private string? _comments;
// Custom comparer for enumerables
private static readonly DelegateEqualityComparer> s_groupsComparer = new DelegateEqualityComparer>(
- (groups, enumerable) => groups.Select(x => x.Alias).UnsortedSequenceEqual(enumerable.Select(x => x.Alias)),
+ (groups, enumerable) => groups?.Select(x => x.Alias).UnsortedSequenceEqual(enumerable?.Select(x => x.Alias)) ?? false,
groups => groups.GetHashCode());
///
@@ -35,7 +35,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Used to construct a new instance without an identity
///
- public static MemberIdentityUser CreateNew(string username, string email, string memberTypeAlias, bool isApproved, string name = null)
+ public static MemberIdentityUser CreateNew(string username, string email, string memberTypeAlias, bool isApproved, string? name = null)
{
if (string.IsNullOrWhiteSpace(username))
{
@@ -48,7 +48,7 @@ namespace Umbraco.Cms.Core.Security
user.Email = email;
user.MemberTypeAlias = memberTypeAlias;
user.IsApproved = isApproved;
- user.Id = null;
+ user.Id = null!;
user.HasIdentity = false;
user.Name = name;
user.EnableChangeTracking();
@@ -58,7 +58,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Gets or sets the member's comments
///
- public string Comments
+ public string? Comments
{
get => _comments;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _comments, nameof(Comments));
@@ -76,7 +76,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Gets or sets the alias of the member type
///
- public string MemberTypeAlias { get; set; }
+ public string? MemberTypeAlias { get; set; }
private static string UserIdToString(int userId) => string.Intern(userId.ToString(CultureInfo.InvariantCulture));
diff --git a/src/Umbraco.Infrastructure/Security/MemberPasswordHasher.cs b/src/Umbraco.Infrastructure/Security/MemberPasswordHasher.cs
index e470bf0a6c..71a48e19c5 100644
--- a/src/Umbraco.Infrastructure/Security/MemberPasswordHasher.cs
+++ b/src/Umbraco.Infrastructure/Security/MemberPasswordHasher.cs
@@ -80,7 +80,7 @@ namespace Umbraco.Cms.Core.Security
// Else we need to detect what the password is. This will be the case
// for upgrades since no password config will exist.
- byte[] decodedHashedPassword = null;
+ byte[]? decodedHashedPassword = null;
bool isAspNetIdentityHash = false;
try
@@ -96,7 +96,7 @@ namespace Umbraco.Cms.Core.Security
// check for default ASP.NET Identity password hash flags
if (isAspNetIdentityHash)
{
- if (decodedHashedPassword[0] == 0x00 || decodedHashedPassword[0] == 0x01)
+ if (decodedHashedPassword?[0] == 0x00 || decodedHashedPassword?[0] == 0x01)
{
return base.VerifyHashedPassword(user, hashedPassword, providedPassword);
}
diff --git a/src/Umbraco.Infrastructure/Security/MemberRoleStore.cs b/src/Umbraco.Infrastructure/Security/MemberRoleStore.cs
index 03339fbd33..70743f3660 100644
--- a/src/Umbraco.Infrastructure/Security/MemberRoleStore.cs
+++ b/src/Umbraco.Infrastructure/Security/MemberRoleStore.cs
@@ -77,7 +77,7 @@ namespace Umbraco.Cms.Core.Security
return Task.FromResult(IdentityResult.Failed(_intParseError));
}
- IMemberGroup memberGroup = _memberGroupService.GetById(roleId);
+ IMemberGroup? memberGroup = _memberGroupService.GetById(roleId);
if (memberGroup != null)
{
if (MapToMemberGroup(role, memberGroup))
@@ -109,7 +109,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentException("The Id of the role is not an integer");
}
- IMemberGroup memberGroup = _memberGroupService.GetById(roleId);
+ IMemberGroup? memberGroup = _memberGroupService.GetById(roleId);
if (memberGroup != null)
{
_memberGroupService.Delete(memberGroup);
@@ -133,7 +133,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(role));
}
- return Task.FromResult(role.Id);
+ return Task.FromResult(role.Id)!;
}
///
@@ -147,7 +147,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(role));
}
- return Task.FromResult(role.Name);
+ return Task.FromResult(role.Name)!;
}
///
@@ -182,7 +182,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(roleId));
}
- IMemberGroup memberGroup;
+ IMemberGroup? memberGroup;
// member group can be found by int or Guid, so try both
if (!int.TryParse(roleId, NumberStyles.Integer, CultureInfo.InvariantCulture, out int id))
@@ -201,7 +201,7 @@ namespace Umbraco.Cms.Core.Security
memberGroup = _memberGroupService.GetById(id);
}
- return Task.FromResult(memberGroup == null ? null : MapFromMemberGroup(memberGroup));
+ return Task.FromResult(memberGroup == null ? null : MapFromMemberGroup(memberGroup))!;
}
///
@@ -215,7 +215,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(name));
}
IMemberGroup memberGroup = _memberGroupService.GetByName(name);
- return Task.FromResult(memberGroup == null ? null : MapFromMemberGroup(memberGroup));
+ return Task.FromResult(memberGroup == null ? null : MapFromMemberGroup(memberGroup))!;
}
///
diff --git a/src/Umbraco.Infrastructure/Security/MemberUserStore.cs b/src/Umbraco.Infrastructure/Security/MemberUserStore.cs
index 420d66b0b4..24fab739e5 100644
--- a/src/Umbraco.Infrastructure/Security/MemberUserStore.cs
+++ b/src/Umbraco.Infrastructure/Security/MemberUserStore.cs
@@ -104,8 +104,8 @@ namespace Umbraco.Cms.Core.Security
IMember memberEntity = _memberService.CreateMember(
user.UserName,
user.Email,
- user.Name.IsNullOrWhiteSpace() ? user.UserName : user.Name,
- user.MemberTypeAlias.IsNullOrWhiteSpace() ? Constants.Security.DefaultMemberTypeAlias : user.MemberTypeAlias);
+ user.Name.IsNullOrWhiteSpace() ? user.UserName : user.Name!,
+ user.MemberTypeAlias.IsNullOrWhiteSpace() ? Constants.Security.DefaultMemberTypeAlias : user.MemberTypeAlias!);
UpdateMemberProperties(memberEntity, user);
@@ -113,7 +113,7 @@ namespace Umbraco.Cms.Core.Security
_memberService.Save(memberEntity);
//We need to add roles now that the member has an Id. It do not work implicit in UpdateMemberProperties
- _memberService.AssignRoles(new[] { memberEntity.Id }, user.Roles.Select(x => x.RoleId).ToArray());
+ _memberService.AssignRoles(new[] { memberEntity.Id }, user.Roles.Select(x => x.RoleId).Where(x => x is not null).ToArray()!);
if (!memberEntity.HasIdentity)
{
@@ -176,7 +176,7 @@ namespace Umbraco.Cms.Core.Security
}
using IScope scope = _scopeProvider.CreateScope(autoComplete: true);
- IMember found = _memberService.GetById(asInt);
+ IMember? found = _memberService.GetById(asInt);
if (found != null)
{
// we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it.
@@ -225,7 +225,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(user));
}
- IMember found = _memberService.GetById(UserIdToInt(user.Id));
+ IMember? found = _memberService.GetById(UserIdToInt(user.Id));
if (found != null)
{
_memberService.Delete(found);
@@ -253,13 +253,13 @@ namespace Umbraco.Cms.Core.Security
}
- IMember user = Guid.TryParse(userId, out var key) ? _memberService.GetByKey(key) : _memberService.GetById(UserIdToInt(userId));
+ IMember? user = Guid.TryParse(userId, out var key) ? _memberService.GetByKey(key) : _memberService.GetById(UserIdToInt(userId));
if (user == null)
{
- return Task.FromResult((MemberIdentityUser)null);
+ return Task.FromResult((MemberIdentityUser)null!);
}
- return Task.FromResult(AssignLoginsCallback(_mapper.Map(user)));
+ return Task.FromResult(AssignLoginsCallback(_mapper.Map(user)))!;
}
///
@@ -270,10 +270,10 @@ namespace Umbraco.Cms.Core.Security
IMember user = _memberService.GetByUsername(userName);
if (user == null)
{
- return Task.FromResult((MemberIdentityUser)null);
+ return Task.FromResult((MemberIdentityUser)null!);
}
- MemberIdentityUser result = AssignLoginsCallback(_mapper.Map(user));
+ MemberIdentityUser result = AssignLoginsCallback(_mapper.Map(user))!;
return Task.FromResult(result);
}
@@ -283,12 +283,12 @@ namespace Umbraco.Cms.Core.Security
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
- IMember member = _memberService.GetByEmail(email);
- MemberIdentityUser result = member == null
+ IMember? member = _memberService.GetByEmail(email);
+ MemberIdentityUser? result = member == null
? null
: _mapper.Map(member);
- return Task.FromResult(AssignLoginsCallback(result));
+ return Task.FromResult(AssignLoginsCallback(result))!;
}
///
@@ -317,13 +317,16 @@ namespace Umbraco.Cms.Core.Security
}
ICollection logins = user.Logins;
- var instance = new IdentityUserLogin(
- login.LoginProvider,
- login.ProviderKey,
- user.Id.ToString());
+ if (user.Id is not null)
+ {
+ var instance = new IdentityUserLogin(
+ login.LoginProvider,
+ login.ProviderKey,
+ user.Id.ToString());
- IdentityUserLogin userLogin = instance;
- logins.Add(userLogin);
+ IdentityUserLogin userLogin = instance;
+ logins.Add(userLogin);
+ }
return Task.CompletedTask;
}
@@ -348,7 +351,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(providerKey));
}
- IIdentityUserLogin userLogin = user.Logins.SingleOrDefault(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey);
+ IIdentityUserLogin? userLogin = user.Logins.SingleOrDefault(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey);
if (userLogin != null)
{
user.Logins.Remove(userLogin);
@@ -389,24 +392,31 @@ namespace Umbraco.Cms.Core.Security
MemberIdentityUser user = await FindUserAsync(userId, cancellationToken);
if (user == null)
{
- return await Task.FromResult((IdentityUserLogin)null);
+ return await Task.FromResult((IdentityUserLogin)null!);
}
IList logins = await GetLoginsAsync(user, cancellationToken);
- UserLoginInfo found = logins.FirstOrDefault(x => x.ProviderKey == providerKey && x.LoginProvider == loginProvider);
+ UserLoginInfo? found = logins.FirstOrDefault(x => x.ProviderKey == providerKey && x.LoginProvider == loginProvider);
if (found == null)
{
- return await Task.FromResult((IdentityUserLogin)null);
+ return await Task.FromResult((IdentityUserLogin)null!);
}
- return new IdentityUserLogin
+ if (user.Id is not null)
{
- LoginProvider = found.LoginProvider,
- ProviderKey = found.ProviderKey,
- // TODO: We don't store this value so it will be null
- ProviderDisplayName = found.ProviderDisplayName,
- UserId = user.Id
- };
+ return new IdentityUserLogin
+ {
+ LoginProvider = found.LoginProvider,
+ ProviderKey = found.ProviderKey,
+ // TODO: We don't store this value so it will be null
+ ProviderDisplayName = found.ProviderDisplayName,
+ UserId = user.Id
+ };
+ }
+ else
+ {
+ return null!;
+ }
}
///
@@ -428,7 +438,7 @@ namespace Umbraco.Cms.Core.Security
var logins = _externalLoginService.Find(loginProvider, providerKey).ToList();
if (logins.Count == 0)
{
- return Task.FromResult((IdentityUserLogin)null);
+ return Task.FromResult((IdentityUserLogin)null!);
}
IIdentityUserLogin found = logins[0];
@@ -496,7 +506,7 @@ namespace Umbraco.Cms.Core.Security
IEnumerable members = _memberService.GetMembersByMemberType(roleName);
- IList membersIdentityUsers = members.Select(x => _mapper.Map(x)).ToList();
+ IList membersIdentityUsers = members.Select(x => _mapper.Map(x)!).ToList();
return Task.FromResult(membersIdentityUsers);
}
@@ -509,10 +519,10 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentNullException(nameof(roleName));
}
- IMemberGroup group = _memberService.GetAllRoles().SingleOrDefault(x => x.Name == roleName);
+ IMemberGroup? group = _memberService.GetAllRoles().SingleOrDefault(x => x.Name == roleName);
if (group == null)
{
- return Task.FromResult((UmbracoIdentityRole)null);
+ return Task.FromResult((UmbracoIdentityRole)null!);
}
return Task.FromResult(new UmbracoIdentityRole(group.Name)
@@ -528,14 +538,14 @@ namespace Umbraco.Cms.Core.Security
MemberIdentityUser user = await FindUserAsync(userId, cancellationToken);
if (user == null)
{
- return null;
+ return null!;
}
- IdentityUserRole found = user.Roles.FirstOrDefault(x => x.RoleId.InvariantEquals(roleId));
- return found;
+ IdentityUserRole? found = user.Roles.FirstOrDefault(x => x.RoleId.InvariantEquals(roleId));
+ return found!;
}
- private MemberIdentityUser AssignLoginsCallback(MemberIdentityUser user)
+ private MemberIdentityUser? AssignLoginsCallback(MemberIdentityUser? user)
{
if (user != null)
{
@@ -553,21 +563,21 @@ namespace Umbraco.Cms.Core.Security
// don't assign anything if nothing has changed as this will trigger the track changes of the model
if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastLoginDateUtc))
|| (member.LastLoginDate != default && identityUser.LastLoginDateUtc.HasValue == false)
- || (identityUser.LastLoginDateUtc.HasValue && member.LastLoginDate.ToUniversalTime() != identityUser.LastLoginDateUtc.Value))
+ || (identityUser.LastLoginDateUtc.HasValue && member.LastLoginDate?.ToUniversalTime() != identityUser.LastLoginDateUtc.Value))
{
changeType = MemberDataChangeType.LoginOnly;
// if the LastLoginDate is being set to MinValue, don't convert it ToLocalTime
- DateTime dt = identityUser.LastLoginDateUtc == DateTime.MinValue ? DateTime.MinValue : identityUser.LastLoginDateUtc.Value.ToLocalTime();
+ DateTime? dt = identityUser.LastLoginDateUtc == DateTime.MinValue ? DateTime.MinValue : identityUser.LastLoginDateUtc?.ToLocalTime();
member.LastLoginDate = dt;
}
if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastPasswordChangeDateUtc))
|| (member.LastPasswordChangeDate != default && identityUser.LastPasswordChangeDateUtc.HasValue == false)
- || (identityUser.LastPasswordChangeDateUtc.HasValue && member.LastPasswordChangeDate.ToUniversalTime() != identityUser.LastPasswordChangeDateUtc.Value))
+ || (identityUser.LastPasswordChangeDateUtc.HasValue && member.LastPasswordChangeDate?.ToUniversalTime() != identityUser.LastPasswordChangeDateUtc.Value))
{
changeType = MemberDataChangeType.FullSave;
- member.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc.Value.ToLocalTime();
+ member.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc?.ToLocalTime();
}
if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Comments))
@@ -589,7 +599,7 @@ namespace Umbraco.Cms.Core.Security
&& member.Name != identityUser.Name && identityUser.Name.IsNullOrWhiteSpace() == false)
{
changeType = MemberDataChangeType.FullSave;
- member.Name = identityUser.Name;
+ member.Name = identityUser.Name ?? string.Empty;
}
if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Email))
@@ -665,13 +675,13 @@ namespace Umbraco.Cms.Core.Security
return changeType;
}
- public IPublishedContent GetPublishedMember(MemberIdentityUser user)
+ public IPublishedContent? GetPublishedMember(MemberIdentityUser user)
{
if (user == null)
{
return null;
}
- IMember member = _memberService.GetByKey(user.Key);
+ IMember? member = _memberService.GetByKey(user.Key);
if (member == null)
{
return null;
@@ -695,7 +705,7 @@ namespace Umbraco.Cms.Core.Security
/// tracking ORMs like EFCore.
///
///
- public override Task GetTokenAsync(MemberIdentityUser user, string loginProvider, string name, CancellationToken cancellationToken)
+ public override Task GetTokenAsync(MemberIdentityUser user, string loginProvider, string name, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -704,7 +714,7 @@ namespace Umbraco.Cms.Core.Security
{
throw new ArgumentNullException(nameof(user));
}
- IIdentityUserToken token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
+ IIdentityUserToken? token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name));
return Task.FromResult(token?.Value);
}
diff --git a/src/Umbraco.Infrastructure/Security/UmbracoIdentityRole.cs b/src/Umbraco.Infrastructure/Security/UmbracoIdentityRole.cs
index 0b0285d852..ebf3bf5943 100644
--- a/src/Umbraco.Infrastructure/Security/UmbracoIdentityRole.cs
+++ b/src/Umbraco.Infrastructure/Security/UmbracoIdentityRole.cs
@@ -7,10 +7,10 @@ namespace Umbraco.Cms.Core.Security
{
public class UmbracoIdentityRole : IdentityRole, IRememberBeingDirty
{
- private string _id;
- private string _name;
+ private string? _id;
+ private string? _name;
- public UmbracoIdentityRole(string roleName) : base(roleName)
+ public UmbracoIdentityRole(string? roleName) : base(roleName)
{
}
@@ -32,7 +32,7 @@ namespace Umbraco.Cms.Core.Security
}
///
- public override string Id
+ public override string? Id
{
get => _id;
set
@@ -43,7 +43,7 @@ namespace Umbraco.Cms.Core.Security
}
///
- public override string Name
+ public override string? Name
{
get => _name;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _name, nameof(Name));
diff --git a/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs b/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs
index 05e70076c6..36a652889f 100644
--- a/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs
+++ b/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs
@@ -29,20 +29,20 @@ namespace Umbraco.Cms.Core.Security
///
public abstract class UmbracoIdentityUser : IdentityUser, IRememberBeingDirty
{
- private string _name;
- private string _passwordConfig;
- private string _id;
- private string _email;
- private string _userName;
+ private string? _name;
+ private string? _passwordConfig;
+ private string _id = null!;
+ private string _email = null!;
+ private string _userName = null!;
private DateTime? _lastLoginDateUtc;
private bool _emailConfirmed;
private int _accessFailedCount;
- private string _passwordHash;
+ private string? _passwordHash;
private DateTime? _lastPasswordChangeDateUtc;
- private ObservableCollection _logins;
- private ObservableCollection _tokens;
- private Lazy> _getLogins;
- private Lazy> _getTokens;
+ private ObservableCollection? _logins;
+ private ObservableCollection? _tokens;
+ private Lazy>? _getLogins;
+ private Lazy>? _getTokens;
private ObservableCollection> _roles;
///
@@ -92,7 +92,7 @@ namespace Umbraco.Cms.Core.Security
public override string Email
{
get => _email;
- set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _email, nameof(Email));
+ set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _email!, nameof(Email));
}
///
@@ -107,7 +107,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Gets or sets the salted/hashed form of the user password
///
- public override string PasswordHash
+ public override string? PasswordHash
{
get => _passwordHash;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _passwordHash, nameof(PasswordHash));
@@ -212,9 +212,12 @@ namespace Umbraco.Cms.Core.Security
// if (_getTokens != null && !_getTokens.IsValueCreated)
if (_getTokens?.IsValueCreated != true)
{
- foreach (IIdentityUserToken l in _getTokens.Value)
+ if (_getTokens is not null)
{
- _tokens.Add(l);
+ foreach (IIdentityUserToken l in _getTokens.Value)
+ {
+ _tokens.Add(l);
+ }
}
}
@@ -249,7 +252,7 @@ namespace Umbraco.Cms.Core.Security
public override string UserName
{
get => _userName;
- set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _userName, nameof(UserName));
+ set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _userName!, nameof(UserName));
}
///
@@ -277,7 +280,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Gets or sets the user's real name
///
- public string Name
+ public string? Name
{
get => _name;
set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _name, nameof(Name));
@@ -286,7 +289,7 @@ namespace Umbraco.Cms.Core.Security
///
/// Gets or sets the password config
///
- public string PasswordConfig
+ public string? PasswordConfig
{
// TODO: Implement this for members: AB#11550
get => _passwordConfig;
@@ -337,11 +340,14 @@ namespace Umbraco.Cms.Core.Security
///
/// Adding a role this way will not reflect on the user's group's collection or it's allowed sections until the user is persisted
///
- public void AddRole(string role) => Roles.Add(new IdentityUserRole
+ public void AddRole(string role)
{
- UserId = Id,
- RoleId = role
- });
+ Roles.Add(new IdentityUserRole
+ {
+ UserId = Id,
+ RoleId = role
+ });
+ }
///
/// Used to set a lazy call back to populate the user's Login list
@@ -355,10 +361,10 @@ namespace Umbraco.Cms.Core.Security
/// The lazy value
internal void SetTokensCallback(Lazy> callback) => _getTokens = callback ?? throw new ArgumentNullException(nameof(callback));
- private void Logins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(Logins));
+ private void Logins_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(Logins));
- private void LoginTokens_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(LoginTokens));
+ private void LoginTokens_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(LoginTokens));
- private void Roles_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(Roles));
+ private void Roles_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => BeingDirty.OnPropertyChanged(nameof(Roles));
}
}
diff --git a/src/Umbraco.Infrastructure/Security/UmbracoPasswordHasher.cs b/src/Umbraco.Infrastructure/Security/UmbracoPasswordHasher.cs
index da08bc8713..b1e13497f7 100644
--- a/src/Umbraco.Infrastructure/Security/UmbracoPasswordHasher.cs
+++ b/src/Umbraco.Infrastructure/Security/UmbracoPasswordHasher.cs
@@ -49,8 +49,8 @@ namespace Umbraco.Cms.Core.Security
if (!user.PasswordConfig.IsNullOrWhiteSpace())
{
// check if the (legacy) password security supports this hash algorith and if so then use it
- var deserialized = _jsonSerializer.Deserialize(user.PasswordConfig);
- if (LegacyPasswordSecurity.SupportHashAlgorithm(deserialized.HashAlgorithm))
+ var deserialized = _jsonSerializer.Deserialize(user.PasswordConfig!);
+ if (deserialized?.HashAlgorithm is not null && LegacyPasswordSecurity.SupportHashAlgorithm(deserialized.HashAlgorithm))
{
var result = LegacyPasswordSecurity.VerifyPassword(deserialized.HashAlgorithm, providedPassword, hashedPassword);
@@ -72,7 +72,7 @@ namespace Umbraco.Cms.Core.Security
// The PBKDF2.ASPNETCORE.V2 settings are:
// PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
- switch (deserialized.HashAlgorithm)
+ switch (deserialized?.HashAlgorithm)
{
case Constants.Security.AspNetCoreV3PasswordHashAlgorithmName:
return base.VerifyHashedPassword(user, hashedPassword, providedPassword);
diff --git a/src/Umbraco.Infrastructure/Security/UmbracoUserManager.cs b/src/Umbraco.Infrastructure/Security/UmbracoUserManager.cs
index 111a05d816..0504ddb85b 100644
--- a/src/Umbraco.Infrastructure/Security/UmbracoUserManager.cs
+++ b/src/Umbraco.Infrastructure/Security/UmbracoUserManager.cs
@@ -20,7 +20,7 @@ namespace Umbraco.Cms.Core.Security
where TUser : UmbracoIdentityUser
where TPasswordConfig : class, IPasswordConfiguration, new()
{
- private PasswordGenerator _passwordGenerator;
+ private PasswordGenerator? _passwordGenerator;
///
/// Initializes a new instance of the class.
diff --git a/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs b/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs
index aaaaed55e7..ef10380785 100644
--- a/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs
+++ b/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs
@@ -27,7 +27,7 @@ namespace Umbraco.Cms.Core.Security
[EditorBrowsable(EditorBrowsableState.Never)]
public override IQueryable Users => throw new NotImplementedException();
- protected static int UserIdToInt(string userId)
+ protected static int UserIdToInt(string? userId)
{
if(int.TryParse(userId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
{
@@ -74,7 +74,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(normalizedRoleName));
}
- IdentityUserRole userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName);
+ IdentityUserRole? userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName);
if (userRole == null)
{
@@ -118,7 +118,7 @@ namespace Umbraco.Cms.Core.Security
}
///
- public override Task GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default)
+ public override Task GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -129,7 +129,7 @@ namespace Umbraco.Cms.Core.Security
// the stamp cannot be null, so if it is currently null then we'll just return a hash of the password
return Task.FromResult(user.SecurityStamp.IsNullOrWhiteSpace()
- ? user.PasswordHash.GenerateHash()
+ ? user.PasswordHash?.GenerateHash()
: user.SecurityStamp);
}
@@ -198,7 +198,7 @@ namespace Umbraco.Cms.Core.Security
throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(normalizedRoleName));
}
- IdentityUserRole userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName);
+ IdentityUserRole? userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName);
if (userRole != null)
{
diff --git a/src/Umbraco.Infrastructure/Serialization/AutoInterningStringConverter.cs b/src/Umbraco.Infrastructure/Serialization/AutoInterningStringConverter.cs
index b8a6baaec8..222535d196 100644
--- a/src/Umbraco.Infrastructure/Serialization/AutoInterningStringConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/AutoInterningStringConverter.cs
@@ -20,18 +20,18 @@ namespace Umbraco.Cms.Infrastructure.Serialization
throw new NotImplementedException($"{nameof(AutoInterningStringConverter)} should not be used globally");
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Check is in case the value is a non-string literal such as an integer.
var s = reader.TokenType == JsonToken.String
- ? string.Intern((string)reader.Value)
- : string.Intern((string)JToken.Load(reader));
+ ? string.Intern((string)reader.Value!)
+ : string.Intern((string)JToken.Load(reader)!);
return s;
}
public override bool CanWrite => false;
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) => throw new NotImplementedException();
}
}
diff --git a/src/Umbraco.Infrastructure/Serialization/AutoInterningStringKeyCaseInsensitiveDictionaryConverter.cs b/src/Umbraco.Infrastructure/Serialization/AutoInterningStringKeyCaseInsensitiveDictionaryConverter.cs
index cff3aa69a2..262c732e1d 100644
--- a/src/Umbraco.Infrastructure/Serialization/AutoInterningStringKeyCaseInsensitiveDictionaryConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/AutoInterningStringKeyCaseInsensitiveDictionaryConverter.cs
@@ -20,7 +20,7 @@ namespace Umbraco.Cms.Infrastructure.Serialization
{
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject)
{
@@ -30,7 +30,7 @@ namespace Umbraco.Cms.Infrastructure.Serialization
switch (reader.TokenType)
{
case JsonToken.PropertyName:
- var key = string.Intern(reader.Value.ToString());
+ var key = string.Intern(reader.Value!.ToString()!);
if (!reader.Read())
throw new Exception("Unexpected end when reading object.");
diff --git a/src/Umbraco.Infrastructure/Serialization/ForceInt32Converter.cs b/src/Umbraco.Infrastructure/Serialization/ForceInt32Converter.cs
index e6d8499910..71c879f746 100644
--- a/src/Umbraco.Infrastructure/Serialization/ForceInt32Converter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/ForceInt32Converter.cs
@@ -11,16 +11,16 @@ namespace Umbraco.Cms.Infrastructure.Serialization
return objectType == typeof (object) || objectType == typeof (int);
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var jsonValue = serializer.Deserialize(reader);
- return jsonValue.Type == JTokenType.Integer
+ return jsonValue?.Type == JTokenType.Integer
? jsonValue.Value()
: serializer.Deserialize(reader);
}
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
diff --git a/src/Umbraco.Infrastructure/Serialization/FuzzyBooleanConverter.cs b/src/Umbraco.Infrastructure/Serialization/FuzzyBooleanConverter.cs
index b98e8c93a0..118abe3470 100644
--- a/src/Umbraco.Infrastructure/Serialization/FuzzyBooleanConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/FuzzyBooleanConverter.cs
@@ -7,19 +7,19 @@ namespace Umbraco.Cms.Infrastructure.Serialization
{
public override bool CanWrite => false;
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
public override bool CanRead => true;
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var value = reader.Value;
if (value is bool) return value;
- switch (value.ToString().ToLower().Trim())
+ switch (value?.ToString()?.ToLower().Trim())
{
case "true":
case "yes":
diff --git a/src/Umbraco.Infrastructure/Serialization/JsonNetSerializer.cs b/src/Umbraco.Infrastructure/Serialization/JsonNetSerializer.cs
index dd228ac008..a9ad6a900d 100644
--- a/src/Umbraco.Infrastructure/Serialization/JsonNetSerializer.cs
+++ b/src/Umbraco.Infrastructure/Serialization/JsonNetSerializer.cs
@@ -19,11 +19,11 @@ namespace Umbraco.Cms.Infrastructure.Serialization
NullValueHandling = NullValueHandling.Ignore
};
- public string Serialize(object input) => JsonConvert.SerializeObject(input, JsonSerializerSettings);
+ public string Serialize(object? input) => JsonConvert.SerializeObject(input, JsonSerializerSettings);
- public T Deserialize(string input) => JsonConvert.DeserializeObject(input, JsonSerializerSettings);
+ public T? Deserialize(string input) => JsonConvert.DeserializeObject(input, JsonSerializerSettings);
- public T DeserializeSubset(string input, string key)
+ public T? DeserializeSubset(string input, string key)
{
if (key == null) throw new ArgumentNullException(nameof(key));
diff --git a/src/Umbraco.Infrastructure/Serialization/JsonReadConverter.cs b/src/Umbraco.Infrastructure/Serialization/JsonReadConverter.cs
index fe684bd784..028bfac767 100644
--- a/src/Umbraco.Infrastructure/Serialization/JsonReadConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/JsonReadConverter.cs
@@ -26,7 +26,7 @@ namespace Umbraco.Cms.Infrastructure.Serialization
}
///
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
// Load JObject from stream
var jObject = JObject.Load(reader);
@@ -42,11 +42,11 @@ namespace Umbraco.Cms.Infrastructure.Serialization
protected virtual void Deserialize(JObject jobject, T target, JsonSerializer serializer)
{
// Populate the object properties
- serializer.Populate(jobject.CreateReader(), target);
+ serializer.Populate(jobject.CreateReader(), target!);
}
///
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotSupportedException("JsonReadConverter instances do not support writing.");
}
diff --git a/src/Umbraco.Infrastructure/Serialization/JsonToStringConverter.cs b/src/Umbraco.Infrastructure/Serialization/JsonToStringConverter.cs
index 3cf23154c8..3aa03f8cd6 100644
--- a/src/Umbraco.Infrastructure/Serialization/JsonToStringConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/JsonToStringConverter.cs
@@ -9,12 +9,12 @@ namespace Umbraco.Cms.Infrastructure.Serialization
///
internal class JsonToStringConverter : JsonConverter
{
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.ValueType == typeof(string))
{
diff --git a/src/Umbraco.Infrastructure/Serialization/KnownTypeUdiJsonConverter.cs b/src/Umbraco.Infrastructure/Serialization/KnownTypeUdiJsonConverter.cs
index c79071bc8d..ee93430bad 100644
--- a/src/Umbraco.Infrastructure/Serialization/KnownTypeUdiJsonConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/KnownTypeUdiJsonConverter.cs
@@ -12,12 +12,12 @@ namespace Umbraco.Cms.Infrastructure.Serialization
return typeof(Udi).IsAssignableFrom(objectType);
}
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
- writer.WriteValue(value.ToString());
+ writer.WriteValue(value?.ToString());
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var jo = JToken.ReadFrom(reader);
var val = jo.ToObject();
diff --git a/src/Umbraco.Infrastructure/Serialization/NoTypeConverterJsonConverter.cs b/src/Umbraco.Infrastructure/Serialization/NoTypeConverterJsonConverter.cs
index 0b5c9acc49..a44116e360 100644
--- a/src/Umbraco.Infrastructure/Serialization/NoTypeConverterJsonConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/NoTypeConverterJsonConverter.cs
@@ -40,12 +40,12 @@ namespace Umbraco.Cms.Infrastructure.Serialization
return typeof(T).IsAssignableFrom(objectType);
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
return JsonSerializer.CreateDefault(JsonSerializerSettings).Deserialize(reader, objectType);
}
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
JsonSerializer.CreateDefault(JsonSerializerSettings).Serialize(writer, value);
}
diff --git a/src/Umbraco.Infrastructure/Serialization/UdiJsonConverter.cs b/src/Umbraco.Infrastructure/Serialization/UdiJsonConverter.cs
index 0b1f74918b..ce63bbbb55 100644
--- a/src/Umbraco.Infrastructure/Serialization/UdiJsonConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/UdiJsonConverter.cs
@@ -12,12 +12,12 @@ namespace Umbraco.Cms.Infrastructure.Serialization
return typeof (Udi).IsAssignableFrom(objectType);
}
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
- writer.WriteValue(value.ToString());
+ writer.WriteValue(value?.ToString());
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var jo = JToken.ReadFrom(reader);
var val = jo.ToObject();
diff --git a/src/Umbraco.Infrastructure/Serialization/UdiRangeJsonConverter.cs b/src/Umbraco.Infrastructure/Serialization/UdiRangeJsonConverter.cs
index 4cf71b9c5a..88f084092e 100644
--- a/src/Umbraco.Infrastructure/Serialization/UdiRangeJsonConverter.cs
+++ b/src/Umbraco.Infrastructure/Serialization/UdiRangeJsonConverter.cs
@@ -12,12 +12,12 @@ namespace Umbraco.Cms.Infrastructure.Serialization
return typeof(UdiRange).IsAssignableFrom(objectType);
}
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
- writer.WriteValue(value.ToString());
+ writer.WriteValue(value?.ToString());
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var jo = JToken.ReadFrom(reader);
var val = jo.ToObject();
diff --git a/src/Umbraco.Infrastructure/Services/IdKeyMap.cs b/src/Umbraco.Infrastructure/Services/IdKeyMap.cs
index 0c6c57dbfd..c851408a6f 100644
--- a/src/Umbraco.Infrastructure/Services/IdKeyMap.cs
+++ b/src/Umbraco.Infrastructure/Services/IdKeyMap.cs
@@ -173,11 +173,11 @@ namespace Umbraco.Cms.Core.Services
//if it's unknown don't include the nodeObjectType in the query
if (umbracoObjectType == UmbracoObjectTypes.Unknown)
{
- val = _scopeAccessor.AmbientScope.Database.ExecuteScalar("SELECT id FROM umbracoNode WHERE uniqueId=@id", new { id = key});
+ val = _scopeAccessor.AmbientScope?.Database.ExecuteScalar("SELECT id FROM umbracoNode WHERE uniqueId=@id", new { id = key});
}
else
{
- val = _scopeAccessor.AmbientScope.Database.ExecuteScalar("SELECT id FROM umbracoNode WHERE uniqueId=@id AND (nodeObjectType=@type OR nodeObjectType=@reservation)",
+ val = _scopeAccessor.AmbientScope?.Database.ExecuteScalar("SELECT id FROM umbracoNode WHERE uniqueId=@id AND (nodeObjectType=@type OR nodeObjectType=@reservation)",
new { id = key, type = GetNodeObjectTypeGuid(umbracoObjectType), reservation = Cms.Core.Constants.ObjectTypes.IdReservation });
}
scope.Complete();
@@ -215,12 +215,12 @@ namespace Umbraco.Cms.Core.Services
return GetIdForKey(guidUdi.Guid, umbracoType);
}
- public Attempt GetUdiForId(int id, UmbracoObjectTypes umbracoObjectType)
+ public Attempt GetUdiForId(int id, UmbracoObjectTypes umbracoObjectType)
{
var keyAttempt = GetKeyForId(id, umbracoObjectType);
return keyAttempt.Success
- ? Attempt.Succeed(new GuidUdi(UdiEntityTypeHelper.FromUmbracoObjectType(umbracoObjectType), keyAttempt.Result))
- : Attempt.Fail();
+ ? Attempt.Succeed(new GuidUdi(UdiEntityTypeHelper.FromUmbracoObjectType(umbracoObjectType), keyAttempt.Result))
+ : Attempt.Fail();
}
public Attempt GetKeyForId(int id, UmbracoObjectTypes umbracoObjectType)
@@ -261,11 +261,11 @@ namespace Umbraco.Cms.Core.Services
//if it's unknown don't include the nodeObjectType in the query
if (umbracoObjectType == UmbracoObjectTypes.Unknown)
{
- val = _scopeAccessor.AmbientScope.Database.ExecuteScalar("SELECT uniqueId FROM umbracoNode WHERE id=@id", new { id });
+ val = _scopeAccessor.AmbientScope?.Database.ExecuteScalar("SELECT uniqueId FROM umbracoNode WHERE id=@id", new { id });
}
else
{
- val = _scopeAccessor.AmbientScope.Database.ExecuteScalar("SELECT uniqueId FROM umbracoNode WHERE id=@id AND (nodeObjectType=@type OR nodeObjectType=@reservation)",
+ val = _scopeAccessor.AmbientScope?.Database.ExecuteScalar("SELECT uniqueId FROM umbracoNode WHERE id=@id AND (nodeObjectType=@type OR nodeObjectType=@reservation)",
new { id, type = GetNodeObjectTypeGuid(umbracoObjectType), reservation = Cms.Core.Constants.ObjectTypes.IdReservation });
}
scope.Complete();
diff --git a/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs b/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs
index f62361a883..2b856ec98f 100644
--- a/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs
+++ b/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs
@@ -26,7 +26,7 @@ namespace Umbraco.Cms.Core.Services.Implement
_isAvailable = new Lazy(DetermineIsAvailable);
}
- public void Add(AuditType type, int userId, int objectId, string entityType, string comment, string? parameters = null)
+ public void Add(AuditType type, int userId, int objectId, string? entityType, string comment, string? parameters = null)
{
using (var scope = ScopeProvider.CreateScope())
{
@@ -156,7 +156,7 @@ namespace Umbraco.Cms.Core.Services.Implement
}
///
- public IAuditEntry Write(int performingUserId, string perfomingDetails, string performingIp, DateTime eventDateUtc, int affectedUserId, string affectedDetails, string eventType, string eventDetails)
+ public IAuditEntry Write(int performingUserId, string perfomingDetails, string performingIp, DateTime eventDateUtc, int affectedUserId, string? affectedDetails, string eventType, string eventDetails)
{
if (performingUserId < 0 && performingUserId != Cms.Core.Constants.Security.SuperUserId) throw new ArgumentOutOfRangeException(nameof(performingUserId));
if (string.IsNullOrWhiteSpace(perfomingDetails)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(perfomingDetails));
diff --git a/src/Umbraco.Infrastructure/Services/Implement/CacheInstructionService.cs b/src/Umbraco.Infrastructure/Services/Implement/CacheInstructionService.cs
index a037cd1095..749924ecfc 100644
--- a/src/Umbraco.Infrastructure/Services/Implement/CacheInstructionService.cs
+++ b/src/Umbraco.Infrastructure/Services/Implement/CacheInstructionService.cs
@@ -218,7 +218,7 @@ namespace Umbraco.Cms.Core.Services.Implement
}
// Deserialize remote instructions & skip if it fails.
- if (!TryDeserializeInstructions(instruction, out JArray jsonInstructions))
+ if (!TryDeserializeInstructions(instruction, out JArray? jsonInstructions))
{
lastId = instruction.Id; // skip
continue;
@@ -245,7 +245,7 @@ namespace Umbraco.Cms.Core.Services.Implement
///
/// Attempts to deserialize the instructions to a JArray.
///
- private bool TryDeserializeInstructions(CacheInstruction instruction, out JArray jsonInstructions)
+ private bool TryDeserializeInstructions(CacheInstruction instruction, out JArray? jsonInstructions)
{
try
{
@@ -265,17 +265,25 @@ namespace Umbraco.Cms.Core.Services.Implement
///
/// Parses out the individual instructions to be processed.
///
- private static List GetAllInstructions(IEnumerable jsonInstructions)
+ private static List GetAllInstructions(IEnumerable? jsonInstructions)
{
var result = new List();
- foreach (JToken jsonItem in jsonInstructions)
+ if (jsonInstructions is not null)
+ {
+ return result;
+ }
+
+ foreach (JToken jsonItem in jsonInstructions!)
{
// Could be a JObject in which case we can convert to a RefreshInstruction.
// Otherwise it could be another JArray - in which case we'll iterate that.
if (jsonItem is JObject jsonObj)
{
- RefreshInstruction instruction = jsonObj.ToObject();
- result.Add(instruction);
+ RefreshInstruction? instruction = jsonObj.ToObject();
+ if (instruction is not null)
+ {
+ result.Add(instruction);
+ }
}
else
{
@@ -402,19 +410,32 @@ namespace Umbraco.Cms.Core.Services.Implement
refresher.Refresh(id);
}
- private void RefreshByIds(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, string jsonIds)
+ private void RefreshByIds(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, string? jsonIds)
{
ICacheRefresher refresher = GetRefresher(cacheRefreshers, uniqueIdentifier);
- foreach (var id in JsonConvert.DeserializeObject(jsonIds))
+ if (jsonIds is null)
{
- refresher.Refresh(id);
+ return;
+ }
+
+ var ids = JsonConvert.DeserializeObject(jsonIds);
+ if (ids is not null)
+ {
+ foreach (var id in ids)
+ {
+ refresher.Refresh(id);
+ }
}
}
- private void RefreshByJson(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, string jsonPayload)
+ private void RefreshByJson(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, string? jsonPayload)
{
IJsonCacheRefresher refresher = GetJsonRefresher(cacheRefreshers, uniqueIdentifier);
- refresher.Refresh(jsonPayload);
+ if (jsonPayload is not null)
+ {
+ refresher.Refresh(jsonPayload);
+ }
+
}
private void RemoveById(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, int id)
@@ -425,7 +446,7 @@ namespace Umbraco.Cms.Core.Services.Implement
private ICacheRefresher GetRefresher(CacheRefresherCollection cacheRefreshers, Guid id)
{
- ICacheRefresher refresher = cacheRefreshers[id];
+ ICacheRefresher? refresher = cacheRefreshers[id];
if (refresher == null)
{
throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
diff --git a/src/Umbraco.Infrastructure/Services/Implement/DataTypeService.cs b/src/Umbraco.Infrastructure/Services/Implement/DataTypeService.cs
index f52b1f5b05..54c171a1a6 100644
--- a/src/Umbraco.Infrastructure/Services/Implement/DataTypeService.cs
+++ b/src/Umbraco.Infrastructure/Services/Implement/DataTypeService.cs
@@ -58,7 +58,7 @@ namespace Umbraco.Cms.Core.Services.Implement
#region Containers
- public Attempt> CreateContainer(int parentId, Guid key, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
+ public Attempt?> CreateContainer(int parentId, Guid key, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
{
var evtMsgs = EventMessagesFactory.Get();
using (var scope = ScopeProvider.CreateScope())
@@ -96,7 +96,7 @@ namespace Umbraco.Cms.Core.Services.Implement
}
}
- public EntityContainer GetContainer(int containerId)
+ public EntityContainer? GetContainer(int containerId)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -142,7 +142,7 @@ namespace Umbraco.Cms.Core.Services.Implement
}
}
- public Attempt SaveContainer(EntityContainer container, int userId = Cms.Core.Constants.Security.SuperUserId)
+ public Attempt SaveContainer(EntityContainer container, int userId = Cms.Core.Constants.Security.SuperUserId)
{
var evtMsgs = EventMessagesFactory.Get();
@@ -177,7 +177,7 @@ namespace Umbraco.Cms.Core.Services.Implement
return OperationResult.Attempt.Succeed(evtMsgs);
}
- public Attempt DeleteContainer(int containerId, int userId = Cms.Core.Constants.Security.SuperUserId)
+ public Attempt DeleteContainer(int containerId, int userId = Cms.Core.Constants.Security.SuperUserId)
{
var evtMsgs = EventMessagesFactory.Get();
using (var scope = ScopeProvider.CreateScope())
@@ -211,7 +211,7 @@ namespace Umbraco.Cms.Core.Services.Implement
return OperationResult.Attempt.Succeed(evtMsgs);
}
- public Attempt> RenameContainer(int id, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
+ public Attempt?> RenameContainer(int id, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
{
var evtMsgs = EventMessagesFactory.Get();
using (var scope = ScopeProvider.CreateScope())
@@ -254,7 +254,7 @@ namespace Umbraco.Cms.Core.Services.Implement
///
/// Name of the
///
- public IDataType GetDataType(string name)
+ public IDataType? GetDataType(string name)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -269,7 +269,7 @@ namespace Umbraco.Cms.Core.Services.Implement
///
/// Id of the
///
- public IDataType GetDataType(int id)
+ public IDataType? GetDataType(int id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -284,7 +284,7 @@ namespace Umbraco.Cms.Core.Services.Implement
///
/// Unique guid Id of the DataType
///
- public IDataType GetDataType(Guid id)
+ public IDataType? GetDataType(Guid id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -326,7 +326,7 @@ namespace Umbraco.Cms.Core.Services.Implement
}
}
- private void ConvertMissingEditorOfDataTypeToLabel(IDataType dataType)
+ private void ConvertMissingEditorOfDataTypeToLabel(IDataType? dataType)
{
if (dataType == null)
{
@@ -348,7 +348,7 @@ namespace Umbraco.Cms.Core.Services.Implement
}
}
- public Attempt> Move(IDataType toMove, int parentId)
+ public Attempt?> Move(IDataType toMove, int parentId)
{
var evtMsgs = EventMessagesFactory.Get();
var moveInfo = new List>();
@@ -366,7 +366,7 @@ namespace Umbraco.Cms.Core.Services.Implement
try
{
- EntityContainer container = null;
+ EntityContainer? container = null;
if (parentId > 0)
{
container = _dataTypeContainerRepository.Get(parentId);
@@ -492,10 +492,13 @@ namespace Umbraco.Cms.Core.Services.Implement
{
foreach (var propertyGroup in contentType.PropertyGroups)
{
- var types = propertyGroup.PropertyTypes.Where(x => x.DataTypeId == dataType.Id).ToList();
- foreach (var propertyType in types)
+ var types = propertyGroup.PropertyTypes?.Where(x => x.DataTypeId == dataType.Id).ToList();
+ if (types is not null)
{
- propertyGroup.PropertyTypes.Remove(propertyType);
+ foreach (var propertyType in types)
+ {
+ propertyGroup.PropertyTypes?.Remove(propertyType);
+ }
}
}
diff --git a/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs b/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs
index 8cb981f5da..65ea915433 100644
--- a/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs
+++ b/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs
@@ -47,9 +47,9 @@ namespace Umbraco.Cms.Core.Services.Implement
#region Installation
- public CompiledPackage GetCompiledPackageInfo(XDocument xml) => _packageInstallation.ReadPackage(xml);
+ public CompiledPackage GetCompiledPackageInfo(XDocument? xml) => _packageInstallation.ReadPackage(xml);
- public InstallationSummary InstallCompiledPackageData(XDocument packageXml, int userId = Constants.Security.SuperUserId)
+ public InstallationSummary InstallCompiledPackageData(XDocument? packageXml, int userId = Constants.Security.SuperUserId)
{
CompiledPackage compiledPackage = GetCompiledPackageInfo(packageXml);
@@ -98,16 +98,16 @@ namespace Umbraco.Cms.Core.Services.Implement
_createdPackages.Delete(id);
}
- public IEnumerable GetAllCreatedPackages() => _createdPackages.GetAll();
+ public IEnumerable GetAllCreatedPackages() => _createdPackages.GetAll();
- public PackageDefinition GetCreatedPackageById(int id) => _createdPackages.GetById(id);
+ public PackageDefinition? GetCreatedPackageById(int id) => _createdPackages.GetById(id);
public bool SaveCreatedPackage(PackageDefinition definition) => _createdPackages.SavePackage(definition);
public string ExportCreatedPackage(PackageDefinition definition) => _createdPackages.ExportPackage(definition);
- public InstalledPackage GetInstalledPackageByName(string packageName)
- => GetAllInstalledPackages().Where(x => x.PackageName.InvariantEquals(packageName)).FirstOrDefault();
+ public InstalledPackage? GetInstalledPackageByName(string packageName)
+ => GetAllInstalledPackages().Where(x => x.PackageName?.InvariantEquals(packageName) ?? false).FirstOrDefault();
public IEnumerable GetAllInstalledPackages()
{
@@ -118,7 +118,7 @@ namespace Umbraco.Cms.Core.Services.Implement
// Collect the package from the package migration plans
foreach(PackageMigrationPlan plan in _packageMigrationPlans)
{
- if (!installedPackages.TryGetValue(plan.PackageName, out InstalledPackage installedPackage))
+ if (!installedPackages.TryGetValue(plan.PackageName, out InstalledPackage? installedPackage))
{
installedPackage = new InstalledPackage
{
@@ -141,7 +141,7 @@ namespace Umbraco.Cms.Core.Services.Implement
// Collect and merge the packages from the manifests
foreach(PackageManifest package in _manifestParser.GetManifests())
{
- if (!installedPackages.TryGetValue(package.PackageName, out InstalledPackage installedPackage))
+ if (!installedPackages.TryGetValue(package.PackageName, out InstalledPackage? installedPackage))
{
installedPackage = new InstalledPackage
{
diff --git a/src/Umbraco.Infrastructure/Services/Implement/ServerRegistrationService.cs b/src/Umbraco.Infrastructure/Services/Implement/ServerRegistrationService.cs
index 92968510fa..db81c3f79f 100644
--- a/src/Umbraco.Infrastructure/Services/Implement/ServerRegistrationService.cs
+++ b/src/Umbraco.Infrastructure/Services/Implement/ServerRegistrationService.cs
@@ -54,7 +54,7 @@ namespace Umbraco.Cms.Core.Services.Implement
var regs = _serverRegistrationRepository.GetMany().ToArray();
var hasSchedulingPublisher = regs.Any(x => ((ServerRegistration) x).IsSchedulingPublisher);
- var server = regs.FirstOrDefault(x => x.ServerIdentity.InvariantEquals(serverIdentity));
+ var server = regs.FirstOrDefault(x => x.ServerIdentity?.InvariantEquals(serverIdentity) ?? false);
if (server == null)
{
@@ -101,7 +101,7 @@ namespace Umbraco.Cms.Core.Services.Implement
((ServerRegistrationRepository) _serverRegistrationRepository).ClearCache(); // ensure we have up-to-date cache // ensure we have up-to-date cache
- var server = _serverRegistrationRepository.GetMany().FirstOrDefault(x => x.ServerIdentity.InvariantEquals(serverIdentity));
+ var server = _serverRegistrationRepository.GetMany().FirstOrDefault(x => x.ServerIdentity?.InvariantEquals(serverIdentity) ?? false);
if (server == null) return;
server.IsActive = server.IsSchedulingPublisher = false;
_serverRegistrationRepository.Save(server); // will trigger a cache reload // will trigger a cache reload
diff --git a/src/Umbraco.Infrastructure/Services/Implement/TwoFactorLoginService.cs b/src/Umbraco.Infrastructure/Services/Implement/TwoFactorLoginService.cs
index cdcc6b19e9..da5190e27e 100644
--- a/src/Umbraco.Infrastructure/Services/Implement/TwoFactorLoginService.cs
+++ b/src/Umbraco.Infrastructure/Services/Implement/TwoFactorLoginService.cs
@@ -57,14 +57,18 @@ namespace Umbraco.Cms.Core.Services
var providersOnUser = (await _twoFactorLoginRepository.GetByUserOrMemberKeyAsync(userOrMemberKey))
.Select(x => x.ProviderName).ToArray();
- return providersOnUser.Where(IsKnownProviderName);
+ return providersOnUser.Where(IsKnownProviderName)!;
}
///
/// The provider needs to be registered as either a member provider or backoffice provider to show up.
///
- private bool IsKnownProviderName(string providerName)
+ private bool IsKnownProviderName(string? providerName)
{
+ if (providerName is null)
+ {
+ return false;
+ }
if (_identityOptions.Value.Tokens.ProviderMap.ContainsKey(providerName))
{
return true;
@@ -85,14 +89,14 @@ namespace Umbraco.Cms.Core.Services
}
///
- public async Task GetSecretForUserAndProviderAsync(Guid userOrMemberKey, string providerName)
+ public async Task GetSecretForUserAndProviderAsync(Guid userOrMemberKey, string providerName)
{
using IScope scope = _scopeProvider.CreateScope(autoComplete: true);
return (await _twoFactorLoginRepository.GetByUserOrMemberKeyAsync(userOrMemberKey)).FirstOrDefault(x => x.ProviderName == providerName)?.Secret;
}
///
- public async Task GetSetupInfoAsync(Guid userOrMemberKey, string providerName)
+ public async Task GetSetupInfoAsync(Guid userOrMemberKey, string providerName)
{
var secret = await GetSecretForUserAndProviderAsync(userOrMemberKey, providerName);
@@ -104,7 +108,7 @@ namespace Umbraco.Cms.Core.Services
secret = GenerateSecret();
- if (!_twoFactorSetupGenerators.TryGetValue(providerName, out ITwoFactorProvider generator))
+ if (!_twoFactorSetupGenerators.TryGetValue(providerName, out ITwoFactorProvider? generator))
{
throw new InvalidOperationException($"No ITwoFactorSetupGenerator found for provider: {providerName}");
}
@@ -125,7 +129,7 @@ namespace Umbraco.Cms.Core.Services
///
public bool ValidateTwoFactorSetup(string providerName, string secret, string code)
{
- if (!_twoFactorSetupGenerators.TryGetValue(providerName, out ITwoFactorProvider generator))
+ if (!_twoFactorSetupGenerators.TryGetValue(providerName, out ITwoFactorProvider? generator))
{
throw new InvalidOperationException($"No ITwoFactorSetupGenerator found for provider: {providerName}");
}
diff --git a/src/Umbraco.Infrastructure/Suspendable.cs b/src/Umbraco.Infrastructure/Suspendable.cs
index 022a641094..15f6ce4330 100644
--- a/src/Umbraco.Infrastructure/Suspendable.cs
+++ b/src/Umbraco.Infrastructure/Suspendable.cs
@@ -49,8 +49,8 @@ namespace Umbraco.Cms.Infrastructure
s_tried = false;
- ICacheRefresher pageRefresher = cacheRefresherCollection[ContentCacheRefresher.UniqueId];
- pageRefresher.RefreshAll();
+ ICacheRefresher? pageRefresher = cacheRefresherCollection[ContentCacheRefresher.UniqueId];
+ pageRefresher?.RefreshAll();
}
}
diff --git a/src/Umbraco.Infrastructure/Sync/BatchedDatabaseServerMessenger.cs b/src/Umbraco.Infrastructure/Sync/BatchedDatabaseServerMessenger.cs
index bc58342d82..420cac9d27 100644
--- a/src/Umbraco.Infrastructure/Sync/BatchedDatabaseServerMessenger.cs
+++ b/src/Umbraco.Infrastructure/Sync/BatchedDatabaseServerMessenger.cs
@@ -45,11 +45,11 @@ namespace Umbraco.Cms.Infrastructure.Sync
}
///
- protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null)
+ protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable? ids = null, string? json = null)
{
var idsA = ids?.ToArray();
- if (GetArrayType(idsA, out Type arrayType) == false)
+ if (GetArrayType(idsA, out Type? arrayType) == false)
{
throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids));
}
@@ -60,7 +60,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
///
public override void SendMessages()
{
- ICollection batch = GetBatch(false);
+ ICollection? batch = GetBatch(false);
if (batch == null)
{
return;
@@ -72,7 +72,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
CacheInstructionService.DeliverInstructionsInBatches(instructions, LocalIdentity);
}
- private ICollection GetBatch(bool create)
+ private ICollection? GetBatch(bool create)
{
var key = nameof(BatchedDatabaseServerMessenger);
@@ -82,7 +82,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
}
// No thread-safety here because it'll run in only 1 thread (request) at a time.
- var batch = (ICollection)_requestCache.Get(key);
+ var batch = (ICollection?)_requestCache.Get(key);
if (batch == null && create)
{
batch = new List();
@@ -95,11 +95,11 @@ namespace Umbraco.Cms.Infrastructure.Sync
private void BatchMessage(
ICacheRefresher refresher,
MessageType messageType,
- IEnumerable ids = null,
- Type idType = null,
- string json = null)
+ IEnumerable? ids = null,
+ Type? idType = null,
+ string? json = null)
{
- ICollection batch = GetBatch(true);
+ ICollection? batch = GetBatch(true);
IEnumerable instructions = RefreshInstruction.GetInstructions(refresher, JsonSerializer, messageType, ids, idType, json);
// Batch if we can, else write to DB immediately.
diff --git a/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs b/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs
index b6dcc4d432..065b9b8640 100644
--- a/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs
+++ b/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs
@@ -122,12 +122,12 @@ namespace Umbraco.Cms.Infrastructure.Sync
protected override void DeliverRemote(
ICacheRefresher refresher,
MessageType messageType,
- IEnumerable ids = null,
- string json = null)
+ IEnumerable? ids = null,
+ string? json = null)
{
var idsA = ids?.ToArray();
- if (GetArrayType(idsA, out Type idType) == false)
+ if (GetArrayType(idsA, out Type? idType) == false)
{
throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids));
}
diff --git a/src/Umbraco.Infrastructure/Sync/LastSyncedFileManager.cs b/src/Umbraco.Infrastructure/Sync/LastSyncedFileManager.cs
index 462eb88239..134b5c9a92 100644
--- a/src/Umbraco.Infrastructure/Sync/LastSyncedFileManager.cs
+++ b/src/Umbraco.Infrastructure/Sync/LastSyncedFileManager.cs
@@ -9,9 +9,9 @@ namespace Umbraco.Cms.Infrastructure.Sync
{
public sealed class LastSyncedFileManager
{
- private string _distCacheFile;
+ private string? _distCacheFile;
private bool _lastIdReady;
- private object _lastIdLock;
+ private object? _lastIdLock;
private int _lastId;
private readonly IHostingEnvironment _hostingEnvironment;
@@ -24,6 +24,10 @@ namespace Umbraco.Cms.Infrastructure.Sync
/// The id.
public void SaveLastSyncedId(int id)
{
+ if (_lastIdLock is null)
+ {
+ return;
+ }
lock (_lastIdLock)
{
if (!_lastIdReady)
diff --git a/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs b/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs
index 536d1d9aa0..9692dcc8b5 100644
--- a/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs
+++ b/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs
@@ -34,7 +34,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
}
// ensures that all items in the enumerable are of the same type, either int or Guid.
- protected static bool GetArrayType(IEnumerable ids, out Type arrayType)
+ protected static bool GetArrayType(IEnumerable? ids, out Type? arrayType)
{
arrayType = null;
if (ids == null) return true;
@@ -176,7 +176,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
///
/// Since this is only for non strongly typed it will throw for message types that by instance
///
- protected void DeliverLocal(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null)
+ protected void DeliverLocal(ICacheRefresher refresher, MessageType messageType, IEnumerable? ids = null, string? json = null)
{
if (refresher == null) throw new ArgumentNullException(nameof(refresher));
@@ -205,7 +205,10 @@ namespace Umbraco.Cms.Infrastructure.Sync
var jsonRefresher = refresher as IJsonCacheRefresher;
if (jsonRefresher == null)
throw new InvalidOperationException("The cache refresher " + refresher.GetType() + " is not of type " + typeof(IJsonCacheRefresher));
- jsonRefresher.Refresh(json);
+ if (json is not null)
+ {
+ jsonRefresher.Refresh(json);
+ }
break;
case MessageType.RemoveById:
@@ -283,7 +286,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
// refresher.Notify(payload);
//}
- protected abstract void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null);
+ protected abstract void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable? ids = null, string? json = null);
//protected abstract void DeliverRemote(ICacheRefresher refresher, object payload);
@@ -304,7 +307,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
DeliverRemote(refresher, MessageType.RefreshByJson, null, json);
}
- protected virtual void Deliver(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null)
+ protected virtual void Deliver(ICacheRefresher refresher, MessageType messageType, IEnumerable? ids = null, string? json = null)
{
if (refresher == null) throw new ArgumentNullException(nameof(refresher));
diff --git a/src/Umbraco.Infrastructure/Sync/SyncBootStateAccessor.cs b/src/Umbraco.Infrastructure/Sync/SyncBootStateAccessor.cs
index ff6823177a..4fb7ca59d5 100644
--- a/src/Umbraco.Infrastructure/Sync/SyncBootStateAccessor.cs
+++ b/src/Umbraco.Infrastructure/Sync/SyncBootStateAccessor.cs
@@ -16,7 +16,7 @@ namespace Umbraco.Cms.Infrastructure.Sync
private SyncBootState _syncBootState;
private bool _syncBootStateReady;
- private object _syncBootStateLock;
+ private object? _syncBootStateLock;
public SyncBootStateAccessor(
ILogger logger,
diff --git a/src/Umbraco.Infrastructure/TagQuery.cs b/src/Umbraco.Infrastructure/TagQuery.cs
index 284416d9d4..b54d6e38d8 100644
--- a/src/Umbraco.Infrastructure/TagQuery.cs
+++ b/src/Umbraco.Infrastructure/TagQuery.cs
@@ -29,7 +29,7 @@ namespace Umbraco.Cms.Core
}
///
- public IEnumerable GetContentByTag(string tag, string group = null, string? culture = null)
+ public IEnumerable GetContentByTag(string tag, string? group = null, string? culture = null)
{
var ids = _tagService.GetTaggedContentByTag(tag, group, culture)
.Select(x => x.EntityId);
@@ -47,7 +47,7 @@ namespace Umbraco.Cms.Core
}
///
- public IEnumerable GetMediaByTag(string tag, string group = null, string? culture = null)
+ public IEnumerable GetMediaByTag(string tag, string? group = null, string? culture = null)
{
var ids = _tagService.GetTaggedMediaByTag(tag, group, culture)
.Select(x => x.EntityId);
@@ -65,37 +65,37 @@ namespace Umbraco.Cms.Core
}
///
- public IEnumerable GetAllTags(string group = null, string? culture = null)
+ public IEnumerable GetAllTags(string? group = null, string? culture = null)
{
return _mapper.MapEnumerable(_tagService.GetAllTags(group, culture));
}
///
- public IEnumerable GetAllContentTags(string group = null, string? culture = null)
+ public IEnumerable GetAllContentTags(string? group = null, string? culture = null)
{
return _mapper.MapEnumerable(_tagService.GetAllContentTags(group, culture));
}
///
- public IEnumerable GetAllMediaTags(string group = null, string? culture = null)
+ public IEnumerable GetAllMediaTags(string? group = null, string? culture = null)
{
return _mapper.MapEnumerable(_tagService.GetAllMediaTags(group, culture));
}
///
- public IEnumerable GetAllMemberTags(string group = null, string? culture = null)
+ public IEnumerable GetAllMemberTags(string? group = null, string? culture = null)
{
return _mapper.MapEnumerable(_tagService.GetAllMemberTags(group, culture));
}
///
- public IEnumerable GetTagsForProperty(int contentId, string propertyTypeAlias, string group = null, string? culture = null)
+ public IEnumerable GetTagsForProperty(int contentId, string propertyTypeAlias, string? group = null, string? culture = null)
{
return _mapper.MapEnumerable(_tagService.GetTagsForProperty(contentId, propertyTypeAlias, group, culture));
}
///
- public IEnumerable GetTagsForEntity(int contentId, string group = null, string? culture = null)
+ public IEnumerable GetTagsForEntity(int contentId, string? group = null, string? culture = null)
{
return _mapper.MapEnumerable(_tagService.GetTagsForEntity(contentId, group, culture));
}
diff --git a/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs b/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs
index 63ad681969..7f006a056d 100644
--- a/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs
+++ b/src/Umbraco.Infrastructure/Trees/TreeRootNode.cs
@@ -143,7 +143,7 @@ namespace Umbraco.Cms.Core.Models.Trees
/// The node's children collection
///
[DataMember(Name = "children")]
- public TreeNodeCollection Children { get; private set; }
+ public TreeNodeCollection? Children { get; private set; }
///
/// Returns true if there are any children
@@ -152,6 +152,6 @@ namespace Umbraco.Cms.Core.Models.Trees
/// This is used in the UI to configure a full screen section/app
///
[DataMember(Name = "containsTrees")]
- public bool ContainsTrees => Children.Count > 0 || !_isSingleNodeTree;
+ public bool ContainsTrees => Children?.Count > 0 || !_isSingleNodeTree;
}
}
diff --git a/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs b/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs
index 34c3f65652..37370d73d2 100644
--- a/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs
+++ b/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs
@@ -98,8 +98,8 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
// custom back office assets, and any scripts found in package manifests
// that have the default bundle options.
- IEnumerable jsAssets = (customAssets.TryGetValue(AssetType.Javascript, out IEnumerable customScripts) ? customScripts : Enumerable.Empty())
- .Union(propertyEditorAssets.TryGetValue(AssetType.Javascript, out IEnumerable scripts) ? scripts : Enumerable.Empty());
+ IEnumerable jsAssets = (customAssets.TryGetValue(AssetType.Javascript, out IEnumerable? customScripts) ? customScripts : Enumerable.Empty())
+ .Union(propertyEditorAssets.TryGetValue(AssetType.Javascript, out IEnumerable? scripts) ? scripts : Enumerable.Empty());
_runtimeMinifier.CreateJsBundle(
UmbracoExtensionsJsBundleName,
@@ -108,17 +108,17 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
GetScriptsForBackOfficeExtensions(jsAssets)));
// Create a bundle per package manifest that is declaring an Independent bundle type
- RegisterPackageBundlesForIndependentOptions(_parser.CombinedManifest.Scripts, AssetType.Javascript);
+ RegisterPackageBundlesForIndependentOptions(_parser.CombinedManifest?.Scripts, AssetType.Javascript);
// Create a single non-optimized (no file processing) bundle for all manifests declaring None as a bundle option
- RegisterPackageBundlesForNoneOption(_parser.CombinedManifest.Scripts, UmbracoNonOptimizedPackageJsBundleName);
+ RegisterPackageBundlesForNoneOption(_parser.CombinedManifest?.Scripts, UmbracoNonOptimizedPackageJsBundleName);
// This bundle includes all CSS from property editor assets,
// custom back office assets, and any CSS found in package manifests
// that have the default bundle options.
- IEnumerable cssAssets = (customAssets.TryGetValue(AssetType.Css, out IEnumerable customStyles) ? customStyles : Enumerable.Empty())
- .Union(propertyEditorAssets.TryGetValue(AssetType.Css, out IEnumerable styles) ? styles : Enumerable.Empty());
+ IEnumerable cssAssets = (customAssets.TryGetValue(AssetType.Css, out IEnumerable? customStyles) ? customStyles : Enumerable.Empty())
+ .Union(propertyEditorAssets.TryGetValue(AssetType.Css, out IEnumerable? styles) ? styles : Enumerable.Empty());
_runtimeMinifier.CreateCssBundle(
UmbracoCssBundleName,
@@ -127,23 +127,23 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
GetStylesheetsForBackOffice(cssAssets)));
// Create a bundle per package manifest that is declaring an Independent bundle type
- RegisterPackageBundlesForIndependentOptions(_parser.CombinedManifest.Stylesheets, AssetType.Css);
+ RegisterPackageBundlesForIndependentOptions(_parser.CombinedManifest?.Stylesheets, AssetType.Css);
// Create a single non-optimized (no file processing) bundle for all manifests declaring None as a bundle option
- RegisterPackageBundlesForNoneOption(_parser.CombinedManifest.Stylesheets, UmbracoNonOptimizedPackageCssBundleName);
+ RegisterPackageBundlesForNoneOption(_parser.CombinedManifest?.Stylesheets, UmbracoNonOptimizedPackageCssBundleName);
}
public static string GetIndependentPackageBundleName(ManifestAssets manifestAssets, AssetType assetType)
=> $"{manifestAssets.PackageName.ToLowerInvariant()}-{(assetType == AssetType.Css ? "css" : "js")}";
private void RegisterPackageBundlesForNoneOption(
- IReadOnlyDictionary> combinedPackageManifestAssets,
+ IReadOnlyDictionary>? combinedPackageManifestAssets,
string bundleName)
{
var assets = new HashSet(StringComparer.InvariantCultureIgnoreCase);
// Create a bundle per package manifest that is declaring the matching BundleOptions
- if (combinedPackageManifestAssets.TryGetValue(BundleOptions.None, out IReadOnlyList manifestAssetList))
+ if (combinedPackageManifestAssets?.TryGetValue(BundleOptions.None, out IReadOnlyList? manifestAssetList) ?? false)
{
foreach(var asset in manifestAssetList.SelectMany(x => x.Assets))
{
@@ -159,16 +159,16 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
}
private void RegisterPackageBundlesForIndependentOptions(
- IReadOnlyDictionary> combinedPackageManifestAssets,
+ IReadOnlyDictionary>? combinedPackageManifestAssets,
AssetType assetType)
{
// Create a bundle per package manifest that is declaring the matching BundleOptions
- if (combinedPackageManifestAssets.TryGetValue(BundleOptions.Independent, out IReadOnlyList manifestAssetList))
+ if (combinedPackageManifestAssets?.TryGetValue(BundleOptions.Independent, out IReadOnlyList? manifestAssetList) ?? false)
{
foreach (ManifestAssets manifestAssets in manifestAssetList)
{
string bundleName = GetIndependentPackageBundleName(manifestAssets, assetType);
- string[] filePaths = FormatPaths(manifestAssets.Assets.ToArray());
+ string[]? filePaths = FormatPaths(manifestAssets.Assets.ToArray());
switch (assetType)
{
@@ -189,12 +189,12 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
/// Returns scripts used to load the back office
///
///
- private string[] GetScriptsForBackOfficeExtensions(IEnumerable propertyEditorScripts)
+ private string[] GetScriptsForBackOfficeExtensions(IEnumerable propertyEditorScripts)
{
var scripts = new HashSet(StringComparer.InvariantCultureIgnoreCase);
// only include scripts with the default bundle options here
- if (_parser.CombinedManifest.Scripts.TryGetValue(BundleOptions.Default, out IReadOnlyList manifestAssets))
+ if (_parser.CombinedManifest?.Scripts.TryGetValue(BundleOptions.Default, out IReadOnlyList? manifestAssets) ?? false)
{
foreach (string script in manifestAssets.SelectMany(x => x.Assets))
{
@@ -202,9 +202,12 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
}
}
- foreach (string script in propertyEditorScripts)
+ foreach (string? script in propertyEditorScripts)
{
- scripts.Add(script);
+ if (script is not null)
+ {
+ scripts.Add(script);
+ }
}
return scripts.ToArray();
@@ -214,22 +217,22 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
/// Returns the list of scripts for back office initialization
///
///
- private string[] GetScriptsForBackOfficeCore()
+ private string[]? GetScriptsForBackOfficeCore()
{
var resources = JsonConvert.DeserializeObject(Resources.JsInitialize);
- return resources.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
+ return resources?.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
}
///
/// Returns stylesheets used to load the back office
///
///
- private string[] GetStylesheetsForBackOffice(IEnumerable propertyEditorStyles)
+ private string[] GetStylesheetsForBackOffice(IEnumerable propertyEditorStyles)
{
var stylesheets = new HashSet(StringComparer.InvariantCultureIgnoreCase);
// only include css with the default bundle options here
- if (_parser.CombinedManifest.Stylesheets.TryGetValue(BundleOptions.Default, out IReadOnlyList manifestAssets))
+ if (_parser.CombinedManifest?.Stylesheets.TryGetValue(BundleOptions.Default, out IReadOnlyList? manifestAssets) ?? false)
{
foreach (string script in manifestAssets.SelectMany(x => x.Assets))
{
@@ -237,9 +240,12 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
}
}
- foreach (string stylesheet in propertyEditorStyles)
+ foreach (string? stylesheet in propertyEditorStyles)
{
- stylesheets.Add(stylesheet);
+ if (stylesheet is not null)
+ {
+ stylesheets.Add(stylesheet);
+ }
}
return stylesheets.ToArray();
@@ -249,20 +255,20 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
/// Returns the scripts used for tinymce
///
///
- private string[] GetScriptsForTinyMce()
+ private string[]? GetScriptsForTinyMce()
{
var resources = JsonConvert.DeserializeObject(Resources.TinyMceInitialize);
- return resources.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
+ return resources?.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
}
///
/// Returns the scripts used for preview
///
///
- private string[] GetScriptsForPreview()
+ private string[]? GetScriptsForPreview()
{
var resources = JsonConvert.DeserializeObject(Resources.PreviewInitialize);
- return resources.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
+ return resources?.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
}
///
@@ -270,11 +276,11 @@ namespace Umbraco.Cms.Infrastructure.WebAssets
///
///
///
- private string[] FormatPaths(params string[] assets)
+ private string[]? FormatPaths(params string[]? assets)
{
var umbracoPath = _globalSettings.GetUmbracoMvcArea(_hostingEnvironment);
- return assets
+ return assets?
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(x => !x.StartsWith("/") && Uri.IsWellFormedUriString(x, UriKind.Relative)
// most declarations with be made relative to the /umbraco folder, so things