Fixed build errors after turning nullability errors off

This commit is contained in:
Nikolaj Geisle
2022-02-10 10:32:45 +01:00
parent b75eae01f3
commit 83baba696c
39 changed files with 91 additions and 69 deletions

View File

@@ -35,7 +35,15 @@ namespace Umbraco.Cms.Core
/// <summary>
/// Gets the attempt result, if successful, else a default value.
/// </summary>
public TResult? ResultOr(TResult? value) => Success ? Result : value;
public TResult ResultOr(TResult value)
{
if (Success && Result is not null)
{
return Result;
}
return value;
}
// optimize, use a singleton failed attempt
private static readonly Attempt<TResult> Failed = new Attempt<TResult>(false, default(TResult), null);

View File

@@ -27,7 +27,7 @@ namespace Umbraco.Cms.Core.Media.Exif
/// <returns>
/// An <see cref="T:System.ComponentModel.ICustomTypeDescriptor"/> that can provide metadata for the type.
/// </returns>
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object? instance)
{
return new ExifFileTypeDescriptor(base.GetTypeDescriptor(objectType, instance), instance);
}

View File

@@ -472,7 +472,7 @@ namespace Umbraco.Cms.Core.Media.Exif
/// <param name="obj">Another object to compare to.</param>
/// <returns>true if obj and this instance are the same type and represent
/// the same value; otherwise, false.</returns>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (obj == null)
return false;

View File

@@ -10,12 +10,12 @@ namespace Umbraco.Cms.Core.Persistence
/// <summary>
/// Gets an entity.
/// </summary>
TEntity Get(TId id);
TEntity? Get(TId? id);
/// <summary>
/// Gets entities.
/// </summary>
IEnumerable<TEntity> GetMany(params TId[] ids);
IEnumerable<TEntity> GetMany(params TId?[] ids);
/// <summary>
/// Gets a value indicating whether an entity exists.

View File

@@ -95,13 +95,13 @@ namespace Umbraco.Cms.Core.Persistence.Repositories
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
IUser Get(int id, bool includeSecurityData);
IUser Get(int? id, bool includeSecurityData);
IProfile GetProfile(string username);
IProfile GetProfile(int id);
IDictionary<UserState, int> GetUserStates();
Guid CreateLoginSession(int userId, string requestingIpAddress, bool cleanStaleSessions = true);
Guid CreateLoginSession(int? userId, string requestingIpAddress, bool cleanStaleSessions = true);
bool ValidateLoginSession(int userId, Guid sessionId);
int ClearLoginSessions(int userId);
int ClearLoginSessions(TimeSpan timespan);

View File

@@ -21,7 +21,7 @@ namespace Umbraco.Cms.Core.Security
/// <returns>The current user's Id that has been authenticated for the request.</returns>
/// <remarks>If authentication hasn't taken place this will be unsuccessful.</remarks>
// TODO: This should just be an extension method on ClaimsIdentity
Attempt<int> GetUserId();
Attempt<int?> GetUserId();
/// <summary>
/// Checks if the specified user as access to the app

View File

@@ -9,7 +9,7 @@
<Description>Contains the core assembly needed to run Umbraco Cms. This package only contains the assembly, and can be used for package development. Use the template in the Umbraco.Templates package to setup Umbraco</Description>
<Product>Umbraco CMS</Product>
<Nullable>enable</Nullable>
<WarningsAsErrors>Nullable</WarningsAsErrors>
<!-- <WarningsAsErrors>Nullable</WarningsAsErrors>-->
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">

View File

