Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/202307 code smells 24 #1199

Merged
merged 10 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ private static (bool Exists, long ActualFreeMegabytes) GetSystemDriveInfo(string
return ( false, 0L );
}

var driveInfo = drivesList.FirstOrDefault(
drive => string.Equals(drive.Name, driveName, StringComparison.InvariantCultureIgnoreCase));
var driveInfo = Array.Find(drivesList,
drive => string.Equals(drive.Name, driveName,
StringComparison.InvariantCultureIgnoreCase));
return driveInfo?.AvailableFreeSpace != null ? (true, driveInfo.AvailableFreeSpace / 1024L / 1024L) : (false, 0L);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public Task<HealthCheckResult> CheckHealthAsync(
$"Not configured"));

return Task.FromResult(
resultsList.Any(p => p == FolderOrFileModel.FolderOrFileTypeList.Deleted) ?
resultsList.Exists(p => p == FolderOrFileModel.FolderOrFileTypeList.Deleted) ?
new HealthCheckResult(context.Registration.FailureStatus, $"Configured path is not present on system") :
HealthCheckResult.Healthy("Configured path is present"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public string TagName {
set
{
if ( string.IsNullOrWhiteSpace(value)) return;
if ( !value.StartsWith("v") ) Console.WriteLine($"{_tagName} Should start with v");
if ( !value.StartsWith('v') ) Console.WriteLine($"{_tagName} Should start with v");
_tagName = value;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,11 @@ internal static KeyValuePair<UpdateStatus, string> Parse(IEnumerable<ReleaseMode
{
var orderedReleaseModelList = releaseModelList.OrderByDescending(p => p.TagName);
var tagName = orderedReleaseModelList.FirstOrDefault(p => !p.Draft && !p.PreRelease)?.TagName;
if ( string.IsNullOrWhiteSpace(tagName) || !tagName.StartsWith("v") )
if ( string.IsNullOrWhiteSpace(tagName) ||
!tagName.StartsWith('v') )
{
return new KeyValuePair<UpdateStatus, string>(UpdateStatus.NoReleasesFound,string.Empty);
}

try
{
Expand Down
18 changes: 12 additions & 6 deletions starsky/starsky.feature.import/Services/Import.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public async Task<List<ImportIndexItem>> Preflight(List<string> fullFilePathsLis
var parentFolder = Directory.GetParent(itemSourceFullFilePath)
?.FullName;

if ( parentFolders.All(p => p.Item1 != parentFolder) )
if ( parentFolders.TrueForAll(p => p.Item1 != parentFolder) )
{
parentFolders.Add(new Tuple<string?, List<string>>(parentFolder, new List<string>{itemSourceFullFilePath}));
continue;
Expand All @@ -157,10 +157,16 @@ public async Task<List<ImportIndexItem>> Preflight(List<string> fullFilePathsLis
var fileStorageInfo = _filesystemStorage.Info(parentFolder.Item1!);
if ( fileStorageInfo.IsFolderOrFile !=
FolderOrFileModel.FolderOrFileTypeList.Folder ||
fileStorageInfo.IsFileSystemReadOnly != true ) continue;
fileStorageInfo.IsFileSystemReadOnly != true )
{
continue;
}

var items = parentFolder.Item2.Select(parentItem =>
Array.Find(importIndexItemsList.ToArray(),
p => p.SourceFullFilePath == parentItem)).Cast<ImportIndexItem>();

foreach ( var item in parentFolder.Item2.Select(parentItem => importIndexItemsList.FirstOrDefault(p =>
p.SourceFullFilePath == parentItem)).Where(item => item != null).Cast<ImportIndexItem>() )
foreach ( var item in items )
{
importIndexItemsList[importIndexItemsList.IndexOf(item)]
.Status = ImportStatus.ReadOnlyFileSystem;
Expand Down Expand Up @@ -229,7 +235,7 @@ internal List<ImportIndexItem> CheckForDuplicateNaming(List<ImportIndexItem> imp
var currentDirectoryContent =
directoriesContent[importIndexItem.FileIndexItem.ParentDirectory!];

if ( currentDirectoryContent.Any(p => p == updatedFilePath) )
if ( currentDirectoryContent.Contains(updatedFilePath) )
{
indexer++;
continue;
Expand Down Expand Up @@ -291,7 +297,7 @@ private List<KeyValuePair<string,bool>> AppendDirectoryFilePaths(List<string> fu
internal async Task<ImportIndexItem> PreflightPerFile(KeyValuePair<string,bool> inputFileFullPath,
ImportSettingsModel importSettings)
{
if ( _appSettings.ImportIgnore.Any(p => inputFileFullPath.Key.Contains(p)) )
if ( _appSettings.ImportIgnore.Exists(p => inputFileFullPath.Key.Contains(p)) )
{
ConsoleIfVerbose($"❌ skip due rules: {inputFileFullPath.Key} ");
return new ImportIndexItem{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ internal static void Update(IEnumerable<string> inputFilePaths, List<FileIndexIt
foreach (var subPath in inputFilePaths)
{
// when item is not in the database
if ( fileIndexResultsList.Any(p => p.FilePath == subPath) )
if ( fileIndexResultsList.Exists(p => p.FilePath == subPath) )
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,10 @@ public static List<FileIndexItem> SearchAndReplace(List<FileIndexItem> fileIndex

var propertiesA = new FileIndexItem().GetType().GetProperties(
BindingFlags.Public | BindingFlags.Instance);
var property = propertiesA.FirstOrDefault(p => string.Equals(
p.Name, fieldName, StringComparison.InvariantCultureIgnoreCase));

var property = Array.Find(propertiesA, p => string.Equals(
p.Name, fieldName,
StringComparison.InvariantCultureIgnoreCase));

if ( property?.PropertyType == typeof(string))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ internal List<KeyValuePair<string, string>> AddAppSettingsData( List<KeyValuePai
// ReSharper disable once LoopCanBeConvertedToQuery
foreach (var property in properties)
{
var someAttribute = Attribute.GetCustomAttributes(property).FirstOrDefault(x => x is PackageTelemetryAttribute);
var someAttribute = Array.Find(Attribute.GetCustomAttributes(property), x => x is PackageTelemetryAttribute);
if ( someAttribute == null )
{
continue;
Expand Down
13 changes: 9 additions & 4 deletions starsky/starsky.feature.search/ViewModels/SearchViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -503,9 +503,14 @@ public static SearchViewModel NarrowSearch(SearchViewModel model)

for ( var i = 0; i < model.SearchIn.Count; i++ )
{
var propertyStringName = FileIndexItem.FileIndexPropList().FirstOrDefault(p =>
string.Equals(p, model.SearchIn[i], StringComparison.InvariantCultureIgnoreCase));
if ( string.IsNullOrEmpty(propertyStringName) ) continue;
var propertyStringName = FileIndexItem.FileIndexPropList().Find( p =>
string.Equals(p, model.SearchIn[i],
StringComparison.InvariantCultureIgnoreCase));

if ( string.IsNullOrEmpty(propertyStringName) )
{
continue;
}

var property = new FileIndexItem().GetType().GetProperty(propertyStringName)!;

Expand All @@ -518,7 +523,7 @@ public static SearchViewModel NarrowSearch(SearchViewModel model)
}

// hide xmp files in default view
if ( model.SearchIn.All(p => !string.Equals(p, nameof(SearchInTypes.imageformat),
if ( model.SearchIn.TrueForAll(p => !string.Equals(p, nameof(SearchInTypes.imageformat),
StringComparison.InvariantCultureIgnoreCase)))
{
model.FileIndexItems = model.FileIndexItems!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ internal async Task<IEnumerable<ThumbnailItem>> WorkThumbnailGeneration(

foreach ( var item in chuckedItems )
{
var fileIndexItem = fileIndexItems.FirstOrDefault(p => p.FileHash == item.FileHash);
var fileIndexItem = fileIndexItems.Find(p => p.FileHash == item.FileHash);
if ( fileIndexItem?.FilePath == null ||
fileIndexItem.Status != FileIndexItem.ExifStatus.Ok )
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ internal List<FileIndexItem> AddFileHashIfNotExist(List<FileIndexItem> fileIndex
internal bool ShouldSkipExtraLarge(string publishProfileName)
{
var skipExtraLarge = _publishPreflight?.GetPublishProfileName(publishProfileName)?
.All(p => p.SourceMaxWidth <= 1999);
.TrueForAll(p => p.SourceMaxWidth <= 1999);
return skipExtraLarge == true;

}
Expand Down Expand Up @@ -156,9 +156,10 @@ private async Task<Dictionary<string,bool>> Render(List<FileIndexItem> fileIndex

// Order alphabetically
// Ignore Items with Errors
fileIndexItemsList = fileIndexItemsList.OrderBy(p => p.FileName)
fileIndexItemsList = fileIndexItemsList
.Where(p=> p.Status == FileIndexItem.ExifStatus.Ok ||
p.Status == FileIndexItem.ExifStatus.ReadOnly).ToList();
p.Status == FileIndexItem.ExifStatus.ReadOnly)
.OrderBy(p => p.FileName).ToList();

var copyResult = new Dictionary<string,bool>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ internal async Task AddUserToCache(User user)
if ( !IsCacheEnabled() ) return;
var allUsers = (await AllUsersAsync()).Users;
var index = allUsers.Find(p => p.Id == user.Id);
if ( allUsers.Any(p => p.Id == user.Id) && index != null )
if ( allUsers.Exists(p => p.Id == user.Id) && index != null )
{
var indexOf = allUsers.IndexOf(index);
allUsers[indexOf] = user;
Expand Down Expand Up @@ -211,7 +211,7 @@ private async Task RemoveUserFromCacheAsync(User user)
}

var users = (await AllUsersAsync()).Users;
return users.FirstOrDefault(p => p.Id == userTableId);
return users.Find(p => p.Id == userTableId);
}

/// <summary>
Expand Down Expand Up @@ -284,7 +284,7 @@ public async Task<SignUpResult> SignUpAsync(string name,
}

// Add a user role based on a user id
var roleToAdd = roles.FirstOrDefault(p => p.Code == GetRoleAddToUser(identifier,user));
var roleToAdd = roles.Find(p => p.Code == GetRoleAddToUser(identifier,user));
AddToRole(user, roleToAdd);

if (credentialType == null)
Expand Down Expand Up @@ -555,7 +555,7 @@ public async Task<ValidateResult> ValidateAsync(string credentialTypeCode,
return new ValidateResult(success: false, error: ValidateResultError.SecretNotValid);
}

var userData = (await AllUsersAsync()).Users.FirstOrDefault(p => p.Id == credential.UserId);
var userData = (await AllUsersAsync()).Users.Find(p => p.Id == credential.UserId);
if ( userData == null )
{
return new ValidateResult(success: false, error: ValidateResultError.UserNotFound);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,13 @@ public static List<string> Compare(FileIndexItem sourceIndexItem, FileIndexItem?
}

// Last Edited is not needed
if ( differenceList.Any(p => p == nameof(FileIndexItem.LastEdited).ToLowerInvariant()) )
if ( differenceList.Exists(p => p == nameof(FileIndexItem.LastEdited).ToLowerInvariant()) )
{
differenceList.Remove(nameof(FileIndexItem.LastEdited).ToLowerInvariant());
}

// Last Changed is a generated list
if ( differenceList.Any(p => p == nameof(FileIndexItem.LastChanged).ToLowerInvariant()) )
if ( differenceList.Exists(p => p == nameof(FileIndexItem.LastChanged).ToLowerInvariant()) )
{
differenceList.Remove(nameof(FileIndexItem.LastChanged).ToLowerInvariant());
}
Expand All @@ -134,7 +134,7 @@ public static FileIndexItem Set(FileIndexItem? sourceIndexItem, string fieldName

PropertyInfo[] propertiesA = new FileIndexItem().GetType().GetProperties(
BindingFlags.Public | BindingFlags.Instance);
var property = propertiesA.FirstOrDefault(p =>
var property = Array.Find(propertiesA,p =>
string.Equals(p.Name, fieldName, StringComparison.InvariantCultureIgnoreCase));

var fieldType = fieldContent.GetType();
Expand All @@ -158,7 +158,7 @@ public static FileIndexItem Set(FileIndexItem? sourceIndexItem, string fieldName
{
PropertyInfo[] propertiesA = new FileIndexItem().GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance);
return propertiesA.FirstOrDefault(p =>
return Array.Find(propertiesA,p =>
string.Equals(p.Name, fieldName, StringComparison.InvariantCultureIgnoreCase))?
.GetValue(sourceIndexItem, null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,10 @@ public DateTime ParseDateTimeFromFileName()
{
// Depends on 'AppSettingsProvider.Structure'
// depends on SourceFullFilePath
if(string.IsNullOrEmpty(SourceFullFilePath)) {return new DateTime();}
if ( string.IsNullOrEmpty(SourceFullFilePath) )
{
return new DateTime(0, DateTimeKind.Utc);
}

var fileName = Path.GetFileNameWithoutExtension(SourceFullFilePath);

Expand Down
3 changes: 1 addition & 2 deletions starsky/starsky.foundation.database/Query/Query.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ internal static string GetObjectByFilePathAsyncCacheName(string subPath)
_cache.TryGetValue(
GetObjectByFilePathAsyncCacheName(filePath), out var data) )
{
_logger.LogInformation("Get from cache " + GetObjectByFilePathAsyncCacheName(filePath));
if ( !(data is FileIndexItem fileIndexItem) ) return null;
fileIndexItem.Status = FileIndexItem.ExifStatus.OkAndSame;
return fileIndexItem;
Expand Down Expand Up @@ -478,7 +477,7 @@ public void CacheUpdateItem(List<FileIndexItem> updateStatusContent)
// make it a list to avoid enum errors
displayFileFolders = displayFileFolders.ToList();

var obj = displayFileFolders.FirstOrDefault(p => p.FilePath == item.FilePath);
var obj = displayFileFolders.Find(p => p.FilePath == item.FilePath);
if ( obj != null )
{
// remove add again
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async Task<List<FileIndexItem>> LocalQuery(ApplicationDbContext context)
fileHashesList.Contains(p.FileHash!)).ToListAsync();
foreach ( var fileHash in fileHashesList )
{
if ( result.FirstOrDefault(p => p.FileHash == fileHash) == null )
if ( result.Find(p => p.FileHash == fileHash) == null )
{
result.Add(new FileIndexItem(){FileHash = fileHash,
Status = FileIndexItem.ExifStatus.NotFoundNotInIndex});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public partial class Query
};
}

var currentFileIndexItem = fileIndexItemsList.FirstOrDefault(p => p.FileName == fileName);
var currentFileIndexItem = fileIndexItemsList.Find(p => p.FileName == fileName);

// Could be not found or not in directory cache
if ( currentFileIndexItem == null )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public ThumbnailQuery(ApplicationDbContext context, IServiceScopeFactory? scopeF

public Task<List<ThumbnailItem>?> AddThumbnailRangeAsync(List<ThumbnailResultDataTransferModel> thumbnailItems)
{
if ( thumbnailItems.Any(p => string.IsNullOrEmpty(p.FileHash) ) )
if ( thumbnailItems.Exists(p => string.IsNullOrEmpty(p.FileHash) ) )
{
throw new ArgumentNullException(nameof(thumbnailItems), "[AddThumbnailRangeAsync] FileHash is null or empty");
}
Expand Down Expand Up @@ -208,8 +208,8 @@ private static async Task<bool> RenameInternalAsync(ApplicationDbContext dbConte
var beforeOrNewItems = await dbContext.Thumbnails.Where(p =>
p.FileHash == beforeFileHash || p.FileHash == newFileHash).ToListAsync();

var beforeItem = beforeOrNewItems.FirstOrDefault(p => p.FileHash == beforeFileHash);
var newItem = beforeOrNewItems.FirstOrDefault(p => p.FileHash == newFileHash);
var beforeItem = beforeOrNewItems.Find(p => p.FileHash == beforeFileHash);
var newItem = beforeOrNewItems.Find(p => p.FileHash == newFileHash);

if ( beforeItem == null) return false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ private static List<Assembly> GetEntryAssemblyReferencedAssemblies(List<Assembly
// ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
foreach ( var assemblyFilter in assemblyFilters )
{
var isThere = assemblies.Any(p => p.FullName == assemblyName.FullName);
var isThere = assemblies.Exists(p => p.FullName == assemblyName.FullName);
if (IsWildcardMatch(assemblyName.Name!, assemblyFilter) && !isThere )
{
assemblies.Add(AppDomain.CurrentDomain.Load(assemblyName));
Expand All @@ -165,7 +165,7 @@ private static Assembly[] GetReferencedAssemblies(List<Assembly> assemblies, IEn
foreach ( var referencedAssembly in assembly.GetReferencedAssemblies() )
{
if ( IsWildcardMatch(referencedAssembly.Name!, assemblyFilter)
&& assemblies.All(p => p.FullName != referencedAssembly.FullName) )
&& assemblies.TrueForAll(p => p.FullName != referencedAssembly.FullName) )
{
assemblies.Add(Assembly.Load(referencedAssembly));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
Expand Down Expand Up @@ -28,7 +29,7 @@ public static List<string> Compare(AppSettings sourceIndexItem, object? updateOb
foreach ( var propertyB in propertiesB )
{
// only for when TransferObject is Nullable<bool> and AppSettings is bool
var propertyInfoFromA = propertiesA.FirstOrDefault(p => p.Name == propertyB.Name);
var propertyInfoFromA = Array.Find(propertiesA, p => p.Name == propertyB.Name);
if ( propertyInfoFromA == null ) continue;
if (propertyInfoFromA.PropertyType == typeof(bool?) && propertyB.PropertyType == typeof(bool?))
{
Expand Down Expand Up @@ -277,8 +278,7 @@ internal static void CompareInt(string propertyName, AppSettings sourceIndexItem
/// <returns></returns>
private static object? GetPropertyValue(object car, string propertyName)
{
return car.GetType().GetProperties()
.FirstOrDefault(pi => pi.Name == propertyName)?
return Array.Find(car.GetType().GetProperties(), pi => pi.Name == propertyName)?
.GetValue(car, null);
}

Expand Down
11 changes: 9 additions & 2 deletions starsky/starsky.foundation.platform/Helpers/DateAssembly.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@
// <SourceRevisionId>build$([System.DateTime]::UtcNow.ToString("yyyyMMddHHmmss"))</SourceRevisionId>
// </PropertyGroup>
var attribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if ( attribute?.InformationalVersion == null ) return new DateTime();
if ( attribute?.InformationalVersion == null )
{
return new DateTime(0, DateTimeKind.Utc);

Check warning on line 25 in starsky/starsky.foundation.platform/Helpers/DateAssembly.cs

View check run for this annotation

Codecov / codecov/patch

starsky/starsky.foundation.platform/Helpers/DateAssembly.cs#L25

Added line #L25 was not covered by tests
}

var value = attribute.InformationalVersion;
return ParseBuildTime(value);
}
Expand All @@ -29,7 +33,10 @@
{
const string buildVersionMetadataPrefix = "+build";
var index = value.IndexOf(buildVersionMetadataPrefix, StringComparison.Ordinal);
if ( index <= 0 ) return new DateTime();
if ( index <= 0 )
{
return new DateTime(0, DateTimeKind.Utc);
}
value = value.Substring(index + buildVersionMetadataPrefix.Length);
return DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out var result) ? result : new DateTime();
Expand Down
Loading
Loading