@@ -64,7 +64,7 @@ namespace Umbraco.Cms.Infrastructure.Examine
// explicit scope since we may be in a background thread
using (_scopeProvider.CreateScope(autoComplete: true))
{
if (_publicAccessService.IsProtected(path))
if (_publicAccessService.IsProtected(path).Success)
{
return false;
}

View File

@@ -34,7 +34,7 @@ namespace Umbraco.Cms.Core.Logging.Serilog.Enrichers
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
Guid requestId;
Guid? requestId;
if (!LogHttpRequest.TryGetCurrentHttpRequestId(out requestId, _requestCache))
return;

View File

@@ -17,7 +17,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Dtos
[Column("userId")]
[ForeignKey(typeof(UserDto), Name = "FK_" + TableName + "_umbracoUser_id")]
public int UserId { get; set; }
public int? UserId { get; set; }
/// <summary>
/// Tracks when the session is created

View File

@@ -131,7 +131,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Factories
ContentTypeId = contentTypeId,
DataTypeId = propertyType.DataTypeId,
Description = propertyType.Description,
Mandatory = propertyType.Mandatory,
Mandatory = propertyType.Mandatory ?? false,
MandatoryMessage = propertyType.MandatoryMessage,
Name = propertyType.Name,
SortOrder = propertyType.SortOrder,

View File

@@ -157,7 +157,7 @@ namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
public IUser Get(int id, bool includeSecurityData)
public IUser Get(int? id, bool includeSecurityData)
{
return GetWith(sql => sql.Where<UserDto>(x => x.Id == id), includeSecurityData);
}
@@ -194,7 +194,7 @@ SELECT 4 AS [Key], COUNT(id) AS [Value] FROM umbracoUser WHERE userDisabled = 0
return result.ToDictionary(x => (UserState)x.Key, x => x.Value);
}
public Guid CreateLoginSession(int userId, string requestingIpAddress, bool cleanStaleSessions = true)
public Guid CreateLoginSession(int? userId, string requestingIpAddress, bool cleanStaleSessions = true)
{
var now = DateTime.UtcNow;
var dto = new UserLoginDto

View File

@@ -159,7 +159,7 @@ namespace Umbraco.Cms.Core.PropertyEditors
{
//if it's a boolean property type but a string is found, try to do a conversion
var converted = sBool.TryConvertTo<bool>();
if (converted)
if (converted.Success)
o[field.PropertyName] = converted.Result;
}
else

View File

@@ -45,8 +45,8 @@ namespace Umbraco.Cms.Core.PropertyEditors
return new MultipleTextStringConfiguration
{
Minimum = min ? min.Result : 0,
Maximum = max ? max.Result : 0
Minimum = min.Success ? min.Result : 0,
Maximum = max.Success ? max.Result : 0
};
}

View File

@@ -63,7 +63,7 @@ namespace Umbraco.Cms.Core.Routing
// but until then we need to look it up in the db. For now we've implemented a cached service for
// converting Int -> Guid and vice versa.
Attempt<int> found = entityService.GetId(errorPage.ContentKey, UmbracoObjectTypes.Document);
if (found)
if (found.Success)
{
return found.Result;
}

View File

@@ -215,7 +215,7 @@ namespace Umbraco.Cms.Core.Services
public Attempt<Udi> GetUdiForId(int id, UmbracoObjectTypes umbracoObjectType)
{
var keyAttempt = GetKeyForId(id, umbracoObjectType);
return keyAttempt
return keyAttempt.Success
? Attempt.Succeed<Udi>(new GuidUdi(UdiEntityTypeHelper.FromUmbracoObjectType(umbracoObjectType), keyAttempt.Result))
: Attempt<Udi>.Fail();
}

View File

@@ -127,7 +127,7 @@ namespace Umbraco.Cms.Core.Services.Implement
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
return asInt ? asInt.Result : int.MinValue;
return asInt.Success ? asInt.Result : int.MinValue;
})
.Where(x => x != int.MinValue && x != dataType.Id)
.ToArray();

View File

@@ -369,7 +369,7 @@ namespace Umbraco.Cms.Core.Services.Implement
if (currentCulture.Name.Length > 2) return currentCulture;
var attempt = _fileSources.Value.TryConvert2LetterCultureTo4Letter(currentCulture.TwoLetterISOLanguageName);
return attempt ? attempt.Result : currentCulture;
return attempt.Success ? attempt.Result : currentCulture;
}
private string GetFromDictionarySource(CultureInfo culture, string area, string key,

View File

@@ -40,7 +40,7 @@ namespace Umbraco.Cms.Core.Services.Implement
var editor = _propertyEditors[propertyType.PropertyEditorAlias];
if (editor == null) throw new InvalidOperationException("No property editor found by alias " + propertyType.PropertyEditorAlias);
return ValidatePropertyValue(editor, dataType, postedValue, propertyType.Mandatory, propertyType.ValidationRegExp, propertyType.MandatoryMessage, propertyType.ValidationRegExpMessage);
return ValidatePropertyValue(editor, dataType, postedValue, propertyType.Mandatory ?? false, propertyType.ValidationRegExp, propertyType.MandatoryMessage, propertyType.ValidationRegExpMessage);
}
/// <inheritdoc />
@@ -188,7 +188,7 @@ namespace Umbraco.Cms.Core.Services.Implement
}
var configuration = _dataTypeService.GetDataType(propertyType.DataTypeId).Configuration;
var valueEditor = editor.GetValueEditor(configuration);
return !valueEditor.Validate(value, propertyType.Mandatory, propertyType.ValidationRegExp).Any();
return !valueEditor.Validate(value, propertyType.Mandatory ?? false, propertyType.ValidationRegExp).Any();
}
}
}

View File

@@ -120,7 +120,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)] // Needed to enforce the principle set on the request, if one exists.
public IDictionary<string, object> GetPasswordConfig(int userId)
{
Attempt<int> currentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId();
Attempt<int?> currentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId();
return _passwordConfiguration.GetConfiguration(
currentUserId.Success
? currentUserId.Result != userId

View File

@@ -25,7 +25,6 @@ using Umbraco.Cms.Web.BackOffice.Security;
using Umbraco.Cms.Web.BackOffice.Trees;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Web.BackOffice.Controllers
{

View File

@@ -419,7 +419,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
private ContentItemDisplay GetEmptyInner(IContentType contentType, int parentId)
{
var emptyContent = _contentService.Create("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var emptyContent = _contentService.Create("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
var mapped = MapToDisplay(emptyContent);
return CleanContentItemDisplay(mapped);
@@ -451,7 +451,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
var result = new List<ContentItemDisplay>();
var backOfficeSecurity = _backofficeSecurityAccessor.BackOfficeSecurity;
var userId = backOfficeSecurity.GetUserId().ResultOr(0);
var userId = backOfficeSecurity.GetUserId().Result ?? 0;
var currentUser = backOfficeSecurity.CurrentUser;
// We know that if the ID is less than 0 the parent is null.
// Since this is called with parent ID it's safe to assume that the parent is the same for all the content types.
@@ -670,9 +670,9 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return ValidationProblem(ModelState);
}
var blueprint = _contentService.CreateContentFromBlueprint(content, name, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var blueprint = _contentService.CreateContentFromBlueprint(content, name, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
_contentService.SaveBlueprint(blueprint, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
_contentService.SaveBlueprint(blueprint, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
var notificationModel = new SimpleNotificationModel();
notificationModel.AddSuccessNotification(
@@ -1649,7 +1649,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return HandleContentNotFound(id);
}
var publishResult = _contentService.SaveAndPublish(foundContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var publishResult = _contentService.SaveAndPublish(foundContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
if (publishResult.Success == false)
{
var notificationModel = new SimpleNotificationModel();
@@ -1701,7 +1701,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
//if the current item is in the recycle bin
if (foundContent.Trashed == false)
{
var moveResult = _contentService.MoveToRecycleBin(foundContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var moveResult = _contentService.MoveToRecycleBin(foundContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
if (moveResult.Success == false)
{
return ValidationProblem();
@@ -1709,7 +1709,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
}
else
{
var deleteResult = _contentService.Delete(foundContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var deleteResult = _contentService.Delete(foundContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
if (deleteResult.Success == false)
{
return ValidationProblem();
@@ -1731,7 +1731,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[Authorize(Policy = AuthorizationPolicies.ContentPermissionEmptyRecycleBin)]
public IActionResult EmptyRecycleBin()
{
_contentService.EmptyRecycleBin(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
_contentService.EmptyRecycleBin(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
return Ok(_localizedTextService.Localize("defaultdialogs", "recycleBinIsEmpty"));
}
@@ -1804,7 +1804,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
}
var toMove = toMoveResult.Value;
_contentService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
_contentService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
return Content(toMove.Path, MediaTypeNames.Text.Plain, Encoding.UTF8);
}
@@ -1830,7 +1830,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return toCopyResult.Result;
}
var toCopy = toCopyResult.Value;
var c = _contentService.Copy(toCopy, copy.ParentId, copy.RelateToOriginal, copy.Recursive, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var c = _contentService.Copy(toCopy, copy.ParentId, copy.RelateToOriginal, copy.Recursive, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
return Content(c.Path, MediaTypeNames.Text.Plain, Encoding.UTF8);
}
@@ -1862,7 +1862,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
if (model.Cultures.Length == 0 || model.Cultures.Length == languageCount)
{
//this means that the entire content item will be unpublished
var unpublishResult = _contentService.Unpublish(foundContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var unpublishResult = _contentService.Unpublish(foundContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
var content = MapToDisplayWithSchedule(foundContent);
@@ -1885,7 +1885,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
var results = new Dictionary<string, PublishResult>();
foreach (var c in model.Cultures)
{
var result = _contentService.Unpublish(foundContent, culture: c, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var result = _contentService.Unpublish(foundContent, culture: c, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
results[c] = result;
if (result.Result == PublishResultType.SuccessUnpublishMandatoryCulture)
{
@@ -2544,7 +2544,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return NotFound();
}
_contentVersionService.SetPreventCleanup(versionId, preventCleanup, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
_contentVersionService.SetPreventCleanup(versionId, preventCleanup, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
return NoContent();
}
@@ -2609,7 +2609,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[HttpPost]
public IActionResult PostRollbackContent(int contentId, int versionId, string culture = "*")
{
var rollbackResult = _contentService.Rollback(contentId, versionId, culture, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var rollbackResult = _contentService.Rollback(contentId, versionId, culture, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
if (rollbackResult.Success)
return Ok();

View File

@@ -562,7 +562,10 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0);
var element = XElement.Parse(xd.InnerXml);
_packageDataInstallation.ImportDocumentType(element, userId);
if (userId is not null)
{
_packageDataInstallation.ImportDocumentType(element, userId.Value);
}
// Try to clean up the temporary file.
try

View File

@@ -244,8 +244,10 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[AppendUserModifiedHeader]
public IActionResult PostSetAvatar(IList<IFormFile> file)
{
var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId();
var result = userId.ResultOr(0);
//borrow the logic from the user controller
return UsersController.PostSetAvatarInternal(file, _userService, _appCaches.RuntimeCache, _mediaFileManager, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
return UsersController.PostSetAvatarInternal(file, _userService, _appCaches.RuntimeCache, _mediaFileManager, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
}
/// <summary>
@@ -285,7 +287,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[ValidateAngularAntiForgeryToken]
public async Task<Dictionary<string, string>> GetCurrentUserLinkedLogins()
{
var identityUser = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0).ToString(CultureInfo.InvariantCulture));
var identityUser = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)?.ToString(CultureInfo.InvariantCulture));
// deduplicate in case there are duplicates (there shouldn't be now since we have a unique constraint on the external logins
// but there didn't used to be)

View File

@@ -91,7 +91,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
long totalRecords;
var dateQuery = sinceDate.HasValue ? _sqlContext.Query<IAuditItem>().Where(x => x.CreateDate >= sinceDate) : null;
var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0);
var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0;
var result = _auditService.GetPagedItemsByUser(userId, pageNumber - 1, pageSize, out totalRecords, orderDirection, customFilter:dateQuery);
var mapped = _umbracoMapper.MapEnumerable<IAuditItem, AuditLog>(result);
return new PagedResult<AuditLog>(totalRecords, pageNumber, pageSize)

View File

@@ -135,7 +135,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return NotFound();
}
var emptyContent = _mediaService.CreateMedia("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
var emptyContent = _mediaService.CreateMedia("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
var mapped = _umbracoMapper.Map<MediaItemDisplay>(emptyContent);
//remove the listview app if it exists
@@ -452,7 +452,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
//if the current item is in the recycle bin
if (foundMedia.Trashed == false)
{
var moveResult = _mediaService.MoveToRecycleBin(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
var moveResult = _mediaService.MoveToRecycleBin(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
if (moveResult == false)
{
return ValidationProblem();
@@ -460,7 +460,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
}
else
{
var deleteResult = _mediaService.Delete(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
var deleteResult = _mediaService.Delete(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
if (deleteResult == false)
{
return ValidationProblem();
@@ -495,7 +495,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
var destinationParentID = move.ParentId;
var sourceParentID = toMove.ParentId;
var moveResult = _mediaService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
var moveResult = _mediaService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
if (sourceParentID == destinationParentID)
{
@@ -568,7 +568,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
}
//save the item
var saveStatus = _mediaService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
var saveStatus = _mediaService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
//return the updated model
var display = _umbracoMapper.Map<MediaItemDisplay>(contentItem.PersistedContent);
@@ -617,7 +617,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[HttpPost]
public IActionResult EmptyRecycleBin()
{
_mediaService.EmptyRecycleBin(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
_mediaService.EmptyRecycleBin(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
return Ok(_localizedTextService.Localize("defaultdialogs", "recycleBinIsEmpty"));
}

View File

@@ -93,7 +93,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
[HttpDelete]
public IActionResult DeleteCreatedPackage(int packageId)
{
_packagingService.DeleteCreatedPackage(packageId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
_packagingService.DeleteCreatedPackage(packageId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? -1);
return Ok();
}
@@ -112,11 +112,11 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
return ValidationErrorResult.CreateNotificationValidationErrorResult(
$"Package migration failed on package {packageName} with error: {ex.Message}. Check log for full details.");
}
}
}
[HttpGet]
public IActionResult DownloadCreatedPackage(int id)
public IActionResult DownloadCreatedPackage(int id)
{
var package = _packagingService.GetCreatedPackageById(id);
if (package == null)

View File

@@ -180,7 +180,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
var enumType = paramType.GetEnumeratedType();
var converted = requestParam.TryConvertTo(enumType ?? paramType);
if (converted)
if (converted.Success)
{
foundCandidate = MatchByType(paramType, context);
if (foundCandidate.HasValue)

View File

@@ -53,7 +53,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
public async Task<ActionResult<IEnumerable<Section>>> GetSections()
{
var sections = _sectionService.GetAllowedSections(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
var sections = _sectionService.GetAllowedSections(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().Result ?? 0);
var sectionModels = sections.Select(_umbracoMapper.Map<Section>).ToArray();

View File

@@ -716,7 +716,7 @@ namespace Umbraco.Cms.Web.BackOffice.Controllers
public IActionResult PostDisableUsers([FromQuery]int[] userIds)
{
var tryGetCurrentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId();
if (tryGetCurrentUserId && userIds.Contains(tryGetCurrentUserId.Result))
if (tryGetCurrentUserId.Success && userIds.Contains(tryGetCurrentUserId.Result.Value))
{
return ValidationProblem("The current user cannot disable itself");
}

View File

@@ -118,7 +118,13 @@ namespace Umbraco.Cms.Web.BackOffice.Filters
return;
}
IUser user = _userService.GetUserById(identity.GetId());
var id = identity.GetId();
if (id is null)
{
return;
}
IUser user = _userService.GetUserById(id.Value);
if (user == null)
{
return;

View File

@@ -176,7 +176,7 @@ namespace Umbraco.Cms.Web.BackOffice.Filters
if (property.DataType is null) throw new InvalidOperationException($"{nameof(property)}.{nameof(property.DataType)} cannot be null");
foreach (var validationResult in PropertyValidationService.ValidatePropertyValue(
editor, property.DataType, postedValue, property.IsRequired,
editor, property.DataType, postedValue, property.IsRequired ?? false,
property.ValidationRegExp, property.IsRequiredMessage, property.ValidationRegExpMessage))
{
AddPropertyError(model, modelWithProperties, editor, property, validationResult, modelState);

View File

@@ -99,7 +99,7 @@ namespace Umbraco.Cms.Web.BackOffice.HealthChecks
return check.ExecuteAction(action);
}
private HealthCheck GetCheckById(Guid id)
private HealthCheck GetCheckById(Guid? id)
{
HealthCheck check = _checks
.Where(x => _disabledCheckIds.Contains(x.Id) == false)

View File

@@ -173,7 +173,7 @@ namespace Umbraco.Cms.Web.BackOffice.Security
// generate a session id and assign it
// create a session token - if we are configured and not in an upgrade state then use the db, otherwise just generate one
Guid session = _runtimeState.Level == RuntimeLevel.Run
? _userService.CreateLoginSession(backOfficeIdentity.GetId(), _ipResolver.GetCurrentRequestIpAddress())
? _userService.CreateLoginSession(backOfficeIdentity.GetId().Value, _ipResolver.GetCurrentRequestIpAddress())
: Guid.NewGuid();
// add our session claim

View File

@@ -137,7 +137,7 @@ namespace Umbraco.Cms.Web.BackOffice.Trees
node.AdditionalData.Add("variesByCulture", documentEntity.Variations.VariesByCulture());
node.AdditionalData.Add("contentType", documentEntity.ContentTypeAlias);
if (_publicAccessService.IsProtected(entity.Path))
if (_publicAccessService.IsProtected(entity.Path).Success)
node.SetProtectedStyle();
return node;

View File

@@ -130,7 +130,7 @@ namespace Umbraco.Cms.Web.Common.Middleware
try
{
// Verbose log start of every request
LogHttpRequest.TryGetCurrentHttpRequestId(out Guid httpRequestId, _requestCache);
LogHttpRequest.TryGetCurrentHttpRequestId(out Guid? httpRequestId, _requestCache);
_logger.LogTrace("Begin request [{HttpRequestId}]: {RequestUrl}", httpRequestId, pathAndQuery);
try
@@ -160,7 +160,7 @@ namespace Umbraco.Cms.Web.Common.Middleware
{
// Verbose log end of every request (in v8 we didn't log the end request of ALL requests, only the front-end which was
// strange since we always logged the beginning, so now we just log start/end of all requests)
LogHttpRequest.TryGetCurrentHttpRequestId(out Guid httpRequestId, _requestCache);
LogHttpRequest.TryGetCurrentHttpRequestId(out Guid? httpRequestId, _requestCache);
_logger.LogTrace("End Request [{HttpRequestId}]: {RequestUrl} ({RequestDuration}ms)", httpRequestId, pathAndQuery, DateTime.Now.Subtract(umbracoContextReference.UmbracoContext.ObjectCreated).TotalMilliseconds);
try

View File

@@ -38,8 +38,12 @@ namespace Umbraco.Cms.Web.Common.Security
//Check again
if (_currentUser == null)
{
Attempt<int> id = GetUserId();
_currentUser = id ? _userService.GetUserById(id.Result) : null;
Attempt<int?> id = GetUserId();
if (id.Success && id.Result is not null)
{
_currentUser = id.Success ? _userService.GetUserById(id.Result.Value) : null;
}
}
}
}
@@ -49,10 +53,10 @@ namespace Umbraco.Cms.Web.Common.Security
}
/// <inheritdoc />
public Attempt<int> GetUserId()
public Attempt<int?> GetUserId()
{
ClaimsIdentity identity = _httpContextAccessor.HttpContext?.GetCurrentIdentity();
return identity == null ? Attempt.Fail<int>() : Attempt.Succeed(identity.GetId());
return identity == null ? Attempt.Fail<int?>() : Attempt.Succeed(identity.GetId());
}
/// <inheritdoc />

View File

@@ -162,7 +162,7 @@ namespace Umbraco.Cms.Web.Common.Security
foreach (var path in paths)
{
//this is a cached call
result[path] = _publicAccessService.IsProtected(path);
result[path] = _publicAccessService.IsProtected(path).Success;
}
return Task.FromResult((IReadOnlyDictionary<string, bool>)result);
}

View File

@@ -63,7 +63,7 @@ namespace Umbraco.Cms.Web.Website.Routing
Attempt<PublicAccessEntry> publicAccessAttempt = _publicAccessService.IsProtected(path);
if (publicAccessAttempt)
if (publicAccessAttempt.Success)
{
_logger.LogDebug("EnsurePublishedContentAccess: Page is protected, check for access");