Clean up most of the analyzer info (#11050)

This turns a number of the code analyzers into warnings and fixes them. Most of the outstanding messages are fixed.

It wasn't particularly easy to break this up as the analyzers are pretty squidgy about reporting what is outstanding. Everything from this point should be much more focused.

We have significant weirdness with collection initialization syntax. It is ambiguous for most of our collection types and AddRange. Behavior varies between debug and release. Hopefully adding params of span overloads will address the ambiguity issue so that auto-fixes will actually create code that builds.
This commit is contained in:
Jeremy Kuhne 2024-03-14 10:46:43 -07:00 коммит произвёл GitHub
Родитель 4668f09903
Коммит 5dce90f12e
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
473 изменённых файлов: 4828 добавлений и 4712 удалений

Просмотреть файл

@ -70,14 +70,14 @@ dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case
dotnet_sort_system_directives_first = true
# Expression-level preferences
dotnet_style_object_initializer = true:suggestion
dotnet_style_object_initializer = true:warning
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_coalesce_expression = true:warning
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:warning
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_prefer_inferred_tuple_names = true:suggestion
@ -90,7 +90,7 @@ tab_width = 4
end_of_line = crlf
dotnet_style_allow_multiple_blank_lines_experimental = true:silent
dotnet_style_allow_statement_immediately_after_block_experimental = true:silent
dotnet_style_prefer_collection_expression = true:suggestion
dotnet_style_prefer_collection_expression = true:warning
# IDE0040: Add accessibility modifiers
dotnet_diagnostic.IDE0040.severity = error
@ -107,30 +107,69 @@ dotnet_diagnostic.SYSLIB1054.severity = none
# SYSLIB1096: Convert to 'GeneratedComInterface'
dotnet_diagnostic.SYSLIB1096.severity = none
# IDE1006: Naming Styles
dotnet_diagnostic.IDE1006.severity = error
# CA1310: Specify StringComparison for correctness
dotnet_diagnostic.CA1310.severity = error
# CA1510: Use ArgumentNullException throw helper
dotnet_diagnostic.CA1510.severity = error
# CA1725: Parameter names should match base declaration
dotnet_diagnostic.CA1725.severity = error
# DOC100: Place text in paragraphs
dotnet_diagnostic.DOC100.severity = error
# CA1859: Use concrete types when possible for improved performance
dotnet_diagnostic.CA1859.severity = error
# DOC100: Place text in paragraphs
dotnet_diagnostic.DOC100.severity = error
# IDE0002: Simplify Member Access
dotnet_diagnostic.IDE0002.severity = error
# IDE0003: Remove qualification
dotnet_diagnostic.IDE0003.severity = error
# IDE0079: Remove unnecessary suppression
dotnet_diagnostic.IDE0079.severity = error
# IDE0017: Simplify object initialization
dotnet_diagnostic.IDE0017.severity = warning
# IDE0019: Use pattern matching
dotnet_diagnostic.IDE0019.severity = warning
# IDE0038: Use pattern matching
dotnet_diagnostic.IDE0038.severity = warning
# IDE0044: Add readonly modifier
dotnet_diagnostic.IDE0044.severity = warning
# IDE0057: Use range operator
dotnet_diagnostic.IDE0057.severity = error
# IDE0063: Use simple 'using' statement
dotnet_diagnostic.IDE0063.severity = warning
# IDE0075: Simplify conditional expression
dotnet_diagnostic.IDE0075.severity = warning
# IDE0078: Use pattern matching
dotnet_diagnostic.IDE0078.severity = warning
# IDE0079: Remove unnecessary suppression
dotnet_diagnostic.IDE0079.severity = error
# IDE0180: Use tuple to swap values
dotnet_diagnostic.IDE0180.severity = warning
# IDE0251: Make member 'readonly'
dotnet_diagnostic.IDE0251.severity = warning
# IDE0270: Use coalesce expression
dotnet_diagnostic.IDE0270.severity = warning
# IDE0300: Simplify collection initialization
dotnet_diagnostic.IDE0300.severity = warning
# IDE1006: Naming Styles
dotnet_diagnostic.IDE1006.severity = error
# .NET diagnostic
dotnet_diagnostic.RS0041.severity = none
dotnet_diagnostic.IDE0005.severity = error
@ -169,8 +208,8 @@ csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_accessors = true:silent
# Pattern matching
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:warning
csharp_style_pattern_matching_over_as_with_null_check = true:warning
csharp_style_inlined_variable_declaration = true:suggestion
# Null checking preferences
@ -201,7 +240,7 @@ csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
csharp_using_directive_placement = outside_namespace:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_prefer_simple_using_statement = true:warning
csharp_prefer_braces = true:silent
csharp_style_namespace_declarations = file_scoped:silent
csharp_style_prefer_method_group_conversion = true:silent
@ -262,6 +301,9 @@ end_of_line = crlf
# CA1861: Avoid constant arrays as arguments - expected to be inline for test readability (4000 hits)
dotnet_diagnostic.CA1861.severity = silent
# This collides with TheoryData usage
dotnet_style_prefer_collection_expression = true:silent
# This should be fixed https://github.com/dotnet/winforms/issues/11041
# xUnit1042: The member referenced by the MemberData attribute returns untyped data rows
dotnet_diagnostic.xUnit1042.severity = none

Просмотреть файл

@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.InteropServices.Marshalling;
@ -15,10 +15,10 @@ internal static class HandleRefMarshaller
_handle = handle;
}
public IntPtr ToUnmanaged() => _handle.Handle;
public readonly IntPtr ToUnmanaged() => _handle.Handle;
public void OnInvoked() => GC.KeepAlive(_handle.Wrapper);
public readonly void OnInvoked() => GC.KeepAlive(_handle.Wrapper);
public void Free() { }
public readonly void Free() { }
}
}

Просмотреть файл

@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Copied from https://raw.githubusercontent.com/dotnet/runtime/main/src/libraries/Common/src/System/LocalAppContextSwitches.Common.cs
@ -18,14 +18,12 @@ internal static partial class LocalAppContextSwitches
// Returns value of given switch using provided cache.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool GetCachedSwitchValue(string switchName, ref int cachedSwitchValue)
internal static bool GetCachedSwitchValue(string switchName, ref int cachedSwitchValue) => cachedSwitchValue switch
{
// The cached switch value has 3 states: 0 - unknown, 1 - true, -1 - false
if (cachedSwitchValue < 0) return false;
if (cachedSwitchValue > 0) return true;
return GetCachedSwitchValueInternal(switchName, ref cachedSwitchValue);
}
< 0 => false,
> 0 => true,
_ => GetCachedSwitchValueInternal(switchName, ref cachedSwitchValue)
};
private static bool GetCachedSwitchValueInternal(string switchName, ref int cachedSwitchValue)
{

Просмотреть файл

@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Diagnostics.CodeAnalysis;
@ -11,7 +11,8 @@ public
#else
internal
#endif
sealed class AllowNullAttribute : Attribute { }
sealed class AllowNullAttribute : Attribute
{ }
/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
@ -20,7 +21,8 @@ public
#else
internal
#endif
sealed class DisallowNullAttribute : Attribute { }
sealed class DisallowNullAttribute : Attribute
{ }
/// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
@ -29,7 +31,8 @@ public
#else
internal
#endif
sealed class MaybeNullAttribute : Attribute { }
sealed class MaybeNullAttribute : Attribute
{ }
/// <summary>Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
@ -38,7 +41,8 @@ public
#else
internal
#endif
sealed class NotNullAttribute : Attribute { }
sealed class NotNullAttribute : Attribute
{ }
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
@ -104,7 +108,8 @@ public
#else
internal
#endif
sealed class DoesNotReturnAttribute : Attribute { }
sealed class DoesNotReturnAttribute : Attribute
{ }
/// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
@ -140,7 +145,7 @@ internal
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullAttribute(string member) => Members = new[] { member };
public MemberNotNullAttribute(string member) => Members = [member];
/// <summary>Initializes the attribute with the list of field and property members.</summary>
/// <param name="members">
@ -171,7 +176,7 @@ internal
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = new[] { member };
Members = [member];
}
/// <summary>Initializes the attribute with the specified return value condition and list of field and property members.</summary>

Просмотреть файл

@ -7,7 +7,8 @@ namespace System;
internal static partial class SR
{
private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out bool usingResourceKeys) ? usingResourceKeys : false;
private static readonly bool s_usingResourceKeys =
AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out bool usingResourceKeys) && usingResourceKeys;
// This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format.
// by default it returns the value of System.Resources.UseSystemResourceKeys AppContext switch or false if not specified.

Просмотреть файл

@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Copied from https://raw.githubusercontent.com/dotnet/runtime/main/src/libraries/Common/src/System/Text/ValueStringBuilder.cs
@ -31,7 +31,7 @@ internal ref partial struct ValueStringBuilder
public int Length
{
get => _pos;
readonly get => _pos;
set
{
Debug.Assert(value >= 0);
@ -40,7 +40,7 @@ internal ref partial struct ValueStringBuilder
}
}
public int Capacity => _chars.Length;
public readonly int Capacity => _chars.Length;
public void EnsureCapacity(int capacity)
{
@ -53,18 +53,15 @@ internal ref partial struct ValueStringBuilder
}
/// <summary>
/// Get a pinnable reference to the builder.
/// Does not ensure there is a null char after <see cref="Length"/>
/// This overload is pattern matched in the C# 7.3+ compiler so you can omit
/// the explicit method call, and write eg "fixed (char* c = builder)"
/// Get a pinnable reference to the builder.
/// Does not ensure there is a null char after <see cref="Length"/>
/// This overload is pattern matched in the C# 7.3+ compiler so you can omit
/// the explicit method call, and write eg "fixed (char* c = builder)"
/// </summary>
public ref char GetPinnableReference()
{
return ref MemoryMarshal.GetReference(_chars);
}
public readonly ref char GetPinnableReference() => ref MemoryMarshal.GetReference(_chars);
/// <summary>
/// Get a pinnable reference to the builder.
/// Get a pinnable reference to the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ref char GetPinnableReference(bool terminate)
@ -89,13 +86,13 @@ internal ref partial struct ValueStringBuilder
public override string ToString()
{
string s = _chars.Slice(0, _pos).ToString();
string s = _chars[.._pos].ToString();
Dispose();
return s;
}
/// <summary>Returns the underlying storage of the builder.</summary>
public Span<char> RawChars => _chars;
public readonly Span<char> RawChars => _chars;
/// <summary>
/// Returns a span around the contents of the builder.
@ -109,16 +106,16 @@ internal ref partial struct ValueStringBuilder
_chars[Length] = '\0';
}
return _chars.Slice(0, _pos);
return _chars[.._pos];
}
public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos);
public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start);
public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
public readonly ReadOnlySpan<char> AsSpan() => _chars[.._pos];
public readonly ReadOnlySpan<char> AsSpan(int start) => _chars[start.._pos];
public readonly ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
public bool TryCopyTo(Span<char> destination, out int charsWritten)
{
if (_chars.Slice(0, _pos).TryCopyTo(destination))
if (_chars[.._pos].TryCopyTo(destination))
{
charsWritten = _pos;
Dispose();
@ -140,7 +137,7 @@ internal ref partial struct ValueStringBuilder
}
int remaining = _pos - index;
_chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
_chars.Slice(index, count).Fill(value);
_pos += count;
}
@ -160,12 +157,8 @@ internal ref partial struct ValueStringBuilder
}
int remaining = _pos - index;
_chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
s
#if !NETCOREAPP
.AsSpan()
#endif
.CopyTo(_chars.Slice(index));
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
s.CopyTo(_chars[index..]);
_pos += count;
}
@ -212,11 +205,7 @@ internal ref partial struct ValueStringBuilder
Grow(s.Length);
}
s
#if !NETCOREAPP
.AsSpan()
#endif
.CopyTo(_chars.Slice(pos));
s.CopyTo(_chars[pos..]);
_pos += s.Length;
}
@ -261,7 +250,7 @@ internal ref partial struct ValueStringBuilder
Grow(value.Length);
}
value.CopyTo(_chars.Slice(_pos));
value.CopyTo(_chars[_pos..]);
_pos += value.Length;
}
@ -311,7 +300,7 @@ internal ref partial struct ValueStringBuilder
// This could also go negative if the actual required length wraps around.
char[] poolArray = ArrayPool<char>.Shared.Rent(newCapacity);
_chars.Slice(0, _pos).CopyTo(poolArray);
_chars[.._pos].CopyTo(poolArray);
char[]? toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = poolArray;

Просмотреть файл

@ -38,12 +38,10 @@ public readonly ref struct BinaryFormatterScope
#pragma warning disable SYSLIB0011 // Type or member is obsolete
BinaryFormatter formatter = new();
#pragma warning restore SYSLIB0011 // Type or member is obsolete
#pragma warning restore SYSLIB0011
try
{
#pragma warning disable SYSLIB0011 // Type or member is obsolete
formatter.Serialize(null!, null!);
#pragma warning restore SYSLIB0011
}
catch (NotSupportedException)
{

Просмотреть файл

@ -128,7 +128,7 @@ internal static class DebuggerAttributes
// Get the text of the DebuggerDisplayAttribute
string attrText = (string)cad.ConstructorArguments[0].Value;
string[] segments = attrText.Split(new[] { '{', '}' });
string[] segments = attrText.Split(['{', '}']);
if (segments.Length % 2 == 0)
{
@ -150,13 +150,12 @@ internal static class DebuggerAttributes
if (i + 1 < segments.Length)
{
string reference = segments[i + 1];
bool noQuotes = reference.EndsWith(",nq");
bool noQuotes = reference.EndsWith(",nq", StringComparison.Ordinal);
reference = reference.Replace(",nq", string.Empty);
// Evaluate the reference.
object member;
if (!TryEvaluateReference(obj, reference, out member))
if (!TryEvaluateReference(obj, reference, out object member))
{
throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} contains the expression \"{reference}\".");
}

Просмотреть файл

@ -74,10 +74,7 @@ public class TestAccessor<T> : ITestAccessor
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
binder: null,
types,
modifiers: null);
if (methodInfo is null)
throw new ArgumentException($"Could not find non public method {methodName}.");
modifiers: null) ?? throw new ArgumentException($"Could not find non public method {methodName}.");
return (TDelegate)methodInfo.CreateDelegate(type, methodInfo.IsStatic ? null : _instance);
}

Просмотреть файл

@ -34,8 +34,8 @@ public static class TestData
private static class FloatingPointData<T>
where T : struct, IBinaryFloatingPointIeee754<T>, IMinMaxValue<T>
{
public static ImmutableArray<T> Data { get; } = ImmutableArray.Create(new T[]
{
public static ImmutableArray<T> Data { get; } =
[
T.MinValue,
T.MaxValue,
T.One,
@ -46,7 +46,8 @@ public static class TestData
T.NegativeInfinity,
T.Epsilon,
T.Epsilon * T.NegativeOne
});
,
];
}
private static class IntegerData<T>
@ -54,13 +55,13 @@ public static class TestData
{
public static ImmutableArray<T> Data { get; }
= ImmutableArray.Create(T.MinValue == T.Zero
? new T[]
{
?
[
T.MinValue,
T.MaxValue,
T.One,
T.MaxValue / (T.One + T.One)
}
]
: new T[]
{
T.MinValue,
@ -75,12 +76,9 @@ public static class TestData
private static class PositiveIntegerData<T>
where T : struct, IBinaryInteger<T>, IMinMaxValue<T>
{
public static ImmutableArray<T> Data { get; } = ImmutableArray.Create(new T[]
{
T.Zero,
T.MaxValue,
T.One,
T.MaxValue / (T.One + T.One)
});
public static ImmutableArray<T> Data { get; } =
[
T.Zero, T.MaxValue, T.One, T.MaxValue / (T.One + T.One)
];
}
}

Просмотреть файл

@ -58,10 +58,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices
Public ReadOnly Property Info() As AssemblyInfo
Get
If _info Is Nothing Then
Dim Assembly As Reflection.Assembly = Reflection.Assembly.GetEntryAssembly()
If Assembly Is Nothing Then 'It can be nothing if we are an add-in or a dll on the web
Assembly = Reflection.Assembly.GetCallingAssembly()
End If
Dim Assembly As Reflection.Assembly = If(Reflection.Assembly.GetEntryAssembly(), Reflection.Assembly.GetCallingAssembly())
_info = New AssemblyInfo(Assembly)
End If
Return _info

Просмотреть файл

@ -4,7 +4,6 @@
Option Strict On
Option Explicit On
Imports System
Imports System.IO
Imports System.IO.Pipes
Imports System.Runtime.InteropServices

Просмотреть файл

@ -499,12 +499,14 @@ Namespace Microsoft.VisualBasic.ApplicationServices
' "My Project\Application.myapp\Application.Designer.vb for how those UI-set values get applied.)
' Once all this is done, we give the User another chance to change the value by code through
' the ApplyDefaults event.
' Overriding MinimumSplashScreenDisplayTime needs still to keep working!
Dim applicationDefaultsEventArgs = New ApplyApplicationDefaultsEventArgs(
MinimumSplashScreenDisplayTime,
HighDpiMode)
HighDpiMode) With
{
.MinimumSplashScreenDisplayTime = MinimumSplashScreenDisplayTime
}
' Overriding MinimumSplashScreenDisplayTime needs still to keep working!
applicationDefaultsEventArgs.MinimumSplashScreenDisplayTime = MinimumSplashScreenDisplayTime
RaiseEvent ApplyApplicationDefaults(Me, applicationDefaultsEventArgs)
If (applicationDefaultsEventArgs.Font IsNot Nothing) Then

Просмотреть файл

@ -153,7 +153,7 @@ Namespace Microsoft.VisualBasic
''' <param name="value"></param>
Private Shared Sub ValidateAudioPlayModeEnum(value As AudioPlayMode, paramName As String)
If value < AudioPlayMode.WaitToComplete OrElse value > AudioPlayMode.BackgroundLoop Then
Throw New ComponentModel.InvalidEnumArgumentException(paramName, DirectCast(value, Integer), GetType(AudioPlayMode))
Throw New ComponentModel.InvalidEnumArgumentException(paramName, value, GetType(AudioPlayMode))
End If
End Sub

Просмотреть файл

@ -732,10 +732,7 @@ Namespace Microsoft.VisualBasic.Logging
If Append Then
' Try to get the file's actual encoding. If we get it, that trumps
' the user specified value
fileEncoding = GetFileEncoding(fileName)
If fileEncoding Is Nothing Then
fileEncoding = Encoding
End If
fileEncoding = If(GetFileEncoding(fileName), Encoding)
End If
Dim baseStreamWriter As New StreamWriter(fileName, Append, fileEncoding)
@ -931,7 +928,7 @@ Namespace Microsoft.VisualBasic.Logging
''' <param name="value"></param>
Private Shared Sub ValidateLogFileLocationEnumValue(value As LogFileLocation, paramName As String)
If value < LogFileLocation.TempDirectory OrElse value > LogFileLocation.Custom Then
Throw New InvalidEnumArgumentException(paramName, DirectCast(value, Integer), GetType(LogFileLocation))
Throw New InvalidEnumArgumentException(paramName, value, GetType(LogFileLocation))
End If
End Sub
@ -941,7 +938,7 @@ Namespace Microsoft.VisualBasic.Logging
''' <param name="value"></param>
Private Shared Sub ValidateDiskSpaceExhaustedOptionEnumValue(value As DiskSpaceExhaustedOption, paramName As String)
If value < DiskSpaceExhaustedOption.ThrowException OrElse value > DiskSpaceExhaustedOption.DiscardMessages Then
Throw New InvalidEnumArgumentException(paramName, DirectCast(value, Integer), GetType(DiskSpaceExhaustedOption))
Throw New InvalidEnumArgumentException(paramName, value, GetType(DiskSpaceExhaustedOption))
End If
End Sub
@ -951,7 +948,7 @@ Namespace Microsoft.VisualBasic.Logging
''' <param name="value"></param>
Private Shared Sub ValidateLogFileCreationScheduleOptionEnumValue(value As LogFileCreationScheduleOption, paramName As String)
If value < LogFileCreationScheduleOption.None OrElse value > LogFileCreationScheduleOption.Weekly Then
Throw New InvalidEnumArgumentException(paramName, DirectCast(value, Integer), GetType(LogFileCreationScheduleOption))
Throw New InvalidEnumArgumentException(paramName, value, GetType(LogFileCreationScheduleOption))
End If
End Sub

Просмотреть файл

@ -69,7 +69,7 @@ public class ApplicationBaseTests
pairs.Add((key, (string)vars[key]));
}
return pairs.OrderBy(pair => pair.Item1).ToArray();
return [.. pairs.OrderBy(pair => pair.Item1)];
}
[Fact]

Просмотреть файл

@ -25,7 +25,7 @@ public class SingleInstanceTests
{
var received = _received;
Interlocked.CompareExchange(ref _received, null, received);
return received.ToImmutableArray();
return [.. received];
}
}

Просмотреть файл

@ -25,8 +25,10 @@ public class UnhandledExceptionEventArgsTests
[InlineData(false)]
public void ExitApplication_Set_GetReturnsExpected(bool value)
{
UnhandledExceptionEventArgs args = new(true, null);
args.ExitApplication = value;
UnhandledExceptionEventArgs args = new(true, null)
{
ExitApplication = value
};
Assert.Equal(value, args.ExitApplication);
}
}

Просмотреть файл

@ -26,7 +26,7 @@ public class WindowsFormsApplicationBaseTests
private static string GetUniqueIDFromAssembly(string guid, Version version)
{
CustomAttributeBuilder attributeBuilder = new(
typeof(GuidAttribute).GetConstructor(new[] { typeof(string) }), new[] { guid });
typeof(GuidAttribute).GetConstructor([typeof(string)]), new[] { guid });
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
new AssemblyName(Guid.NewGuid().ToString()) { Version = version },
AssemblyBuilderAccess.RunAndCollect,

Просмотреть файл

@ -28,9 +28,11 @@ public class FileLogTraceListenerTests : FileCleanupTestBase
public void Write()
{
TraceEventCache cache = new();
FileLogTraceListener listener = new();
listener.Location = LogFileLocation.Custom;
listener.CustomLocation = GetTestFilePath();
FileLogTraceListener listener = new()
{
Location = LogFileLocation.Custom,
CustomLocation = GetTestFilePath()
};
listener.Write("Write");
listener.WriteLine("WriteLine");

Просмотреть файл

@ -16,13 +16,13 @@ public class FileSystemProxyTests : FileCleanupTestBase
private static bool HasExpectedData(string FileNameWithPath, string ExpectedData)
{
string actualData = System.IO.File.ReadAllText(FileNameWithPath);
string actualData = File.ReadAllText(FileNameWithPath);
return ExpectedData == actualData;
}
private static void WriteFile(string FileName, string TestData)
{
System.IO.File.WriteAllText(FileName, TestData);
File.WriteAllText(FileName, TestData);
}
[Fact]
@ -37,7 +37,7 @@ public class FileSystemProxyTests : FileCleanupTestBase
{
var TestDirInfo = new DirectoryInfo(TestDirectory);
string Root = TestDirInfo.Root.Name;
Assert.Equal(_fileSystem.CombinePath(Root, "Test2"), System.IO.Path.Combine(Root, "Test2"));
Assert.Equal(_fileSystem.CombinePath(Root, "Test2"), Path.Combine(Root, "Test2"));
}
[Fact]
@ -45,30 +45,30 @@ public class FileSystemProxyTests : FileCleanupTestBase
{
Assert.Equal(_fileSystem.CombinePath(TestDirectory, null), TestDirectory);
Assert.Equal(_fileSystem.CombinePath(TestDirectory, ""), TestDirectory);
Assert.Equal(_fileSystem.CombinePath(TestDirectory, "Test"), System.IO.Path.Combine(TestDirectory, "Test"));
Assert.Equal(_fileSystem.CombinePath(TestDirectory, "Test"), Path.Combine(TestDirectory, "Test"));
}
[Fact]
public void CopyDirectory_SourceDirectoryName_DestinationDirectoryName()
{
string FullPathToSourceDirectory = System.IO.Path.Combine(TestDirectory, "SourceDirectory");
System.IO.Directory.CreateDirectory(FullPathToSourceDirectory);
string FullPathToSourceDirectory = Path.Combine(TestDirectory, "SourceDirectory");
Directory.CreateDirectory(FullPathToSourceDirectory);
for (int i = 0; i < 6; i++)
{
CreateTestFile(SourceData, PathFromBase: "SourceDirectory", TestFileName: $"NewFile{i}");
}
string FullPathToTargetDirectory = System.IO.Path.Combine(TestDirectory, "TargetDirectory");
string FullPathToTargetDirectory = Path.Combine(TestDirectory, "TargetDirectory");
_fileSystem.CopyDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory);
Assert.Equal(System.IO.Directory.GetFiles(FullPathToSourceDirectory).Length, System.IO.Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in System.IO.Directory.GetFiles(FullPathToTargetDirectory))
Assert.Equal(Directory.GetFiles(FullPathToSourceDirectory).Length, Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in Directory.GetFiles(FullPathToTargetDirectory))
{
// Ensure copy transferred written data
Assert.True(HasExpectedData(CurrentFile, SourceData));
}
System.IO.Directory.Delete(FullPathToTargetDirectory, recursive: true);
System.IO.Directory.CreateDirectory(FullPathToTargetDirectory);
Directory.Delete(FullPathToTargetDirectory, recursive: true);
Directory.CreateDirectory(FullPathToTargetDirectory);
CreateTestFile(TestData: SourceData, PathFromBase: "TargetDirectory", TestFileName: $"NewFile0");
Assert.Throws<IOException>(() => _fileSystem.CopyDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory));
}
@ -76,48 +76,48 @@ public class FileSystemProxyTests : FileCleanupTestBase
[Fact]
public void CopyDirectory_SourceDirectoryName_DestinationDirectoryName_OverwriteFalse()
{
string FullPathToSourceDirectory = System.IO.Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = System.IO.Path.Combine(TestDirectory, "TargetDirectory");
System.IO.Directory.CreateDirectory(FullPathToSourceDirectory);
string FullPathToSourceDirectory = Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = Path.Combine(TestDirectory, "TargetDirectory");
Directory.CreateDirectory(FullPathToSourceDirectory);
for (int i = 0; i < 6; i++)
{
CreateTestFile(SourceData, PathFromBase: "SourceDirectory", TestFileName: $"NewFile{i}");
}
_fileSystem.CopyDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory, overwrite: false);
Assert.Equal(System.IO.Directory.GetFiles(FullPathToSourceDirectory).Length, System.IO.Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in System.IO.Directory.GetFiles(FullPathToTargetDirectory))
Assert.Equal(Directory.GetFiles(FullPathToSourceDirectory).Length, Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in Directory.GetFiles(FullPathToTargetDirectory))
{
// Ensure copy transferred written data
Assert.True(HasExpectedData(CurrentFile, SourceData));
}
System.IO.Directory.Delete(FullPathToTargetDirectory, recursive: true);
System.IO.Directory.CreateDirectory(FullPathToTargetDirectory);
Directory.Delete(FullPathToTargetDirectory, recursive: true);
Directory.CreateDirectory(FullPathToTargetDirectory);
CreateTestFile(DestData, PathFromBase: "TargetDirectory", TestFileName: $"NewFile0");
Assert.Throws<IOException>(() => _fileSystem.CopyDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory, overwrite: false));
Assert.Equal(System.IO.Directory.GetFiles(FullPathToTargetDirectory).Length, System.IO.Directory.GetFiles(FullPathToSourceDirectory).Length);
foreach (string CurrentFile in System.IO.Directory.GetFiles(FullPathToTargetDirectory))
Assert.Equal(Directory.GetFiles(FullPathToTargetDirectory).Length, Directory.GetFiles(FullPathToSourceDirectory).Length);
foreach (string CurrentFile in Directory.GetFiles(FullPathToTargetDirectory))
{
Assert.True(HasExpectedData(CurrentFile, CurrentFile.EndsWith("0") ? DestData : SourceData));
Assert.True(HasExpectedData(CurrentFile, CurrentFile.EndsWith('0') ? DestData : SourceData));
}
}
[Fact]
public void CopyDirectory_SourceDirectoryName_DestinationDirectoryName_OverwriteTrue()
{
string FullPathToSourceDirectory = System.IO.Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = System.IO.Path.Combine(TestDirectory, "TargetDirectory");
System.IO.Directory.CreateDirectory(FullPathToSourceDirectory);
System.IO.Directory.CreateDirectory(FullPathToTargetDirectory);
string FullPathToSourceDirectory = Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = Path.Combine(TestDirectory, "TargetDirectory");
Directory.CreateDirectory(FullPathToSourceDirectory);
Directory.CreateDirectory(FullPathToTargetDirectory);
for (int i = 0; i < 6; i++)
{
CreateTestFile(SourceData, PathFromBase: "SourceDirectory", TestFileName: $"NewFile{i}");
}
_fileSystem.CopyDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory, overwrite: true);
Assert.Equal(System.IO.Directory.GetFiles(FullPathToSourceDirectory).Length, System.IO.Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in System.IO.Directory.GetFiles(FullPathToTargetDirectory))
Assert.Equal(Directory.GetFiles(FullPathToSourceDirectory).Length, Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in Directory.GetFiles(FullPathToTargetDirectory))
{
// Ensure copy transferred written data
Assert.True(HasExpectedData(CurrentFile, SourceData));
@ -179,23 +179,23 @@ public class FileSystemProxyTests : FileCleanupTestBase
[Fact]
public void CreateDirectory_Directory()
{
string FullPathToNewDirectory = System.IO.Path.Combine(TestDirectory, "NewDirectory");
Assert.False(System.IO.Directory.Exists(FullPathToNewDirectory));
string FullPathToNewDirectory = Path.Combine(TestDirectory, "NewDirectory");
Assert.False(Directory.Exists(FullPathToNewDirectory));
_fileSystem.CreateDirectory(FullPathToNewDirectory);
Assert.True(System.IO.Directory.Exists(FullPathToNewDirectory));
Assert.True(Directory.Exists(FullPathToNewDirectory));
}
[Fact]
public void CurrentDirectoryGet()
{
string CurrentDirectory = System.IO.Directory.GetCurrentDirectory();
string CurrentDirectory = Directory.GetCurrentDirectory();
Assert.Equal(_fileSystem.CurrentDirectory, CurrentDirectory);
}
[Fact]
public void CurrentDirectorySet()
{
string SavedCurrentDirectory = System.IO.Directory.GetCurrentDirectory();
string SavedCurrentDirectory = Directory.GetCurrentDirectory();
_fileSystem.CurrentDirectory = TestDirectory;
Assert.Equal(TestDirectory, _fileSystem.CurrentDirectory);
_fileSystem.CurrentDirectory = SavedCurrentDirectory;
@ -205,27 +205,27 @@ public class FileSystemProxyTests : FileCleanupTestBase
[Fact]
public void DeleteDirectory_Directory_DeleteAllContents()
{
string FullPathToNewDirectory = System.IO.Path.Combine(TestDirectory, "NewDirectory");
System.IO.Directory.CreateDirectory(FullPathToNewDirectory);
Assert.True(System.IO.Directory.Exists(FullPathToNewDirectory));
string FullPathToNewDirectory = Path.Combine(TestDirectory, "NewDirectory");
Directory.CreateDirectory(FullPathToNewDirectory);
Assert.True(Directory.Exists(FullPathToNewDirectory));
string testFileSource = CreateTestFile(SourceData, PathFromBase: "NewDirectory", TestFileName: "TestFile");
Assert.True(System.IO.File.Exists(testFileSource));
Assert.True(File.Exists(testFileSource));
_fileSystem.DeleteDirectory(FullPathToNewDirectory, DeleteDirectoryOption.DeleteAllContents);
Assert.False(System.IO.Directory.Exists(FullPathToNewDirectory));
Assert.False(Directory.Exists(FullPathToNewDirectory));
}
[Fact]
public void DeleteDirectory_Directory_ThrowIfDirectoryNonEmpty()
{
string FullPathToNewDirectory = System.IO.Path.Combine(TestDirectory, "NewDirectory");
string FullPathToNewDirectory = Path.Combine(TestDirectory, "NewDirectory");
_fileSystem.CreateDirectory(FullPathToNewDirectory);
Assert.True(System.IO.Directory.Exists(FullPathToNewDirectory));
Assert.True(Directory.Exists(FullPathToNewDirectory));
string testFileSource = CreateTestFile(SourceData, PathFromBase: "NewDirectory", TestFileName: "TestFile");
Assert.True(System.IO.File.Exists(testFileSource));
Assert.True(File.Exists(testFileSource));
Assert.Throws<IOException>(() => _fileSystem.DeleteDirectory(FullPathToNewDirectory, DeleteDirectoryOption.ThrowIfDirectoryNonEmpty));
Assert.True(System.IO.Directory.Exists(FullPathToNewDirectory));
Assert.True(System.IO.File.Exists(testFileSource));
Assert.True(Directory.Exists(FullPathToNewDirectory));
Assert.True(File.Exists(testFileSource));
}
[Fact]
@ -233,16 +233,16 @@ public class FileSystemProxyTests : FileCleanupTestBase
{
string testFileSource = CreateTestFile(SourceData, TestFileName: GetTestFileName());
Assert.True(System.IO.File.Exists(testFileSource));
Assert.True(File.Exists(testFileSource));
_fileSystem.DeleteFile(testFileSource);
Assert.False(System.IO.File.Exists(testFileSource));
Assert.False(File.Exists(testFileSource));
}
[Fact]
public void DirectoryExists_Directory()
{
Assert.True(_fileSystem.DirectoryExists(TestDirectory));
Assert.False(_fileSystem.DirectoryExists(System.IO.Path.Combine(TestDirectory, "NewDirectory")));
Assert.False(_fileSystem.DirectoryExists(Path.Combine(TestDirectory, "NewDirectory")));
}
// Not tested:
@ -254,7 +254,7 @@ public class FileSystemProxyTests : FileCleanupTestBase
string testFileSource = CreateTestFile(SourceData, TestFileName: GetTestFileName());
Assert.True(_fileSystem.FileExists(testFileSource));
_fileSystem.FileExists(testFileSource);
System.IO.File.Delete(testFileSource);
File.Delete(testFileSource);
Assert.False(_fileSystem.FileExists(testFileSource));
}
@ -269,17 +269,17 @@ public class FileSystemProxyTests : FileCleanupTestBase
Assert.Empty(DirectoryList);
for (int i = 0; i < 6; i++)
{
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"GetDirectories_DirectoryNewSubDirectory{i}"));
Directory.CreateDirectory(Path.Combine(TestDirectory, $"GetDirectories_DirectoryNewSubDirectory{i}"));
}
DirectoryList = _fileSystem.GetDirectories(TestDirectory);
Assert.Equal(6, DirectoryList.Count);
for (int i = 0; i < 6; i++)
{
Assert.Contains(System.IO.Path.Combine(TestDirectory, $"GetDirectories_DirectoryNewSubDirectory{i}"), DirectoryList);
Assert.Contains(Path.Combine(TestDirectory, $"GetDirectories_DirectoryNewSubDirectory{i}"), DirectoryList);
}
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"GetDirectories_DirectoryNewSubDirectory0", $"NewSubSubDirectory"));
Directory.CreateDirectory(Path.Combine(TestDirectory, $"GetDirectories_DirectoryNewSubDirectory0", $"NewSubSubDirectory"));
DirectoryList = _fileSystem.GetDirectories(TestDirectory);
Assert.Equal(6, DirectoryList.Count);
}
@ -291,17 +291,17 @@ public class FileSystemProxyTests : FileCleanupTestBase
Assert.Empty(DirectoryList);
for (int i = 0; i < 6; i++)
{
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"GetDirectories_Directory_SearchOptionNewSubDirectory{i}"));
Directory.CreateDirectory(Path.Combine(TestDirectory, $"GetDirectories_Directory_SearchOptionNewSubDirectory{i}"));
}
DirectoryList = _fileSystem.GetDirectories(TestDirectory, SearchOption.SearchTopLevelOnly);
Assert.Equal(6, DirectoryList.Count);
for (int i = 0; i < 6; i++)
{
Assert.Contains(System.IO.Path.Combine(TestDirectory, $"GetDirectories_Directory_SearchOptionNewSubDirectory{i}"), DirectoryList);
Assert.Contains(Path.Combine(TestDirectory, $"GetDirectories_Directory_SearchOptionNewSubDirectory{i}"), DirectoryList);
}
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"GetDirectories_Directory_SearchOptionNewSubDirectory0", $"NewSubSubDirectory"));
Directory.CreateDirectory(Path.Combine(TestDirectory, $"GetDirectories_Directory_SearchOptionNewSubDirectory0", $"NewSubSubDirectory"));
DirectoryList = _fileSystem.GetDirectories(TestDirectory, SearchOption.SearchTopLevelOnly);
Assert.Equal(6, DirectoryList.Count);
DirectoryList = _fileSystem.GetDirectories(TestDirectory, SearchOption.SearchAllSubDirectories);
@ -316,18 +316,18 @@ public class FileSystemProxyTests : FileCleanupTestBase
List<string> CreatedDirectories = [];
for (int i = 0; i < 6; i++)
{
CreatedDirectories.Add(System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"NewSubDirectory00{i}")).Name);
CreatedDirectories.Add(Directory.CreateDirectory(Path.Combine(TestDirectory, $"NewSubDirectory00{i}")).Name);
}
DirectoryList = _fileSystem.GetDirectories(TestDirectory, SearchOption.SearchTopLevelOnly, "*000", "*001");
Assert.Equal(2, DirectoryList.Count);
for (int i = 0; i < 2; i++)
{
string DirectoryName = System.IO.Path.Combine(TestDirectory, $"NewSubDirectory00{i}");
string DirectoryName = Path.Combine(TestDirectory, $"NewSubDirectory00{i}");
Assert.Contains(DirectoryName, DirectoryList);
}
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"NewSubDirectory000", $"NewSubSubDirectory000"));
Directory.CreateDirectory(Path.Combine(TestDirectory, $"NewSubDirectory000", $"NewSubSubDirectory000"));
DirectoryList = _fileSystem.GetDirectories(TestDirectory, SearchOption.SearchTopLevelOnly, "*000");
Assert.Single(DirectoryList);
DirectoryList = _fileSystem.GetDirectories(TestDirectory, SearchOption.SearchAllSubDirectories, "*000");
@ -339,10 +339,10 @@ public class FileSystemProxyTests : FileCleanupTestBase
{
for (int i = 0; i < 6; i++)
{
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"NewSubDirectory{i}"));
Directory.CreateDirectory(Path.Combine(TestDirectory, $"NewSubDirectory{i}"));
}
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, $"NewSubDirectory0", $"NewSubSubDirectory"));
Directory.CreateDirectory(Path.Combine(TestDirectory, $"NewSubDirectory0", $"NewSubSubDirectory"));
var info = _fileSystem.GetDirectoryInfo(TestDirectory);
var infoFromIO = new DirectoryInfo(TestDirectory);
Assert.Equal(info.CreationTime, infoFromIO.CreationTime);
@ -357,7 +357,7 @@ public class FileSystemProxyTests : FileCleanupTestBase
[Fact]
public void GetDriveInfo_Drive()
{
var Drives = System.IO.DriveInfo.GetDrives();
var Drives = DriveInfo.GetDrives();
Assert.True(Drives.Length > 0);
Assert.Equal(_fileSystem.GetDriveInfo(Drives[0].Name).Name, new DriveInfo(Drives[0].Name).Name);
}
@ -400,10 +400,10 @@ public class FileSystemProxyTests : FileCleanupTestBase
Assert.Equal(6, FileList.Count);
for (int i = 0; i < 6; i++)
{
Assert.Contains(System.IO.Path.Combine(TestDirectory, $"NewFile{i}"), FileList);
Assert.Contains(Path.Combine(TestDirectory, $"NewFile{i}"), FileList);
}
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, "GetFiles_DirectoryNewSubDirectory"));
Directory.CreateDirectory(Path.Combine(TestDirectory, "GetFiles_DirectoryNewSubDirectory"));
CreateTestFile(SourceData, PathFromBase: "GetFiles_DirectoryNewSubDirectory", TestFileName: "NewFile");
FileList = _fileSystem.GetFiles(TestDirectory);
Assert.Equal(6, FileList.Count);
@ -412,8 +412,8 @@ public class FileSystemProxyTests : FileCleanupTestBase
[Fact]
public void GetFiles_Directory_SearchOption()
{
string NewSubDirectoryPath = System.IO.Path.Combine(TestDirectory, "GetFiles_Directory_SearchOptionNewSubDirectory");
System.IO.Directory.CreateDirectory(NewSubDirectoryPath);
string NewSubDirectoryPath = Path.Combine(TestDirectory, "GetFiles_Directory_SearchOptionNewSubDirectory");
Directory.CreateDirectory(NewSubDirectoryPath);
CreateTestFile(SourceData, PathFromBase: "GetFiles_Directory_SearchOptionNewSubDirectory", TestFileName: "NewFile");
var FileList = _fileSystem.GetFiles(TestDirectory);
Assert.Empty(FileList);
@ -427,14 +427,14 @@ public class FileSystemProxyTests : FileCleanupTestBase
Assert.Equal(6, FileList.Count);
for (int i = 0; i < 6; i++)
{
Assert.Contains(System.IO.Path.Combine(TestDirectory, $"NewFile{i}"), FileList);
Assert.Contains(Path.Combine(TestDirectory, $"NewFile{i}"), FileList);
}
FileList = _fileSystem.GetFiles(TestDirectory, SearchOption.SearchAllSubDirectories);
Assert.Equal(8, FileList.Count);
for (int i = 0; i < 7; i++)
{
Assert.True(System.IO.File.Exists(FileList[i]));
Assert.True(File.Exists(FileList[i]));
}
}
@ -456,8 +456,8 @@ public class FileSystemProxyTests : FileCleanupTestBase
Assert.Contains(FileList[i], TestFileList);
}
string NewSubDirectoryPath = System.IO.Path.Combine(TestDirectory, "GetFiles_Directory_SearchOption_WildcardsNewSubDirectory");
System.IO.Directory.CreateDirectory(NewSubDirectoryPath);
string NewSubDirectoryPath = Path.Combine(TestDirectory, "GetFiles_Directory_SearchOption_WildcardsNewSubDirectory");
Directory.CreateDirectory(NewSubDirectoryPath);
TestFileList.Add(CreateTestFile(SourceData, PathFromBase: "GetFiles_Directory_SearchOption_WildcardsNewSubDirectory", TestFileName: "NewFile.cs"));
FileList = _fileSystem.GetFiles(TestDirectory, SearchOption.SearchAllSubDirectories, "*.cs");
Assert.Contains(TestFileList[^1], FileList);
@ -467,46 +467,46 @@ public class FileSystemProxyTests : FileCleanupTestBase
[Fact]
public void GetName_Path()
{
Assert.Equal(_fileSystem.GetName(TestDirectory), System.IO.Path.GetFileName(TestDirectory));
Assert.Equal(_fileSystem.GetName(TestDirectory), Path.GetFileName(TestDirectory));
}
[Fact]
public void GetParentPath_Path()
{
Assert.Equal(_fileSystem.GetParentPath(TestDirectory), System.IO.Path.GetDirectoryName(TestDirectory));
Assert.Equal(_fileSystem.GetParentPath(TestDirectory), Path.GetDirectoryName(TestDirectory));
}
[Fact]
public void GetTempFileName()
{
string TempFile = _fileSystem.GetTempFileName();
Assert.True(System.IO.File.Exists(TempFile));
Assert.True(File.Exists(TempFile));
Assert.Equal(0, (new FileInfo(TempFile)).Length);
System.IO.File.Delete(TempFile);
File.Delete(TempFile);
}
[Fact]
public void MoveDirectory_SourceDirectoryName_DestinationDirectoryName()
{
string FullPathToSourceDirectory = System.IO.Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = System.IO.Path.Combine(TestDirectory, "TargetDirectory");
System.IO.Directory.CreateDirectory(FullPathToSourceDirectory);
string FullPathToSourceDirectory = Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = Path.Combine(TestDirectory, "TargetDirectory");
Directory.CreateDirectory(FullPathToSourceDirectory);
for (int i = 0; i < 6; i++)
{
CreateTestFile(SourceData, PathFromBase: "SourceDirectory", TestFileName: $"NewFile{i}");
}
_fileSystem.MoveDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory);
Assert.Equal(6, System.IO.Directory.GetFiles(FullPathToTargetDirectory).Length);
Assert.False(System.IO.Directory.Exists(FullPathToSourceDirectory));
foreach (string CurrentFile in System.IO.Directory.GetFiles(FullPathToTargetDirectory))
Assert.Equal(6, Directory.GetFiles(FullPathToTargetDirectory).Length);
Assert.False(Directory.Exists(FullPathToSourceDirectory));
foreach (string CurrentFile in Directory.GetFiles(FullPathToTargetDirectory))
{
// Ensure move transferred written data
Assert.True(HasExpectedData(CurrentFile, SourceData));
}
System.IO.Directory.Move(FullPathToTargetDirectory, FullPathToSourceDirectory);
System.IO.Directory.CreateDirectory(FullPathToTargetDirectory);
Directory.Move(FullPathToTargetDirectory, FullPathToSourceDirectory);
Directory.CreateDirectory(FullPathToTargetDirectory);
CreateTestFile(SourceData, PathFromBase: "TargetDirectory", TestFileName: "NewFile0");
Assert.Throws<IOException>(() => _fileSystem.MoveDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory));
}
@ -514,57 +514,57 @@ public class FileSystemProxyTests : FileCleanupTestBase
[Fact]
public void MoveDirectory_SourceDirectoryName_DestinationDirectoryName_OverwriteFalse()
{
string FullPathToSourceDirectory = System.IO.Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = System.IO.Path.Combine(TestDirectory, "TargetDirectory");
System.IO.Directory.CreateDirectory(FullPathToSourceDirectory);
string FullPathToSourceDirectory = Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = Path.Combine(TestDirectory, "TargetDirectory");
Directory.CreateDirectory(FullPathToSourceDirectory);
for (int i = 0; i < 6; i++)
{
CreateTestFile(SourceData, PathFromBase: "SourceDirectory", TestFileName: $"NewFile{i}");
}
_fileSystem.MoveDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory, overwrite: false);
Assert.Equal(6, System.IO.Directory.GetFiles(FullPathToTargetDirectory).Length);
Assert.False(System.IO.Directory.Exists(FullPathToSourceDirectory));
foreach (string CurrentFile in System.IO.Directory.GetFiles(FullPathToTargetDirectory))
Assert.Equal(6, Directory.GetFiles(FullPathToTargetDirectory).Length);
Assert.False(Directory.Exists(FullPathToSourceDirectory));
foreach (string CurrentFile in Directory.GetFiles(FullPathToTargetDirectory))
{
// Ensure move transferred written data
Assert.True(HasExpectedData(CurrentFile, SourceData));
}
System.IO.Directory.Move(FullPathToTargetDirectory, FullPathToSourceDirectory);
System.IO.Directory.CreateDirectory(FullPathToTargetDirectory);
Directory.Move(FullPathToTargetDirectory, FullPathToSourceDirectory);
Directory.CreateDirectory(FullPathToTargetDirectory);
string NewFile0WithPath = CreateTestFile(DestData, PathFromBase: "TargetDirectory", TestFileName: "NewFile0");
Assert.Throws<IOException>(() => _fileSystem.MoveDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory, overwrite: false));
string[] RemainingSourceFilesWithPath = System.IO.Directory.GetFiles(FullPathToSourceDirectory);
string[] RemainingSourceFilesWithPath = Directory.GetFiles(FullPathToSourceDirectory);
// We couldn't move one file
Assert.Single(RemainingSourceFilesWithPath);
// Ensure the file left has correct data
Assert.True(HasExpectedData(RemainingSourceFilesWithPath[0], SourceData));
string[] DestinationFilesWithPath = System.IO.Directory.GetFiles(FullPathToTargetDirectory);
string[] DestinationFilesWithPath = Directory.GetFiles(FullPathToTargetDirectory);
Assert.Equal(6, DestinationFilesWithPath.Length);
foreach (string CurrentFile in DestinationFilesWithPath)
{
Assert.True(HasExpectedData(CurrentFile, CurrentFile.EndsWith("0") ? DestData : SourceData));
Assert.True(HasExpectedData(CurrentFile, CurrentFile.EndsWith('0') ? DestData : SourceData));
}
}
[Fact]
public void MoveDirectory_SourceDirectoryName_DestinationDirectoryName_OverwriteTrue()
{
string FullPathToSourceDirectory = System.IO.Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = System.IO.Path.Combine(TestDirectory, "TargetDirectory");
System.IO.Directory.CreateDirectory(FullPathToSourceDirectory);
System.IO.Directory.CreateDirectory(FullPathToTargetDirectory);
string FullPathToSourceDirectory = Path.Combine(TestDirectory, "SourceDirectory");
string FullPathToTargetDirectory = Path.Combine(TestDirectory, "TargetDirectory");
Directory.CreateDirectory(FullPathToSourceDirectory);
Directory.CreateDirectory(FullPathToTargetDirectory);
for (int i = 0; i < 6; i++)
{
CreateTestFile(SourceData, PathFromBase: "SourceDirectory", TestFileName: $"NewFile{i}");
}
_fileSystem.MoveDirectory(FullPathToSourceDirectory, FullPathToTargetDirectory, overwrite: true);
Assert.False(System.IO.Directory.Exists(FullPathToSourceDirectory));
Assert.Equal(6, System.IO.Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in System.IO.Directory.GetFiles(FullPathToTargetDirectory))
Assert.False(Directory.Exists(FullPathToSourceDirectory));
Assert.Equal(6, Directory.GetFiles(FullPathToTargetDirectory).Length);
foreach (string CurrentFile in Directory.GetFiles(FullPathToTargetDirectory))
{
// Ensure copy transferred written data
Assert.True(HasExpectedData(CurrentFile, SourceData));
@ -575,10 +575,10 @@ public class FileSystemProxyTests : FileCleanupTestBase
public void MoveFile_SourceFileName_DestinationFileName()
{
string SourceFileNameWithPath = CreateTestFile(SourceData, TestFileName: GetTestFileName());
string DestinationFileNameWithPath = System.IO.Path.Combine(TestDirectory, "NewName");
string DestinationFileNameWithPath = Path.Combine(TestDirectory, "NewName");
_fileSystem.MoveFile(SourceFileNameWithPath, DestinationFileNameWithPath);
Assert.False(System.IO.File.Exists(SourceFileNameWithPath));
Assert.True(System.IO.File.Exists(DestinationFileNameWithPath));
Assert.False(File.Exists(SourceFileNameWithPath));
Assert.True(File.Exists(DestinationFileNameWithPath));
Assert.True(HasExpectedData(DestinationFileNameWithPath, SourceData));
SourceFileNameWithPath = DestinationFileNameWithPath;
@ -586,39 +586,39 @@ public class FileSystemProxyTests : FileCleanupTestBase
Assert.Throws<IOException>(() => _fileSystem.MoveFile(SourceFileNameWithPath, DestinationFileNameWithPath));
// Make sure we did not override existing file
Assert.True(HasExpectedData(DestinationFileNameWithPath, DestData));
Assert.True(System.IO.File.Exists(SourceFileNameWithPath));
Assert.True(File.Exists(SourceFileNameWithPath));
}
[Fact]
public void MoveFile_SourceFileName_DestinationFileName_OverwriteFalse()
{
string SourceFileNameWithPath = CreateTestFile(SourceData, TestFileName: GetTestFileName());
string DestinationFileNameWithPath = System.IO.Path.Combine(TestDirectory, "NewName");
string DestinationFileNameWithPath = Path.Combine(TestDirectory, "NewName");
_fileSystem.MoveFile(SourceFileNameWithPath, DestinationFileNameWithPath, overwrite: false);
Assert.False(System.IO.File.Exists(SourceFileNameWithPath));
Assert.True(System.IO.File.Exists(DestinationFileNameWithPath));
Assert.False(File.Exists(SourceFileNameWithPath));
Assert.True(File.Exists(DestinationFileNameWithPath));
Assert.True(HasExpectedData(DestinationFileNameWithPath, SourceData));
SourceFileNameWithPath = DestinationFileNameWithPath;
DestinationFileNameWithPath = CreateTestFile(DestData, TestFileName: GetTestFileName());
Assert.Throws<IOException>(() => _fileSystem.MoveFile(SourceFileNameWithPath, DestinationFileNameWithPath, overwrite: false));
// Make sure we did not override existing file
Assert.True(HasExpectedData(DestinationFileNameWithPath, DestData));
Assert.True(System.IO.File.Exists(SourceFileNameWithPath));
Assert.True(File.Exists(SourceFileNameWithPath));
}
[Fact]
public void MoveFile_SourceFileName_DestinationFileName_OverwriteTrue()
{
string SourceFileNameWithPath = CreateTestFile(SourceData, TestFileName: GetTestFileName());
string DestinationFileNameWithPath = System.IO.Path.Combine(TestDirectory, "NewName");
string DestinationFileNameWithPath = Path.Combine(TestDirectory, "NewName");
_fileSystem.MoveFile(SourceFileNameWithPath, DestinationFileNameWithPath, overwrite: true);
Assert.False(System.IO.File.Exists(SourceFileNameWithPath));
Assert.True(System.IO.File.Exists(DestinationFileNameWithPath));
Assert.False(File.Exists(SourceFileNameWithPath));
Assert.True(File.Exists(DestinationFileNameWithPath));
Assert.True(HasExpectedData(DestinationFileNameWithPath, SourceData));
CreateTestFile(DestData, PathFromBase: null, TestFileName: (new FileInfo(SourceFileNameWithPath)).Name);
_fileSystem.MoveFile(sourceFileName: DestinationFileNameWithPath, destinationFileName: SourceFileNameWithPath, overwrite: true);
Assert.True(System.IO.File.Exists(SourceFileNameWithPath));
Assert.False(System.IO.File.Exists(DestinationFileNameWithPath));
Assert.True(File.Exists(SourceFileNameWithPath));
Assert.False(File.Exists(DestinationFileNameWithPath));
Assert.True(HasExpectedData(SourceFileNameWithPath, SourceData));
}
@ -638,20 +638,20 @@ public class FileSystemProxyTests : FileCleanupTestBase
public void RenameDirectory_Directory_NewName()
{
// <exception cref="IO.FileNotFoundException">If directory does not point to an existing directory.</exception>
Assert.Throws<DirectoryNotFoundException>(() => _fileSystem.RenameDirectory(System.IO.Path.Combine(TestDirectory, "DoesNotExistDirectory"), "NewDirectory"));
string OrigDirectoryWithPath = System.IO.Path.Combine(TestDirectory, "OriginalDirectory");
System.IO.Directory.CreateDirectory(OrigDirectoryWithPath);
Assert.Throws<DirectoryNotFoundException>(() => _fileSystem.RenameDirectory(Path.Combine(TestDirectory, "DoesNotExistDirectory"), "NewDirectory"));
string OrigDirectoryWithPath = Path.Combine(TestDirectory, "OriginalDirectory");
Directory.CreateDirectory(OrigDirectoryWithPath);
// <exception cref="System.ArgumentException">If newName is null or Empty String.</exception>
Assert.Throws<ArgumentNullException>(() => _fileSystem.RenameDirectory(OrigDirectoryWithPath, ""));
string DirectoryNameWithPath = System.IO.Path.Combine(TestDirectory, "DoesNotExist");
string DirectoryNameWithPath = Path.Combine(TestDirectory, "DoesNotExist");
// <exception cref="System.ArgumentException">If contains path information.</exception>
Assert.Throws<ArgumentException>(() => _fileSystem.RenameDirectory(OrigDirectoryWithPath, DirectoryNameWithPath));
_fileSystem.RenameDirectory(OrigDirectoryWithPath, "NewFDirectory");
string NewFDirectoryPath = System.IO.Path.Combine(TestDirectory, "NewFDirectory");
Assert.True(System.IO.Directory.Exists(NewFDirectoryPath));
Assert.False(System.IO.Directory.Exists(OrigDirectoryWithPath));
string NewFDirectoryPath = Path.Combine(TestDirectory, "NewFDirectory");
Assert.True(Directory.Exists(NewFDirectoryPath));
Assert.False(Directory.Exists(OrigDirectoryWithPath));
// <exception cref="IO.IOException">If directory points to a root directory or if there's an existing directory or an existing file with the same name.</exception>
System.IO.Directory.CreateDirectory(OrigDirectoryWithPath);
Directory.CreateDirectory(OrigDirectoryWithPath);
Assert.Throws<IOException>(() => _fileSystem.RenameDirectory(NewFDirectoryPath, "OriginalDirectory"));
}
@ -659,7 +659,7 @@ public class FileSystemProxyTests : FileCleanupTestBase
public void RenameFile_File_NewName()
{
// <exception cref="IO.FileNotFoundException">If file does not point to an existing file.</exception>
Assert.Throws<FileNotFoundException>(() => _fileSystem.RenameFile(System.IO.Path.Combine(TestDirectory, "DoesNotExistFile"), "NewFile"));
Assert.Throws<FileNotFoundException>(() => _fileSystem.RenameFile(Path.Combine(TestDirectory, "DoesNotExistFile"), "NewFile"));
string OrigFileWithPath = CreateTestFile(SourceData, TestFileName: GetTestFileName());
string ExistingFileWithPath = CreateTestFile(DestData, TestFileName: GetTestFileName());
// <exception cref="System.ArgumentException">If newName is null or Empty String.</exception>
@ -667,12 +667,12 @@ public class FileSystemProxyTests : FileCleanupTestBase
// <exception cref="System.ArgumentException">If contains path information.</exception>
Assert.Throws<ArgumentException>(() => _fileSystem.RenameFile(OrigFileWithPath, ExistingFileWithPath));
_fileSystem.RenameFile(OrigFileWithPath, "NewFile");
string NewFileWithPath = System.IO.Path.Combine(TestDirectory, "NewFile");
Assert.True(System.IO.File.Exists(NewFileWithPath));
Assert.False(System.IO.File.Exists(OrigFileWithPath));
string NewFileWithPath = Path.Combine(TestDirectory, "NewFile");
Assert.True(File.Exists(NewFileWithPath));
Assert.False(File.Exists(OrigFileWithPath));
// <exception cref="IO.IOException">If there's an existing directory or an existing file with the same name.</exception>
Assert.Throws<IOException>(() => _fileSystem.RenameFile(NewFileWithPath, "NewFile"));
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(TestDirectory, "NewFDirectory"));
Directory.CreateDirectory(Path.Combine(TestDirectory, "NewFDirectory"));
Assert.Throws<IOException>(() => _fileSystem.RenameFile(NewFileWithPath, "NewFDirectory"));
}
@ -691,15 +691,15 @@ public class FileSystemProxyTests : FileCleanupTestBase
private string CreateTestFile(string TestData, string TestFileName, string PathFromBase = null)
{
Assert.False(String.IsNullOrEmpty(TestFileName));
Assert.False(string.IsNullOrEmpty(TestFileName));
string TempFileNameWithPath = TestDirectory;
if (!string.IsNullOrEmpty(PathFromBase))
{
TempFileNameWithPath = System.IO.Path.Combine(TempFileNameWithPath, PathFromBase);
TempFileNameWithPath = Path.Combine(TempFileNameWithPath, PathFromBase);
}
TempFileNameWithPath = System.IO.Path.Combine(TempFileNameWithPath, TestFileName);
Assert.False(System.IO.File.Exists(TempFileNameWithPath), $"File {TempFileNameWithPath} should not exist!");
TempFileNameWithPath = Path.Combine(TempFileNameWithPath, TestFileName);
Assert.False(File.Exists(TempFileNameWithPath), $"File {TempFileNameWithPath} should not exist!");
WriteFile(TempFileNameWithPath, TestData);
return TempFileNameWithPath;
}

Просмотреть файл

@ -15,10 +15,14 @@ public class ContextValueTests
[Fact]
public void MultipleInstances()
{
ContextValue<int> context1 = new();
context1.Value = 1;
ContextValue<int> context2 = new();
context2.Value = 2;
ContextValue<int> context1 = new()
{
Value = 1
};
ContextValue<int> context2 = new()
{
Value = 2
};
Assert.Equal(1, context1.Value);
Assert.Equal(2, context2.Value);
}
@ -26,8 +30,10 @@ public class ContextValueTests
[Fact]
public void MultipleThreads()
{
ContextValue<string> context = new();
context.Value = "Hello";
ContextValue<string> context = new()
{
Value = "Hello"
};
Thread thread = new(() =>
{
Assert.Null(context.Value);

Просмотреть файл

@ -148,7 +148,7 @@ public class FontConverter : TypeConverter
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
if (!(value is string font))
if (value is not string font)
{
return base.ConvertFrom(context, culture, value);
}
@ -181,7 +181,7 @@ public class FontConverter : TypeConverter
}
// Some parameters are provided in addition to name.
fontName = font.Substring(0, nameIndex);
fontName = font[..nameIndex];
if (nameIndex < font.Length - 1)
{
@ -192,7 +192,7 @@ public class FontConverter : TypeConverter
if (styleIndex != -1)
{
// style found.
style = font.Substring(styleIndex);
style = font[styleIndex..];
// Get the mid-substring containing the size information.
sizeStr = font.Substring(nameIndex + 1, styleIndex - nameIndex - 1);
@ -200,17 +200,17 @@ public class FontConverter : TypeConverter
else
{
// no style.
sizeStr = font.Substring(nameIndex + 1);
sizeStr = font[(nameIndex + 1)..];
}
// Parse size.
(string? size, string? unit) unitTokens = ParseSizeTokens(sizeStr, separator);
(string? size, string? unit) = ParseSizeTokens(sizeStr, separator);
if (unitTokens.size is not null)
if (size is not null)
{
try
{
fontSize = (float)GetFloatConverter().ConvertFromString(context, culture, unitTokens.size)!;
fontSize = (float)GetFloatConverter().ConvertFromString(context, culture, size)!;
}
catch
{
@ -219,16 +219,16 @@ public class FontConverter : TypeConverter
}
}
if (unitTokens.unit is not null)
if (unit is not null)
{
// ParseGraphicsUnits throws an ArgumentException if format is invalid.
units = ParseGraphicsUnits(unitTokens.unit);
units = ParseGraphicsUnits(unit);
}
if (style is not null)
{
// Parse FontStyle
style = style.Substring(6); // style string always starts with style=
style = style[6..]; // style string always starts with style=
string[] styleTokens = style.Split(separator);
for (int tokenCount = 0; tokenCount < styleTokens.Length; tokenCount++)
@ -281,14 +281,14 @@ public class FontConverter : TypeConverter
if (splitPoint > 0)
{
size = text.Substring(0, splitPoint);
size = text[..splitPoint];
// Trimming spaces between size and units.
size = size.Trim(trimChars);
}
if (splitPoint < length)
{
units = text.Substring(splitPoint);
units = text[splitPoint..];
units = units.TrimEnd(trimChars);
}
}
@ -412,7 +412,7 @@ public class FontConverter : TypeConverter
return base.GetProperties(context, value, attributes);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value, attributes);
return props.Sort(new string[] { nameof(Font.Name), nameof(Font.Size), nameof(Font.Unit) });
return props.Sort([nameof(Font.Name), nameof(Font.Size), nameof(Font.Unit)]);
}
public override bool GetPropertiesSupported(ITypeDescriptorContext? context) => true;
@ -430,15 +430,11 @@ public class FontConverter : TypeConverter
{
}
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
return sourceType == typeof(string) ? true : base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) =>
sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
return value is string strValue ? MatchFontName(strValue, context) : base.ConvertFrom(context, culture, value);
}
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) =>
value is string strValue ? MatchFontName(strValue, context) : base.ConvertFrom(context, culture, value);
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext? context)
{

Просмотреть файл

@ -17,8 +17,7 @@ public sealed partial class Icon : MarshalByRefObject, ICloneable, IDisposable,
}
else
{
if (outputStream is null)
throw new ArgumentNullException(nameof(outputStream));
ArgumentNullException.ThrowIfNull(outputStream);
// Ideally, we would pick apart the icon using
// GetIconInfo, and then pull the individual bitmaps out,

Просмотреть файл

@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
@ -31,8 +31,7 @@ public class ImageFormatConverter : TypeConverter
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
// we must be able to convert from short names and long names
string? strFormat = value as string;
if (strFormat is null)
if (value is not string strFormat)
{
// case #1, this is not a string
return base.ConvertFrom(context, culture, value);
@ -112,7 +111,7 @@ public class ImageFormatConverter : TypeConverter
}
else
{
ConstructorInfo? ctor = typeof(ImageFormat).GetConstructor(new Type[] { typeof(Guid) });
ConstructorInfo? ctor = typeof(ImageFormat).GetConstructor([typeof(Guid)]);
return new InstanceDescriptor(ctor, new object[] { imgFormat.Guid });
}
}

Просмотреть файл

@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Drawing.Imaging;
@ -47,22 +47,13 @@ public sealed class FrameDimension
/// <summary>
/// The page dimension.
/// </summary>
public static FrameDimension Page
{
get { return s_page; }
}
public static FrameDimension Page => s_page;
/// <summary>
/// Returns a value indicating whether the specified object is an <see cref='FrameDimension'/> equivalent to
/// this <see cref='FrameDimension'/>.
/// </summary>
public override bool Equals([NotNullWhen(true)] object? o)
{
FrameDimension? format = o as FrameDimension;
if (format is null)
return false;
return _guid == format._guid;
}
public override bool Equals([NotNullWhen(true)] object? o) => o is FrameDimension format && _guid == format._guid;
public override int GetHashCode()
{
@ -70,13 +61,25 @@ public sealed class FrameDimension
}
/// <summary>
/// Converts this <see cref='FrameDimension'/> to a human-readable string.
/// Converts this <see cref='FrameDimension'/> to a human-readable string.
/// </summary>
public override string ToString()
{
if (this == s_time) return "Time";
if (this == s_resolution) return "Resolution";
if (this == s_page) return "Page";
if (this == s_time)
{
return "Time";
}
if (this == s_resolution)
{
return "Resolution";
}
if (this == s_page)
{
return "Page";
}
return $"[FrameDimension: {_guid}]";
}
}

Просмотреть файл

@ -128,18 +128,66 @@ public sealed class ImageFormat
/// </summary>
public override string ToString()
{
if (Guid == PInvokeCore.ImageFormatMemoryBMP) return "MemoryBMP";
if (Guid == PInvokeCore.ImageFormatBMP) return "Bmp";
if (Guid == PInvokeCore.ImageFormatEMF) return "Emf";
if (Guid == PInvokeCore.ImageFormatWMF) return "Wmf";
if (Guid == PInvokeCore.ImageFormatGIF) return "Gif";
if (Guid == PInvokeCore.ImageFormatJPEG) return "Jpeg";
if (Guid == PInvokeCore.ImageFormatPNG) return "Png";
if (Guid == PInvokeCore.ImageFormatTIFF) return "Tiff";
if (Guid == PInvokeCore.ImageFormatEXIF) return "Exif";
if (Guid == PInvokeCore.ImageFormatIcon) return "Icon";
if (Guid == PInvokeCore.ImageFormatHEIF) return "Heif";
if (Guid == PInvokeCore.ImageFormatWEBP) return "Webp";
if (Guid == PInvokeCore.ImageFormatMemoryBMP)
{
return "MemoryBMP";
}
if (Guid == PInvokeCore.ImageFormatBMP)
{
return "Bmp";
}
if (Guid == PInvokeCore.ImageFormatEMF)
{
return "Emf";
}
if (Guid == PInvokeCore.ImageFormatWMF)
{
return "Wmf";
}
if (Guid == PInvokeCore.ImageFormatGIF)
{
return "Gif";
}
if (Guid == PInvokeCore.ImageFormatJPEG)
{
return "Jpeg";
}
if (Guid == PInvokeCore.ImageFormatPNG)
{
return "Png";
}
if (Guid == PInvokeCore.ImageFormatTIFF)
{
return "Tiff";
}
if (Guid == PInvokeCore.ImageFormatEXIF)
{
return "Exif";
}
if (Guid == PInvokeCore.ImageFormatIcon)
{
return "Icon";
}
if (Guid == PInvokeCore.ImageFormatHEIF)
{
return "Heif";
}
if (Guid == PInvokeCore.ImageFormatWEBP)
{
return "Webp";
}
return $"[ImageFormat: {_guid}]";
}
}

Просмотреть файл

@ -11,14 +11,11 @@ namespace System.Drawing.Printing;
[Serializable]
public partial class InvalidPrinterException : SystemException
{
private readonly PrinterSettings? _settings;
/// <summary>
/// Initializes a new instance of the <see cref='InvalidPrinterException'/> class.
/// </summary>
public InvalidPrinterException(PrinterSettings settings) : base(GenerateMessage(settings))
{
_settings = settings;
}
private static string GenerateMessage(PrinterSettings settings)

Просмотреть файл

@ -231,7 +231,7 @@ public sealed unsafe class StringFormat : MarshalByRefObject, ICloneable, IDispo
_nativeFormat,
firstTabOffset,
tabStops.Length,
ts is null ? &stub :ts).ThrowIfFailed();
ts is null ? &stub : ts).ThrowIfFailed();
GC.KeepAlive(this);
}
}

Просмотреть файл

@ -673,7 +673,7 @@ public class LinearGradientBrushTests
using Matrix matrix = new(1, 2, 3, 4, 5, 6);
Matrix expectedTransform = brush.Transform;
if (order == MatrixOrder.Append || order == MatrixOrder.Prepend)
if (order is MatrixOrder.Append or MatrixOrder.Prepend)
{
expectedTransform.Multiply(matrix, order);
}

Просмотреть файл

@ -356,7 +356,7 @@ public class IconTests
{
string bitmapPath = Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico");
string bitmapPathRoot = Path.GetPathRoot(bitmapPath);
string bitmapUncPath = $"\\\\{Environment.MachineName}\\{bitmapPath.Substring(0, bitmapPathRoot.IndexOf(":"))}$\\{bitmapPath.Replace(bitmapPathRoot, "")}";
string bitmapUncPath = $"\\\\{Environment.MachineName}\\{bitmapPath[..bitmapPathRoot.IndexOf(':')]}$\\{bitmapPath.Replace(bitmapPathRoot, "")}";
// Some path could not be accessible
// if so we just pass the test
@ -841,7 +841,7 @@ public class IconTests
}
// Recent builds of Windows have added a few more icons to regedit.
Assert.True(count == 7 || count == 5, $"count was {count}, expected 5 or 7");
Assert.True(count is 7 or 5, $"count was {count}, expected 5 or 7");
}
[Fact]

Просмотреть файл

@ -23,8 +23,10 @@ public class BitmapDataTests
[InlineData(int.MinValue)]
public void Height_SetValid_ReturnsExpected(int value)
{
BitmapData bd = new();
bd.Height = value;
BitmapData bd = new()
{
Height = value
};
Assert.Equal(value, bd.Height);
}
@ -34,8 +36,10 @@ public class BitmapDataTests
[InlineData(int.MinValue)]
public void Width_SetValid_ReturnsExpected(int value)
{
BitmapData bd = new();
bd.Width = value;
BitmapData bd = new()
{
Width = value
};
Assert.Equal(value, bd.Width);
}
@ -45,8 +49,10 @@ public class BitmapDataTests
[InlineData(int.MinValue)]
public void Reserved_SetValid_ReturnsExpected(int value)
{
BitmapData bd = new();
bd.Reserved = value;
BitmapData bd = new()
{
Reserved = value
};
Assert.Equal(value, bd.Reserved);
}
@ -56,8 +62,10 @@ public class BitmapDataTests
[InlineData(int.MinValue)]
public void Scan0_SetValid_ReturnsExpected(int value)
{
BitmapData bd = new();
bd.Scan0 = new IntPtr(value);
BitmapData bd = new()
{
Scan0 = new IntPtr(value)
};
Assert.Equal(new IntPtr(value), bd.Scan0);
}
@ -67,8 +75,10 @@ public class BitmapDataTests
[InlineData(int.MinValue)]
public void Stride_SetValid_ReturnsExpected(int value)
{
BitmapData bd = new();
bd.Stride = value;
BitmapData bd = new()
{
Stride = value
};
Assert.Equal(value, bd.Stride);
}
@ -97,8 +107,10 @@ public class BitmapDataTests
[InlineData(PixelFormat.Format64bppArgb)]
public void PixelFormat_SetValid_ReturnsExpected(PixelFormat pixelFormat)
{
BitmapData bd = new();
bd.PixelFormat = pixelFormat;
BitmapData bd = new()
{
PixelFormat = pixelFormat
};
Assert.Equal(pixelFormat, bd.PixelFormat);
}

Просмотреть файл

@ -16,16 +16,20 @@ public class ColorMapTests
[Fact]
public void NewColor_SetValid_ReturnsExpected()
{
ColorMap cm = new();
cm.NewColor = Color.AliceBlue;
ColorMap cm = new()
{
NewColor = Color.AliceBlue
};
Assert.Equal(Color.AliceBlue, cm.NewColor);
}
[Fact]
public void OldColor_SetValid_ReturnsExpected()
{
ColorMap cm = new();
cm.OldColor = Color.AliceBlue;
ColorMap cm = new()
{
OldColor = Color.AliceBlue
};
Assert.Equal(Color.AliceBlue, cm.OldColor);
}
}

Просмотреть файл

@ -211,33 +211,34 @@ public class ColorMatrixTests
[Fact]
public void MatrixElement_SetValues_ReturnsExpected()
{
ColorMatrix cm = new();
cm.Matrix00 = 1;
cm.Matrix01 = 2;
cm.Matrix02 = 3;
cm.Matrix03 = 4;
cm.Matrix04 = 5;
cm.Matrix10 = 6;
cm.Matrix11 = 7;
cm.Matrix12 = 8;
cm.Matrix13 = 9;
cm.Matrix14 = 10;
cm.Matrix20 = 11;
cm.Matrix21 = 12;
cm.Matrix22 = 13;
cm.Matrix23 = 14;
cm.Matrix24 = 15;
cm.Matrix30 = 16;
cm.Matrix31 = 17;
cm.Matrix32 = 18;
cm.Matrix33 = 19;
cm.Matrix34 = 20;
cm.Matrix40 = 21;
cm.Matrix41 = 22;
cm.Matrix42 = 23;
cm.Matrix43 = 24;
cm.Matrix44 = 25;
ColorMatrix cm = new()
{
Matrix00 = 1,
Matrix01 = 2,
Matrix02 = 3,
Matrix03 = 4,
Matrix04 = 5,
Matrix10 = 6,
Matrix11 = 7,
Matrix12 = 8,
Matrix13 = 9,
Matrix14 = 10,
Matrix20 = 11,
Matrix21 = 12,
Matrix22 = 13,
Matrix23 = 14,
Matrix24 = 15,
Matrix30 = 16,
Matrix31 = 17,
Matrix32 = 18,
Matrix33 = 19,
Matrix34 = 20,
Matrix40 = 21,
Matrix41 = 22,
Matrix42 = 23,
Matrix43 = 24,
Matrix44 = 25
};
Assert.Equal(1, cm.Matrix00);
Assert.Equal(2, cm.Matrix01);

Просмотреть файл

@ -45,8 +45,10 @@ public class EncoderParametersTests
[MemberData(nameof(Param_TestData))]
public void Dispose_Success(EncoderParameter[] param)
{
EncoderParameters ep = new();
ep.Param = param;
EncoderParameters ep = new()
{
Param = param
};
ep.Dispose();
Assert.Null(ep.Param);
}

Просмотреть файл

@ -24,12 +24,15 @@ public class MetaHeaderTests
[InlineData(short.MinValue)]
public void ShortProperties_SetValues_ReturnsExpected(short value)
{
MetaHeader mh = new();
mh.HeaderSize = value;
mh.NoObjects = value;
mh.NoParameters = value;
mh.Type = value;
mh.Version = value;
MetaHeader mh = new()
{
HeaderSize = value,
NoObjects = value,
NoParameters = value,
Type = value,
Version = value
};
Assert.Equal(value, mh.HeaderSize);
Assert.Equal(value, mh.NoObjects);
Assert.Equal(value, mh.NoParameters);
@ -43,9 +46,11 @@ public class MetaHeaderTests
[InlineData(int.MinValue)]
public void IntProperties_SetValues_ReturnsExpected(int value)
{
MetaHeader mh = new();
mh.Size = value;
mh.MaxRecord = value;
MetaHeader mh = new()
{
Size = value,
MaxRecord = value
};
Assert.Equal(value, mh.Size);
Assert.Equal(value, mh.MaxRecord);
}

Просмотреть файл

@ -26,16 +26,18 @@ public class WmfPlaceableFileHeaderTests
[InlineData(short.MinValue)]
public void ShortProperties_SetValues_ReturnsExpected(short value)
{
WmfPlaceableFileHeader fileHeader = new();
fileHeader.BboxBottom = value;
fileHeader.BboxLeft = value;
fileHeader.BboxRight = value;
fileHeader.BboxTop = value;
fileHeader.Checksum = value;
fileHeader.Hmf = value;
fileHeader.Inch = value;
fileHeader.Key = value;
fileHeader.Reserved = value;
WmfPlaceableFileHeader fileHeader = new()
{
BboxBottom = value,
BboxLeft = value,
BboxRight = value,
BboxTop = value,
Checksum = value,
Hmf = value,
Inch = value,
Key = value,
Reserved = value
};
Assert.Equal(value, fileHeader.BboxBottom);
Assert.Equal(value, fileHeader.BboxLeft);
Assert.Equal(value, fileHeader.BboxRight);
@ -53,9 +55,11 @@ public class WmfPlaceableFileHeaderTests
[InlineData(int.MinValue)]
public void IntProperties_SetValues_ReturnsExpected(int value)
{
WmfPlaceableFileHeader fileHeader = new();
fileHeader.Key = value;
fileHeader.Reserved = value;
WmfPlaceableFileHeader fileHeader = new()
{
Key = value,
Reserved = value
};
Assert.Equal(value, fileHeader.Key);
Assert.Equal(value, fileHeader.Reserved);
}

Просмотреть файл

@ -34,11 +34,13 @@ public class PageSettingsTests
[ConditionalFact(Helpers.AnyInstalledPrinters)]
public void Clone_Success()
{
PageSettings ps = new();
ps.Color = false;
ps.Landscape = true;
ps.Margins = new Margins(120, 130, 140, 150);
ps.PaperSize = new PaperSize("My Custom Size", 222, 333);
PageSettings ps = new()
{
Color = false,
Landscape = true,
Margins = new Margins(120, 130, 140, 150),
PaperSize = new PaperSize("My Custom Size", 222, 333)
};
PageSettings clone = (PageSettings)ps.Clone();
Assert.Equal(ps.Color, clone.Color);

Просмотреть файл

@ -306,7 +306,7 @@ public class BitmapTests
if (sRslt.Length > 0)
{
if (sRslt[^1] != '\\' && sRslt[^1] != '/')
if (sRslt[^1] is not '\\' and not '/')
{
sRslt += "/";
}

Просмотреть файл

@ -362,8 +362,10 @@ public class MetafileFulltrustTest
SizeF size = g.MeasureString(text, test_font);
Assert.False(size.IsEmpty);
StringFormat sf = new();
sf.FormatFlags = StringFormatFlags.NoClip;
StringFormat sf = new()
{
FormatFlags = StringFormatFlags.NoClip
};
sf.SetMeasurableCharacterRanges(ranges);
RectangleF rect = new(0, 0, size.Width, size.Height);

Просмотреть файл

@ -5,7 +5,7 @@ namespace Windows.Win32.Foundation;
internal partial struct DECIMAL
{
public decimal ToDecimal()
public readonly decimal ToDecimal()
{
return new decimal(
(int)Anonymous2.Anonymous.Lo32,

Просмотреть файл

@ -12,8 +12,5 @@ internal partial struct FILETIME
dwHighDateTime = (uint)(ft >> 32);
}
public DateTime ToDateTime()
{
return DateTime.FromFileTime(((long)dwHighDateTime << 32) + dwLowDateTime);
}
public readonly DateTime ToDateTime() => DateTime.FromFileTime(((long)dwHighDateTime << 32) + dwLowDateTime);
}

Просмотреть файл

@ -75,16 +75,18 @@ internal readonly ref struct DeviceContextHdcScope
ApplyGraphicsProperties applyGraphicsState,
bool saveHdcState = false)
{
#if DEBUG
if (deviceContext is null)
{
// As we're throwing in the constructor, `this` will never be passed back and as such .Dispose()
// can't be called. We don't have anything to release at this point so there is no point in having
// the finalizer run.
#if DEBUG
DisposalTracking.SuppressFinalize(this!);
#endif
throw new ArgumentNullException(nameof(deviceContext));
}
#else
ArgumentNullException.ThrowIfNull(deviceContext);
#endif
DeviceContext = deviceContext;
_savedHdcState = 0;

Просмотреть файл

@ -104,7 +104,11 @@ internal unsafe ref struct RegionScope
/// <summary>
/// Returns true if this represents a null HRGN.
/// </summary>
#if DEBUG
public bool IsNull => Region.IsNull;
#else
public readonly bool IsNull => Region.IsNull;
#endif
public static implicit operator HRGN(RegionScope regionScope) => regionScope.Region;
@ -113,7 +117,11 @@ internal unsafe ref struct RegionScope
/// </summary>
public void RelinquishOwnership() => Region = default;
#if DEBUG
public void Dispose()
#else
public readonly void Dispose()
#endif
{
if (!IsNull)
{

Просмотреть файл

@ -33,11 +33,11 @@ internal class ApplicationConfigurationGenerator : IIncrementalGenerator
return;
}
if (outputKind != OutputKind.WindowsApplication &&
if (outputKind is not OutputKind.WindowsApplication
// Starting in the 5.0.100 version of the .NET SDK, when OutputType is set to Exe, it is automatically changed to WinExe
// for WPF and Windows Forms apps that target any framework version, including .NET Framework.
// https://docs.microsoft.com/en-us/dotnet/core/compatibility/sdk/5.0/automatically-infer-winexe-output-type
outputKind != OutputKind.ConsoleApplication)
and not OutputKind.ConsoleApplication)
{
context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.s_errorUnsupportedProjectType, Location.None, nameof(OutputKind.WindowsApplication)));
return;

Просмотреть файл

@ -41,8 +41,8 @@ namespace MyProject
{
foreach (OutputKind projectType in Enum.GetValues(typeof(OutputKind)))
{
if (projectType != OutputKind.ConsoleApplication &&
projectType != OutputKind.WindowsApplication)
if (projectType is not OutputKind.ConsoleApplication
and not OutputKind.WindowsApplication)
{
yield return new object[] { projectType };
}

Просмотреть файл

@ -12,8 +12,8 @@ namespace System.Windows.Forms.Generators.Tests;
[UsesVerify]
public partial class ApplicationConfigurationInitializeBuilderTests
{
private static readonly string[] s_locales = new[]
{
private static readonly string[] s_locales =
[
"ar-SA",
"en-US",
"es-ES",
@ -23,7 +23,7 @@ public partial class ApplicationConfigurationInitializeBuilderTests
"ru-RU",
"tr-TR",
"zh-CN"
};
];
[Theory]
[InlineData(null, "default_top_level")]

Просмотреть файл

@ -13,8 +13,8 @@ public partial class ProjectFileReaderTests
{
public class FontConverterTest
{
private static readonly string[] s_locales = new[]
{
private static readonly string[] s_locales =
[
"ar-SA",
"en-US",
"es-ES",
@ -24,7 +24,7 @@ public partial class ProjectFileReaderTests
"ru-RU",
"tr-TR",
"zh-CN"
};
];
public static IEnumerable<object[]> TestConvertFormData()
{

Просмотреть файл

@ -44,7 +44,7 @@ public static partial class CSharpCodeFixVerifier<TAnalyzer, TCodeFix>
/// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/>
public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource)
=> await VerifyCodeFixAsync(source, new[] { expected }, fixedSource);
=> await VerifyCodeFixAsync(source, [expected], fixedSource);
/// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/>
public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource)

Просмотреть файл

@ -18,7 +18,7 @@ public static partial class CSharpCodeRefactoringVerifier<TCodeRefactoring>
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult, string)"/>
public static async Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource)
{
await VerifyRefactoringAsync(source, new[] { expected }, fixedSource);
await VerifyRefactoringAsync(source, [expected], fixedSource);
}
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult[], string)"/>

Просмотреть файл

@ -20,7 +20,7 @@ internal static class CSharpVerifierHelper
private static ImmutableDictionary<string, ReportDiagnostic> GetNullableWarningsFromCompiler()
{
string[] args = { "/warnaserror:nullable" };
string[] args = ["/warnaserror:nullable"];
var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory);
var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions;

Просмотреть файл

@ -44,7 +44,7 @@ public static partial class VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix>
/// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult, string)"/>
public static async Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource)
=> await VerifyCodeFixAsync(source, new[] { expected }, fixedSource);
=> await VerifyCodeFixAsync(source, [expected], fixedSource);
/// <inheritdoc cref="CodeFixVerifier{TAnalyzer, TCodeFix, TTest, TVerifier}.VerifyCodeFixAsync(string, DiagnosticResult[], string)"/>
public static async Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource)

Просмотреть файл

@ -18,7 +18,7 @@ public static partial class VisualBasicCodeRefactoringVerifier<TCodeRefactoring>
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult, string)"/>
public static async Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource)
{
await VerifyRefactoringAsync(source, new[] { expected }, fixedSource);
await VerifyRefactoringAsync(source, [expected], fixedSource);
}
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult[], string)"/>

Просмотреть файл

@ -64,3 +64,24 @@
[assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Public API", Scope = "member", Target = "~F:System.Windows.Forms.Design.ToolStripDesignerUtils.t_cachedToolboxItems")]
[assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Thread Local", Scope = "member", Target = "~F:System.Windows.Forms.Design.ToolStripDesignerUtils.t_customToolStripItemCount")]
[assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Thread Local", Scope = "member", Target = "~F:System.Windows.Forms.Design.ToolStripDesignerUtils.t_cachedWinformsImages")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~M:System.ComponentModel.Design.Serialization.CodeDomSerializerBase.SerializeToExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager,System.Object)~System.CodeDom.CodeExpression")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.ToolStripDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.ToolStripDropDownDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.TreeViewDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.DataGridViewDesigner.Verbs")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~M:System.Windows.Forms.Design.DataGridViewDesigner.BuildActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.TextBoxDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.MaskedTextBoxDesigner.Verbs")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.MaskedTextBoxDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~M:System.Windows.Forms.Design.Behavior.DesignerActionBehavior.CreateDesignerActionPanel(System.ComponentModel.IComponent)~System.ComponentModel.Design.DesignerActionPanel")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.RichTextBoxDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.SplitContainerDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~M:System.Windows.Forms.Design.ControlCodeDomSerializer.SerializeResumeLayout(System.ComponentModel.Design.Serialization.IDesignerSerializationManager,System.CodeDom.CodeStatementCollection,System.Object)")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.NotifyIconDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.TabControlDesigner.Verbs")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.ListBoxDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.ImageListDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.TableLayoutPanelDesigner.Verbs")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~M:System.Windows.Forms.Design.TableLayoutPanelDesigner.BuildActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.ListViewDesigner.ActionLists")]
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "Creates ambiguity", Scope = "member", Target = "~P:System.Windows.Forms.Design.PictureBoxDesigner.ActionLists")]

Просмотреть файл

@ -44,7 +44,7 @@ public class ArrayEditor : CollectionEditor
/// </summary>
protected override object SetItems(object editValue, object[] value)
{
if (editValue is not null && !(editValue is Array))
if (editValue is not null and not Array)
{
return editValue;
}

Просмотреть файл

@ -103,10 +103,12 @@ public sealed partial class BinaryEditor
{
try
{
SaveFileDialog sfd = new();
sfd.FileName = SR.BinaryEditorFileName;
sfd.Title = SR.BinaryEditorSaveFile;
sfd.Filter = SR.BinaryEditorAllFiles + " (*.*)|*.*";
SaveFileDialog sfd = new()
{
FileName = SR.BinaryEditorFileName,
Title = SR.BinaryEditorSaveFile,
Filter = SR.BinaryEditorAllFiles + " (*.*)|*.*"
};
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.OK)

Просмотреть файл

@ -139,23 +139,30 @@ public class ByteViewer : TableLayoutPanel
{
using (Brush brush = new SolidBrush(SystemColors.ControlLightLight))
{
g.FillRectangle(brush, new Rectangle(HEX_START_X,
CLIENT_START_Y,
HEX_WIDTH + HEX_DUMP_GAP + DUMP_WIDTH + HEX_DUMP_GAP,
_rowCount * CELL_HEIGHT));
g.FillRectangle(
brush,
new Rectangle(
HEX_START_X,
CLIENT_START_Y,
HEX_WIDTH + HEX_DUMP_GAP + DUMP_WIDTH + HEX_DUMP_GAP,
_rowCount * CELL_HEIGHT));
}
using (Pen pen = new(SystemColors.ControlDark))
{
g.DrawRectangle(pen, new Rectangle(HEX_START_X,
CLIENT_START_Y,
HEX_WIDTH + HEX_DUMP_GAP + DUMP_WIDTH + HEX_DUMP_GAP - 1,
_rowCount * CELL_HEIGHT - 1));
g.DrawLine(pen, DUMP_START_X - HEX_DUMP_GAP,
CLIENT_START_Y,
DUMP_START_X - HEX_DUMP_GAP,
CLIENT_START_Y + _rowCount * CELL_HEIGHT - 1);
}
using Pen pen = new(SystemColors.ControlDark);
g.DrawRectangle(
pen,
new Rectangle(
HEX_START_X,
CLIENT_START_Y,
HEX_WIDTH + HEX_DUMP_GAP + DUMP_WIDTH + HEX_DUMP_GAP - 1,
_rowCount * CELL_HEIGHT - 1));
g.DrawLine(
pen,
DUMP_START_X - HEX_DUMP_GAP,
CLIENT_START_Y,
DUMP_START_X - HEX_DUMP_GAP,
CLIENT_START_Y + _rowCount * CELL_HEIGHT - 1);
}
// Char.IsPrintable is going away because it's a mostly meaningless concept.
@ -163,9 +170,11 @@ public class ByteViewer : TableLayoutPanel
private static bool CharIsPrintable(char c)
{
UnicodeCategory uc = char.GetUnicodeCategory(c);
return (!(uc == UnicodeCategory.Control) || (uc == UnicodeCategory.Format) ||
(uc == UnicodeCategory.LineSeparator) || (uc == UnicodeCategory.ParagraphSeparator) ||
(uc == UnicodeCategory.OtherNotAssigned));
return uc is not UnicodeCategory.Control
or UnicodeCategory.Format
or UnicodeCategory.LineSeparator
or UnicodeCategory.ParagraphSeparator
or UnicodeCategory.OtherNotAssigned;
}
/// <summary>
@ -363,38 +372,22 @@ public class ByteViewer : TableLayoutPanel
public virtual DisplayMode GetDisplayMode() => _displayMode;
// Stole this code from XmlScanner
private static int GetEncodingIndex(int c1)
private static int GetEncodingIndex(int c1) => c1 switch
{
switch (c1)
{
case 0x0000:
return 1;
case 0xfeff:
return 2;
case 0xfffe:
return 3;
case 0xefbb:
return 4;
case 0x3c00:
return 5;
case 0x003c:
return 6;
case 0x3f00:
return 7;
case 0x003f:
return 8;
case 0x3c3f:
return 9;
case 0x786d:
return 10;
case 0x4c6f:
return 11;
case 0xa794:
return 12;
default:
return 0; // unknown
}
}
0x0000 => 1,
0xfeff => 2,
0xfffe => 3,
0xefbb => 4,
0x3c00 => 5,
0x003c => 6,
0x3f00 => 7,
0x003f => 8,
0x3c3f => 9,
0x786d => 10,
0x4c6f => 11,
0xa794 => 12,
_ => 0, // unknown
};
/// <summary>
/// Initializes the ansi string variable that will be assigned to the edit box.
@ -455,18 +448,20 @@ public class ByteViewer : TableLayoutPanel
_scrollBar.Dock = DockStyle.Right;
_scrollBar.Visible = false;
_edit = new TextBox();
_edit.AutoSize = false;
_edit.BorderStyle = BorderStyle.None;
_edit.Multiline = true;
_edit.ReadOnly = true;
_edit.ScrollBars = ScrollBars.Both;
_edit.AcceptsTab = true;
_edit.AcceptsReturn = true;
_edit.Dock = DockStyle.Fill;
_edit.Margin = Padding.Empty;
_edit.WordWrap = false;
_edit.Visible = false;
_edit = new TextBox
{
AutoSize = false,
BorderStyle = BorderStyle.None,
Multiline = true,
ReadOnly = true,
ScrollBars = ScrollBars.Both,
AcceptsTab = true,
AcceptsReturn = true,
Dock = DockStyle.Fill,
Margin = Padding.Empty,
WordWrap = false,
Visible = false
};
Controls.Add(_scrollBar, 0, 0);
Controls.Add(_edit, 0, 0);

Просмотреть файл

@ -246,7 +246,7 @@ public partial class CollectionEditor
if (_createdItems is not null)
{
if (_createdItems is [IComponent {Site: not null}, ..])
if (_createdItems is [IComponent { Site: not null }, ..])
{
// here we bail now because we don't want to do the "undo" manually,
// we're part of a transaction, we've added item, the rollback will be
@ -256,7 +256,7 @@ public partial class CollectionEditor
return;
}
object[] items = _createdItems.ToArray();
object[] items = [.. _createdItems];
for (int i = 0; i < items.Length; i++)
{
DestroyInstance(items[i]);
@ -272,7 +272,7 @@ public partial class CollectionEditor
// but this will at least roll back the additions, removals and reordering. See ASURT #85470.
if (_originalItems is not null && _originalItems.Count > 0)
{
Items = _originalItems.ToArray();
Items = [.. _originalItems];
_originalItems.Clear();
}
else
@ -324,9 +324,7 @@ public partial class CollectionEditor
}
int ti = _listBox.TopIndex;
object itemMove = _listBox.Items[index];
_listBox.Items[index] = _listBox.Items[index + 1];
_listBox.Items[index + 1] = itemMove;
(_listBox.Items[index + 1], _listBox.Items[index]) = (_listBox.Items[index], _listBox.Items[index + 1]);
if (ti < _listBox.Items.Count - 1)
{
@ -522,32 +520,30 @@ public partial class CollectionEditor
return;
}
using (Graphics g = _listBox.CreateGraphics())
using Graphics g = _listBox.CreateGraphics();
int old = _listBox.HorizontalExtent;
if (item is not null)
{
int old = _listBox.HorizontalExtent;
if (item is not null)
int w = CalcItemWidth(g, item);
if (w > old)
{
int w = CalcItemWidth(g, item);
if (w > old)
_listBox.HorizontalExtent = w;
}
}
else
{
int max = 0;
foreach (ListItem i in _listBox.Items)
{
int w = CalcItemWidth(g, i);
if (w > max)
{
_listBox.HorizontalExtent = w;
max = w;
}
}
else
{
int max = 0;
foreach (ListItem i in _listBox.Items)
{
int w = CalcItemWidth(g, i);
if (w > max)
{
max = w;
}
}
_listBox.HorizontalExtent = max;
}
_listBox.HorizontalExtent = max;
}
}
@ -689,7 +685,7 @@ public partial class CollectionEditor
if (_removedItems is not null && _dirty)
{
object[] deadItems = _removedItems.ToArray();
object[] deadItems = [.. _removedItems];
for (int i = 0; i < deadItems.Length; i++)
{
@ -997,9 +993,7 @@ public partial class CollectionEditor
{
SuspendEnabledUpdates();
int ti = _listBox.TopIndex;
object itemMove = _listBox.Items[index];
_listBox.Items[index] = _listBox.Items[index - 1];
_listBox.Items[index - 1] = itemMove;
(_listBox.Items[index - 1], _listBox.Items[index]) = (_listBox.Items[index], _listBox.Items[index - 1]);
if (ti > 0)
{

Просмотреть файл

@ -50,7 +50,7 @@ public partial class CollectionEditor
// The first thing the ime does on a key it cares about is send a VK_PROCESSKEY, so we use
// that to sling focus to the grid.
if (m.WParamInternal == (nuint)VK_PROCESSKEY)
if (m.WParamInternal == VK_PROCESSKEY)
{
if (PropertyGrid is not null)
{
@ -74,7 +74,7 @@ public partial class CollectionEditor
case PInvoke.WM_CHAR:
if ((Control.ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
{
break;
}

Просмотреть файл

@ -173,7 +173,7 @@ public partial class CollectionEditor
return;
}
if (ContextMenuStrip is not {Visible: true})
if (ContextMenuStrip is not { Visible: true })
{
SetButtonDrawState();
if (Parent is not null && Bounds.Contains(Parent.PointToClient(Cursor.Position)) && !_dropDownRectangle.Contains(mevent.Location))

Просмотреть файл

@ -121,9 +121,7 @@ internal sealed partial class DesignerActionPanel
protected override bool ProcessDialogKey(Keys keyData)
{
if ((keyData == (Keys.Alt | Keys.Down)) ||
(keyData == (Keys.Alt | Keys.Up)) ||
(keyData == Keys.F4))
if (keyData is (Keys.Alt | Keys.Down) or (Keys.Alt | Keys.Up) or Keys.F4)
{
// Any of these keys indicates the selection is accepted
Visible = false;

Просмотреть файл

@ -291,11 +291,9 @@ internal sealed partial class DesignerActionPanel
int height = width - 1;
_swatch = new Bitmap(width, height);
Rectangle rect = new(1, 1, width - 2, height - 2);
using (Graphics swatchGraphics = Graphics.FromImage(_swatch))
{
_editor.PaintValue(Value, swatchGraphics, rect);
swatchGraphics.DrawRectangle(SystemPens.ControlDark, new Rectangle(0, 0, width - 1, height - 1));
}
using Graphics swatchGraphics = Graphics.FromImage(_swatch);
_editor.PaintValue(Value, swatchGraphics, rect);
swatchGraphics.DrawRectangle(SystemPens.ControlDark, new Rectangle(0, 0, width - 1, height - 1));
}
g.DrawImage(_swatch, new Point(EditRegionRelativeLocation.X + 2, EditorLineSwatchPadding + 5));

Просмотреть файл

@ -98,16 +98,12 @@ internal sealed partial class DesignerActionPanel
public override void PaintLine(Graphics g, int lineWidth, int lineHeight)
{
Color backColor = (_formActive || ActionPanel._dropDownActive) ? ActionPanel.TitleBarColor : ActionPanel.TitleBarUnselectedColor;
using (SolidBrush b = new(backColor))
{
g.FillRectangle(b, 1, 1, lineWidth - 2, lineHeight - 1);
}
using SolidBrush b = new(backColor);
g.FillRectangle(b, 1, 1, lineWidth - 2, lineHeight - 1);
// Paint a line under the title label
using (Pen p = new(ActionPanel.BorderColor))
{
g.DrawLine(p, 0, lineHeight - 1, lineWidth, lineHeight - 1);
}
using Pen p = new(ActionPanel.BorderColor);
g.DrawLine(p, 0, lineHeight - 1, lineWidth, lineHeight - 1);
}
internal override void UpdateActionItem(LineInfo lineInfo, ToolTip toolTip, ref int currentTabIndex)

Просмотреть файл

@ -25,10 +25,8 @@ internal sealed partial class DesignerActionPanel
public override void PaintLine(Graphics g, int lineWidth, int lineHeight)
{
using (Pen p = new(ActionPanel.SeparatorColor))
{
g.DrawLine(p, SeparatorHorizontalPadding, 0, lineWidth - (SeparatorHorizontalPadding + 1), 0);
}
using Pen p = new(ActionPanel.SeparatorColor);
g.DrawLine(p, SeparatorHorizontalPadding, 0, lineWidth - (SeparatorHorizontalPadding + 1), 0);
}
internal override void UpdateActionItem(LineInfo lineInfo, ToolTip toolTip, ref int currentTabIndex)

Просмотреть файл

@ -465,17 +465,13 @@ internal sealed partial class DesignerActionPanel : ContainerControl
Rectangle rect = Bounds;
if (RightToLeft == RightToLeft.Yes)
{
using (LinearGradientBrush gradientBrush = new(rect, GradientDarkColor, GradientLightColor, LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(gradientBrush, ClientRectangle);
}
using LinearGradientBrush gradientBrush = new(rect, GradientDarkColor, GradientLightColor, LinearGradientMode.Horizontal);
e.Graphics.FillRectangle(gradientBrush, ClientRectangle);
}
else
{
using (LinearGradientBrush gradientBrush = new(rect, GradientLightColor, GradientDarkColor, LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(gradientBrush, ClientRectangle);
}
using LinearGradientBrush gradientBrush = new(rect, GradientLightColor, GradientDarkColor, LinearGradientMode.Horizontal);
e.Graphics.FillRectangle(gradientBrush, ClientRectangle);
}
using (Pen borderPen = new(BorderColor))
@ -660,11 +656,11 @@ internal sealed partial class DesignerActionPanel : ContainerControl
}
else if (item is DesignerActionPropertyItem pti)
{
PropertyDescriptor? pd = TypeDescriptor.GetProperties(list)[pti.MemberName];
if (pd is null)
{
throw new InvalidOperationException(string.Format(SR.DesignerActionPanel_CouldNotFindProperty, pti.MemberName, list.GetType().FullName));
}
PropertyDescriptor? pd = TypeDescriptor.GetProperties(list)[pti.MemberName]
?? throw new InvalidOperationException(string.Format(
SR.DesignerActionPanel_CouldNotFindProperty,
pti.MemberName,
list.GetType().FullName));
TypeDescriptorContext context = new(_serviceProvider, pd, list);
bool standardValuesSupported = pd.Converter.GetStandardValuesSupported(context);
@ -873,7 +869,7 @@ internal sealed partial class DesignerActionPanel : ContainerControl
Line newLine = newLineInfo.CreateLine(_serviceProvider, this);
Debug.Assert(newLine.GetType() == newLineInfo.LineType);
List<Control> newControlList = newLine.GetControls();
Control[] controls = newControlList.ToArray();
Control[] controls = [.. newControlList];
Controls.AddRange(controls);
newLine.UpdateActionItem(newLineInfo, _toolTip, ref currentTabIndex);

Просмотреть файл

@ -90,7 +90,7 @@ public class DesignerActionService : IDisposable
}
// Get list of components
IComponent[] compsRemoved = _designerActionLists.Keys.ToArray();
IComponent[] compsRemoved = [.. _designerActionLists.Keys];
// Actually clear our dictionary.
_designerActionLists.Clear();
@ -203,7 +203,7 @@ public class DesignerActionService : IDisposable
if (verbsArray.Count != 0)
{
actionLists.Add(new DesignerActionVerbList(verbsArray.ToArray()));
actionLists.Add(new DesignerActionVerbList([.. verbsArray]));
}
}
}

Просмотреть файл

@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
@ -527,7 +527,7 @@ internal sealed partial class DesignerHost : Container, IDesignerLoaderHost2, ID
if (component == _rootComponent)
{
string className = _rootComponentClassName!;
if (oldName is not null && className.EndsWith(oldName) // If oldName occurs at the end of className
if (oldName is not null && className.EndsWith(oldName, StringComparison.Ordinal) // If oldName occurs at the end of className
&& (className.Length > oldName.Length && className[className.Length - oldName.Length - 1] == '.')) // and is preceeded by a period
{
// We assume the preceeding chars are the namespace and preserve it.

Просмотреть файл

@ -188,7 +188,7 @@ public abstract partial class EventBindingService : IEventBindingService
props.Add(prop);
}
return new PropertyDescriptorCollection(props.ToArray());
return new PropertyDescriptorCollection([.. props]);
}
/// <summary>

Просмотреть файл

@ -19,15 +19,8 @@ internal sealed class ExtenderProviderService : IExtenderProviderService, IExten
/// <summary>
/// Gets the set of extender providers for the component.
/// </summary>
IExtenderProvider[] IExtenderListService.GetExtenderProviders()
{
if (_providers is not null)
{
return _providers.ToArray();
}
return [];
}
IExtenderProvider[] IExtenderListService.GetExtenderProviders() =>
_providers is not null ? ([.. _providers]) : ([]);
/// <summary>
/// Adds an extender provider.

Просмотреть файл

@ -82,7 +82,8 @@ internal sealed class InheritedPropertyDescriptor : PropertyDescriptor
new EditorAttribute(typeof(UITypeEditor), typeof(UITypeEditor)),
new TypeConverterAttribute(typeof(ReadOnlyCollectionConverter))
};
AttributeArray = attributes.ToArray();
AttributeArray = [.. attributes];
readOnlyCollection = true;
}
}
@ -97,7 +98,7 @@ internal sealed class InheritedPropertyDescriptor : PropertyDescriptor
new DefaultValueAttribute(_defaultValue)
};
AttributeArray = attributes.ToArray();
AttributeArray = [.. attributes];
}
}
}

Просмотреть файл

@ -67,7 +67,7 @@ public abstract partial class ObjectSelectorEditor : UITypeEditor
HWND hwnd = (HWND)treeView.Handle;
uint exstyle = (uint)PInvoke.SendMessage(hwnd, PInvoke.TVM_GETEXTENDEDSTYLE);
exstyle |= PInvoke.TVS_EX_DOUBLEBUFFER | PInvoke.TVS_EX_FADEINOUTEXPANDOS;
PInvoke.SendMessage(hwnd, PInvoke.TVM_SETEXTENDEDSTYLE, (WPARAM)0, (LPARAM)(uint)exstyle);
PInvoke.SendMessage(hwnd, PInvoke.TVM_SETEXTENDEDSTYLE, (WPARAM)0, (LPARAM)exstyle);
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext? context) => UITypeEditorEditStyle.DropDown;

Просмотреть файл

@ -292,7 +292,7 @@ internal sealed class ReferenceService : IReferenceService, IDisposable
}
}
return results.ToArray();
return [.. results];
}
/// <summary>

Просмотреть файл

@ -399,9 +399,7 @@ internal sealed class SelectionService : ISelectionService, IDisposable
{
if (primaryIndex != 0)
{
IComponent tmp = _selection[0];
_selection[0] = _selection[primaryIndex];
_selection[primaryIndex] = tmp;
(_selection[primaryIndex], _selection[0]) = (_selection[0], _selection[primaryIndex]);
fChanged = true;
}
}

Просмотреть файл

@ -141,16 +141,20 @@ public abstract partial class BasicDesignerLoader : DesignerLoader, IDesignerLoa
if (_state[s_stateLoaded])
{
Exception ex = new InvalidOperationException(SR.BasicDesignerLoaderAlreadyLoaded);
ex.HelpLink = SR.BasicDesignerLoaderAlreadyLoaded;
Exception ex = new InvalidOperationException(SR.BasicDesignerLoaderAlreadyLoaded)
{
HelpLink = SR.BasicDesignerLoaderAlreadyLoaded
};
throw ex;
}
if (_host is not null && _host != host)
{
Exception ex = new InvalidOperationException(SR.BasicDesignerLoaderDifferentHost);
ex.HelpLink = SR.BasicDesignerLoaderDifferentHost;
Exception ex = new InvalidOperationException(SR.BasicDesignerLoaderDifferentHost)
{
HelpLink = SR.BasicDesignerLoaderDifferentHost
};
throw ex;
}

Просмотреть файл

@ -201,7 +201,7 @@ public sealed partial class CodeDomComponentSerializationService
// We need to resolve the first chunk using the manager. other chunks will be resolved within the nested containers.
int curIndex = name.IndexOf('.');
Debug.Assert(curIndex > 0, "ResolvedNestedName accepts only nested names!");
outerComponent = name.Substring(0, curIndex);
outerComponent = name[..curIndex];
IComponent? curComp = manager.GetInstance(outerComponent) as IComponent;
do
@ -212,7 +212,7 @@ public sealed partial class CodeDomComponentSerializationService
moreChunks = curIndex != -1;
string compName = moreChunks
? name.Substring(prevIndex + 1, curIndex)
: name.Substring(prevIndex + 1);
: name[(prevIndex + 1)..];
if (string.IsNullOrEmpty(compName))
{

Просмотреть файл

@ -198,8 +198,10 @@ public abstract partial class CodeDomDesignerLoader : BasicDesignerLoader, IName
if (_documentCompileUnit is null)
{
Exception ex = new NotSupportedException(SR.CodeDomDesignerLoaderNoLanguageSupport);
ex.HelpLink = SR.CodeDomDesignerLoaderNoLanguageSupport;
Exception ex = new NotSupportedException(SR.CodeDomDesignerLoaderNoLanguageSupport)
{
HelpLink = SR.CodeDomDesignerLoaderNoLanguageSupport
};
throw ex;
}
@ -349,13 +351,17 @@ public abstract partial class CodeDomDesignerLoader : BasicDesignerLoader, IName
StringBuilder builder = new(Environment.NewLine);
builder.AppendJoin(Environment.NewLine, failures);
ex = new InvalidOperationException(string.Format(SR.CodeDomDesignerLoaderNoRootSerializerWithFailures, builder));
ex.HelpLink = SR.CodeDomDesignerLoaderNoRootSerializer;
ex = new InvalidOperationException(string.Format(SR.CodeDomDesignerLoaderNoRootSerializerWithFailures, builder))
{
HelpLink = SR.CodeDomDesignerLoaderNoRootSerializer
};
}
else
{
ex = new InvalidOperationException(SR.CodeDomDesignerLoaderNoRootSerializer);
ex.HelpLink = SR.CodeDomDesignerLoaderNoRootSerializer;
ex = new InvalidOperationException(SR.CodeDomDesignerLoaderNoRootSerializer)
{
HelpLink = SR.CodeDomDesignerLoaderNoRootSerializer
};
}
throw ex;
@ -987,8 +993,10 @@ public abstract partial class CodeDomDesignerLoader : BasicDesignerLoader, IName
{
if (serializationData is not SerializationStore data)
{
Exception ex = new ArgumentException(SR.CodeDomDesignerLoaderBadSerializationObject);
ex.HelpLink = SR.CodeDomDesignerLoaderBadSerializationObject;
Exception ex = new ArgumentException(SR.CodeDomDesignerLoaderBadSerializationObject)
{
HelpLink = SR.CodeDomDesignerLoaderBadSerializationObject
};
throw ex;
}
@ -1044,7 +1052,7 @@ public abstract partial class CodeDomDesignerLoader : BasicDesignerLoader, IName
}
else
{
baseName.AsSpan(i).Replace(span.Slice(i), '`', '_');
baseName.AsSpan(i).Replace(span[i..], '`', '_');
break;
}
}
@ -1199,8 +1207,10 @@ public abstract partial class CodeDomDesignerLoader : BasicDesignerLoader, IName
if (name.Length == 0)
{
Exception ex = new ArgumentException(SR.CodeDomDesignerLoaderInvalidBlankIdentifier);
ex.HelpLink = SR.CodeDomDesignerLoaderInvalidIdentifier;
Exception ex = new ArgumentException(SR.CodeDomDesignerLoaderInvalidBlankIdentifier)
{
HelpLink = SR.CodeDomDesignerLoaderInvalidIdentifier
};
throw ex;
}
@ -1230,8 +1240,10 @@ public abstract partial class CodeDomDesignerLoader : BasicDesignerLoader, IName
catch
{
// we have to change the exception back to the original name
Exception ex = new ArgumentException(string.Format(SR.CodeDomDesignerLoaderInvalidIdentifier, name));
ex.HelpLink = SR.CodeDomDesignerLoaderInvalidIdentifier;
Exception ex = new ArgumentException(string.Format(SR.CodeDomDesignerLoaderInvalidIdentifier, name))
{
HelpLink = SR.CodeDomDesignerLoaderInvalidIdentifier
};
throw ex;
}
@ -1271,8 +1283,10 @@ public abstract partial class CodeDomDesignerLoader : BasicDesignerLoader, IName
if (dup)
{
Exception ex = new ArgumentException(string.Format(SR.CodeDomDesignerLoaderDupComponentName, name));
ex.HelpLink = SR.CodeDomDesignerLoaderDupComponentName;
Exception ex = new ArgumentException(string.Format(SR.CodeDomDesignerLoaderDupComponentName, name))
{
HelpLink = SR.CodeDomDesignerLoaderDupComponentName
};
throw ex;
}

Просмотреть файл

@ -205,5 +205,5 @@ public sealed partial class CodeDomLocalizationProvider : IDisposable, IDesigner
return null; // don't understand this type of serializer.
}
#endregion
#endregion
}

Просмотреть файл

@ -333,7 +333,7 @@ public class CodeDomSerializer : CodeDomSerializerBase
if (referenceName && dotIndex != -1)
{
// if it's a reference name with a dot, we've actually got a property here...
expression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(s_thisRef, name.Substring(0, dotIndex)), name.Substring(dotIndex + 1));
expression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(s_thisRef, name[..dotIndex]), name[(dotIndex + 1)..]);
}
else
{

Просмотреть файл

@ -21,9 +21,11 @@ public abstract partial class CodeDomSerializerBase
private static readonly Attribute[] s_runTimeProperties = [DesignOnlyAttribute.No];
private static readonly TraceSwitch s_traceSerialization = new("DesignerSerialization", "Trace design time serialization");
#pragma warning disable CS0649
#pragma warning disable IDE0044 // Add readonly modifier - can only be readonly in release, should probably refactor to only have this in debug
#if DEBUG
private static Stack<string>? s_traceScope;
#pragma warning restore IDE0044
#else
private static readonly Stack<string>? s_traceScope;
#endif
#pragma warning restore CS0649
/// <summary>
/// Internal constructor so only we can derive from this class.
@ -375,7 +377,7 @@ public abstract partial class CodeDomSerializerBase
continue;
}
string propertyName = resourceName.Substring(dotIndex + 1);
string propertyName = resourceName[(dotIndex + 1)..];
// Now locate the property by this name.
PropertyDescriptor? property = ourProperties[propertyName];
@ -1002,9 +1004,9 @@ public abstract partial class CodeDomSerializerBase
{
string methodName = methodInvokeEx.Method.MethodName;
if (methodName.StartsWith("add_"))
if (methodName.StartsWith("add_", StringComparison.Ordinal))
{
methodName = methodName.Substring(4);
methodName = methodName[4..];
DeserializeAttachEventStatement(manager, new CodeAttachEventStatement(methodInvokeEx.Method.TargetObject, methodName, codeDelegateCreateExpression));
result = null;
}
@ -2676,7 +2678,7 @@ public abstract partial class CodeDomSerializerBase
if (referenceName && dotIndex >= 0)
{
// if it's a reference name with a dot, we've actually got a property here...
expression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(root.Expression, name.Substring(0, dotIndex)), name.Substring(dotIndex + 1));
expression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(root.Expression, name[..dotIndex]), name[(dotIndex + 1)..]);
}
else
{
@ -2692,7 +2694,7 @@ public abstract partial class CodeDomSerializerBase
if (referenceName && dotIndex >= 0)
{
// if it's a reference name with a dot, we've actually got a property here...
expression = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(name.Substring(0, dotIndex)), name.Substring(dotIndex + 1));
expression = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(name[..dotIndex]), name[(dotIndex + 1)..]);
}
else
{

Просмотреть файл

@ -18,11 +18,11 @@ internal sealed partial class ComponentCache : IDisposable
_serManager = manager;
if (manager.GetService(typeof(IComponentChangeService)) is IComponentChangeService cs)
{
cs.ComponentChanging += new ComponentChangingEventHandler(OnComponentChanging);
cs.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged);
cs.ComponentRemoving += new ComponentEventHandler(OnComponentRemove);
cs.ComponentRemoved += new ComponentEventHandler(OnComponentRemove);
cs.ComponentRename += new ComponentRenameEventHandler(OnComponentRename);
cs.ComponentChanging += OnComponentChanging;
cs.ComponentChanged += OnComponentChanged;
cs.ComponentRemoving += OnComponentRemove;
cs.ComponentRemoved += OnComponentRemove;
cs.ComponentRename += OnComponentRename;
}
if (manager.TryGetService(out DesignerOptionService? options))
@ -30,9 +30,9 @@ internal sealed partial class ComponentCache : IDisposable
PropertyDescriptor? componentCacheProp = options.Options.Properties["UseOptimizedCodeGeneration"];
object? optionValue = componentCacheProp?.GetValue(null);
if (optionValue is bool)
if (optionValue is bool boolValue)
{
Enabled = (bool)optionValue;
Enabled = boolValue;
}
}
}

Просмотреть файл

@ -66,7 +66,7 @@ internal class LocalizationCodeDomSerializer : CodeDomSerializer
PropertyDescriptor? descriptor = (PropertyDescriptor?)manager.Context[typeof(PropertyDescriptor)];
ExpressionContext? tree = (ExpressionContext?)manager.Context[typeof(ExpressionContext)];
#pragma warning disable SYSLIB0050 // Type or member is obsolete
bool isSerializable = (value is not null) ? GetReflectionTypeHelper(manager, value).IsSerializable : true;
bool isSerializable = value is null || GetReflectionTypeHelper(manager, value).IsSerializable;
#pragma warning restore SYSLIB0050 // Type or member is obsolete
// If value is not serializable, we have no option but to call the original serializer,

Просмотреть файл

@ -38,7 +38,8 @@ internal partial class ResourceCodeDomSerializer : CodeDomSerializer
{
name = methodInvokeEx.Parameters switch
{
// We've found a call to the ApplyResources method on a ComponentResourceManager object. now we just need to figure out which component ApplyResources is being called for, and put it into that component's bucket.
// We've found a call to the ApplyResources method on a ComponentResourceManager object. now we just need to figure out
// which component ApplyResources is being called for, and put it into that component's bucket.
[CodeFieldReferenceExpression { TargetObject: CodeThisReferenceExpression } fieldReferenceEx, ..] => fieldReferenceEx.FieldName,
[CodeVariableReferenceExpression variableReferenceEx, ..] => variableReferenceEx.VariableName,
_ => null

Просмотреть файл

@ -56,7 +56,7 @@ public sealed class ObjectStatementCollection : IEnumerable
{
for (int idx = 0; idx < _table.Count; idx++)
{
if (object.ReferenceEquals(_table[idx].Owner, statementOwner))
if (ReferenceEquals(_table[idx].Owner, statementOwner))
{
if (_table[idx].Statements is not null)
{
@ -93,7 +93,7 @@ public sealed class ObjectStatementCollection : IEnumerable
{
for (int idx = 0; idx < _table.Count; idx++)
{
if (object.ReferenceEquals(_table[idx].Owner, statementOwner))
if (ReferenceEquals(_table[idx].Owner, statementOwner))
{
if (_table[idx].Statements is null)
{
@ -106,7 +106,7 @@ public sealed class ObjectStatementCollection : IEnumerable
foreach (TableEntry e in _table)
{
if (object.ReferenceEquals(e.Owner, statementOwner))
if (ReferenceEquals(e.Owner, statementOwner))
{
return e.Statements;
}
@ -195,9 +195,9 @@ public sealed class ObjectStatementCollection : IEnumerable
_position = -1;
}
public object Current => Entry;
public readonly object Current => Entry;
public DictionaryEntry Entry
public readonly DictionaryEntry Entry
{
get
{
@ -221,9 +221,9 @@ public sealed class ObjectStatementCollection : IEnumerable
}
}
public object Key => Entry.Key;
public readonly object Key => Entry.Key;
public object? Value => Entry.Value;
public readonly object? Value => Entry.Value;
public bool MoveNext()
{

Просмотреть файл

@ -104,11 +104,8 @@ public partial class TypeCodeDomSerializer : CodeDomSerializerBase
}
}
CodeMemberMethod[] methods = GetInitializeMethods(manager, declaration);
if (methods is null)
{
throw new InvalidOperationException();
}
CodeMemberMethod[] methods = GetInitializeMethods(manager, declaration)
?? throw new InvalidOperationException();
Trace(TraceLevel.Verbose, $"Members to deserialize: {_nameTable.Keys.Count}");
Trace(TraceLevel.Verbose, $"Methods to deserialize: {methods.Length}");
@ -500,11 +497,8 @@ public partial class TypeCodeDomSerializer : CodeDomSerializerBase
CodeStatementCollection? statements = statementCtx.StatementCollection[member];
if (statements is not null)
{
CodeMemberMethod method = GetInitializeMethod(manager, typeDecl, member);
if (method is null)
{
throw new InvalidOperationException();
}
CodeMemberMethod method = GetInitializeMethod(manager, typeDecl, member)
?? throw new InvalidOperationException();
if (!methodMap.TryGetValue(method.Name, out CodeMethodMap? map))
{
@ -525,11 +519,8 @@ public partial class TypeCodeDomSerializer : CodeDomSerializerBase
CodeStatementCollection? rootStatements = statementCtx.StatementCollection[root];
if (rootStatements is not null)
{
CodeMemberMethod rootMethod = GetInitializeMethod(manager, typeDecl, root);
if (rootMethod is null)
{
throw new InvalidOperationException();
}
CodeMemberMethod rootMethod = GetInitializeMethod(manager, typeDecl, root)
?? throw new InvalidOperationException();
if (!methodMap.TryGetValue(rootMethod.Name, out CodeMethodMap? rootMap))
{

Просмотреть файл

@ -160,8 +160,8 @@ internal class ToolStripContainerActionList : DesignerActionList
}
// We should not reparent inherited Controls
var inheritanceAttribute = TypeDescriptor.GetAttributes(control)?[typeof(InheritanceAttribute)] as InheritanceAttribute;
if (inheritanceAttribute is null || inheritanceAttribute.InheritanceLevel == InheritanceLevel.InheritedReadOnly)
if (TypeDescriptor.GetAttributes(control)?[typeof(InheritanceAttribute)] is not InheritanceAttribute inheritanceAttribute
|| inheritanceAttribute.InheritanceLevel == InheritanceLevel.InheritedReadOnly)
{
continue;
}

Просмотреть файл

@ -146,7 +146,7 @@ public partial class ColorEditor
colorList.Add(outColor);
}
return colorList.ToArray();
return [.. colorList];
}
[MemberNotNull(

Просмотреть файл

@ -99,7 +99,7 @@ public class IconEditor : UITypeEditor
protected virtual string GetFileDialogDescription() => SR.iconFileDescription;
protected virtual string[] GetExtensions() => s_iconExtensions.ToArray();
protected virtual string[] GetExtensions() => [.. s_iconExtensions];
/// <inheritdoc />
public override bool GetPaintValueSupported(ITypeDescriptorContext? context) => true;

Просмотреть файл

@ -151,7 +151,7 @@ public class ImageEditor : UITypeEditor
}
}
return list.ToArray();
return [.. list];
}
/// <inheritdoc />

Просмотреть файл

@ -270,7 +270,7 @@ public class ToolboxItem : ISerializable
}
}
return comps.ToArray();
return [.. comps];
}
/// <summary>

Просмотреть файл

@ -426,7 +426,7 @@ public static partial class StronglyTypedResourceBuilder
}
}
unmatchable = errors.ToArray();
unmatchable = [.. errors];
// Validate the generated class now
CodeGenerator.ValidateIdentifiers(codeCompileUnit);

Просмотреть файл

@ -90,7 +90,7 @@ internal sealed class ContainerSelectorBehavior : Behavior
{
selSvc.SetSelectedComponents(new object[] { _containerControl }, SelectionTypes.Primary | SelectionTypes.Toggle);
// Setting the selected component will create a new glyph, so this instance of the glyph won't receive any more mouse messages. So we need to tell the new glyph what the initialDragPoint and okToMove are.
if (!(g is ContainerSelectorGlyph selOld))
if (g is not ContainerSelectorGlyph selOld)
{
return false;
}
@ -99,7 +99,7 @@ internal sealed class ContainerSelectorBehavior : Behavior
{
foreach (Glyph glyph in a.Glyphs)
{
if (!(glyph is ContainerSelectorGlyph selNew))
if (glyph is not ContainerSelectorGlyph selNew)
{
continue;
}

Просмотреть файл

@ -48,7 +48,8 @@ public class ControlBodyGlyph : ComponentGlyph
/// </summary>
public override Cursor? GetHitTest(Point p)
{
bool isVisible = (_component is Control control) ? control.Visible : true; /*non-controls are always visible here*/
// non-controls are always visible here
bool isVisible = _component is not Control control || control.Visible;
if (isVisible && _bounds.Contains(p))
{

Просмотреть файл

@ -76,7 +76,7 @@ internal sealed partial class DragAssistanceManager
}
// only makes sense to do this for Standard and Baseline
if ((l1.LineType != LineType.Standard) && (l1.LineType != LineType.Baseline))
if (l1.LineType is not LineType.Standard and not LineType.Baseline)
{
return null;
}

Просмотреть файл

@ -156,7 +156,7 @@ internal sealed partial class DragAssistanceManager
}
_backgroundImage = backgroundImage;
_rootComponentHandle = host.RootComponent is Control ? ((Control)host.RootComponent).Handle : IntPtr.Zero;
_rootComponentHandle = host.RootComponent is Control control ? control.Handle : IntPtr.Zero;
_resizing = resizing;
_ctrlDrag = ctrlDrag;
Initialize(dragComponents, host);
@ -190,7 +190,7 @@ internal sealed partial class DragAssistanceManager
if (isTarget)
{
// we will remove padding snaplines from targets - it doesn't make sense to snap to the target's padding lines
if (snapLine.Filter is not null && snapLine.Filter.StartsWith(SnapLine.Padding))
if (snapLine.Filter is not null && snapLine.Filter.StartsWith(SnapLine.Padding, StringComparison.Ordinal))
{
continue;
}
@ -208,7 +208,7 @@ internal sealed partial class DragAssistanceManager
}
// store off the bounds in our dictionary, so if we draw snaplines we know the length of the line we need to remember different bounds based on what type of snapline this is.
if ((snapLine.Filter is not null) && snapLine.Filter.StartsWith(SnapLine.Padding))
if ((snapLine.Filter is not null) && snapLine.Filter.StartsWith(SnapLine.Padding, StringComparison.Ordinal))
{
_snapLineToBounds.Add(snapLine, controlRect);
}
@ -581,7 +581,9 @@ internal sealed partial class DragAssistanceManager
/// </summary>
private static bool IsMarginOrPaddingSnapLine(SnapLine snapLine)
{
return snapLine.Filter is not null && (snapLine.Filter.StartsWith(SnapLine.Margin) || snapLine.Filter.StartsWith(SnapLine.Padding));
return snapLine.Filter is not null
&& (snapLine.Filter.StartsWith(SnapLine.Margin, StringComparison.Ordinal)
|| snapLine.Filter.StartsWith(SnapLine.Padding, StringComparison.Ordinal));
}
/// <summary>
@ -678,9 +680,8 @@ internal sealed partial class DragAssistanceManager
// loop while we still have valid distance to check and try to find the smallest valid distance
while (true)
{
int distanceValue;
// get the next smallest snapline index
int snapLineIndex = SmallestDistanceIndex(distances, direction, out distanceValue);
int snapLineIndex = SmallestDistanceIndex(distances, direction, out int distanceValue);
if (snapLineIndex == INVALID_VALUE)
{
@ -746,7 +747,7 @@ internal sealed partial class DragAssistanceManager
Pen currentPen;
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].LineType == LineType.Margin || lines[i].LineType == LineType.Padding)
if (lines[i].LineType is LineType.Margin or LineType.Padding)
{
currentPen = _edgePen;
if (lines[i].X1 == lines[i].X2)
@ -855,7 +856,7 @@ internal sealed partial class DragAssistanceManager
if (IsMarginOrPaddingSnapLine(snapLine))
{
// We already check if snapLine.Filter is not null inside IsMarginOrPaddingSnapLine.
type = snapLine.Filter!.StartsWith(SnapLine.Margin) ? LineType.Margin : LineType.Padding;
type = snapLine.Filter!.StartsWith(SnapLine.Margin, StringComparison.Ordinal) ? LineType.Margin : LineType.Padding;
}
// propagate the baseline through to the linetype

Просмотреть файл

@ -279,7 +279,7 @@ internal sealed partial class DropSourceBehavior : Behavior, IComparer
/// </summary>
private void EndDragDrop(bool allowSetChildIndexOnDrop)
{
if (!(_data.Target is Control dragTarget))
if (_data.Target is not Control dragTarget)
{
return; // can't deal with a non-control drop target yet
}
@ -885,7 +885,7 @@ internal sealed partial class DropSourceBehavior : Behavior, IComparer
/// </summary>
private void InitiateDrag(Point initialMouseLocation, ICollection<IComponent> dragComps)
{
_dragObjects = dragComps.ToList();
_dragObjects = [.. dragComps];
DisableAdorners(_serviceProviderSource, _behaviorServiceSource, false);
Control primaryControl = _dragObjects[0] as Control;
Control primaryParent = primaryControl?.Parent;
@ -980,20 +980,18 @@ internal sealed partial class DropSourceBehavior : Behavior, IComparer
// Draw each control into the dragimage
using (Graphics g = Graphics.FromImage(_dragImage))
{
using (SolidBrush brush = new(primaryControl.BackColor))
using SolidBrush brush = new(primaryControl.BackColor);
for (int i = 0; i < _dragComponents.Length; i++)
{
for (int i = 0; i < _dragComponents.Length; i++)
{
Rectangle controlRect = new(_dragComponents[i].draggedLocation.X - _dragImageRect.X,
_dragComponents[i].draggedLocation.Y - _dragImageRect.Y,
_dragComponents[i].dragImage.Width, _dragComponents[i].dragImage.Height);
// The background
g.FillRectangle(brush, controlRect);
// The foreground
g.DrawImage(_dragComponents[i].dragImage, controlRect,
new Rectangle(0, 0, _dragComponents[i].dragImage.Width, _dragComponents[i].dragImage.Height),
GraphicsUnit.Pixel);
}
Rectangle controlRect = new(_dragComponents[i].draggedLocation.X - _dragImageRect.X,
_dragComponents[i].draggedLocation.Y - _dragImageRect.Y,
_dragComponents[i].dragImage.Width, _dragComponents[i].dragImage.Height);
// The background
g.FillRectangle(brush, controlRect);
// The foreground
g.DrawImage(_dragComponents[i].dragImage, controlRect,
new Rectangle(0, 0, _dragComponents[i].dragImage.Width, _dragComponents[i].dragImage.Height),
GraphicsUnit.Pixel);
}
}

Просмотреть файл

@ -190,7 +190,7 @@ internal class ResizeBehavior : Behavior
}
}
return lines.ToArray();
return [.. lines];
}
/// <summary>
@ -373,17 +373,15 @@ internal class ResizeBehavior : Behavior
Rectangle borderRect = BehaviorService.ControlRectInAdornerWindow(control);
if (!borderRect.IsEmpty)
{
using (Graphics graphics = BehaviorService.AdornerWindowGraphics)
using Graphics graphics = BehaviorService.AdornerWindowGraphics;
graphics.SetClip(borderRect);
using (Region newRegion = new(borderRect))
{
graphics.SetClip(borderRect);
using (Region newRegion = new(borderRect))
{
newRegion.Exclude(Rectangle.Inflate(borderRect, -BorderSize, -BorderSize));
BehaviorService.Invalidate(newRegion);
}
graphics.ResetClip();
newRegion.Exclude(Rectangle.Inflate(borderRect, -BorderSize, -BorderSize));
BehaviorService.Invalidate(newRegion);
}
graphics.ResetClip();
}
}
@ -421,7 +419,7 @@ internal class ResizeBehavior : Behavior
if (propIntegralHeight is not null)
{
object value = propIntegralHeight.GetValue(control);
if (value is bool && (bool)value)
if (value is bool boolValue && boolValue)
{
PropertyDescriptor propItemHeight = TypeDescriptor.GetProperties(control)["ItemHeight"];
if (propItemHeight is not null)
@ -557,7 +555,7 @@ internal class ResizeBehavior : Behavior
if (propIntegralHeight is not null)
{
object value = propIntegralHeight.GetValue(targetControl);
if (value is bool && (bool)value)
if (value is bool boolValue && boolValue)
{
shouldSnapHorizontally = false;
}
@ -783,40 +781,36 @@ internal class ResizeBehavior : Behavior
// render the resize border
if (!newBorderRect.IsEmpty)
{
using (Region newRegion = new(newBorderRect))
using Region newRegion = new(newBorderRect);
newRegion.Exclude(Rectangle.Inflate(newBorderRect, -BorderSize, -BorderSize));
// No reason to get smart about only invalidating part of the border. Thought we could be but no.The reason is the order: ... the new border is drawn (last resize) On next mousemove, the control is resized which redraws the control AND ERASES THE BORDER Then we draw the new border - flash baby. Thus this will always flicker.
if (needToUpdate)
{
newRegion.Exclude(Rectangle.Inflate(newBorderRect, -BorderSize, -BorderSize));
// No reason to get smart about only invalidating part of the border. Thought we could be but no.The reason is the order: ... the new border is drawn (last resize) On next mousemove, the control is resized which redraws the control AND ERASES THE BORDER Then we draw the new border - flash baby. Thus this will always flicker.
if (needToUpdate)
{
using (Region oldRegion = new(oldBorderRect))
{
oldRegion.Exclude(Rectangle.Inflate(oldBorderRect, -BorderSize, -BorderSize));
BehaviorService.Invalidate(oldRegion);
}
}
using Region oldRegion = new(oldBorderRect);
oldRegion.Exclude(Rectangle.Inflate(oldBorderRect, -BorderSize, -BorderSize));
BehaviorService.Invalidate(oldRegion);
}
// draw the new border captureLost could be true if a popup came up and caused a lose focus
if (!_captureLost)
// draw the new border captureLost could be true if a popup came up and caused a lose focus
if (!_captureLost)
{
using (Graphics graphics = BehaviorService.AdornerWindowGraphics)
{
using (Graphics graphics = BehaviorService.AdornerWindowGraphics)
if (_lastResizeRegion is not null)
{
if (_lastResizeRegion is not null)
if (!_lastResizeRegion.Equals(newRegion, graphics))
{
if (!_lastResizeRegion.Equals(newRegion, graphics))
{
_lastResizeRegion.Exclude(newRegion); // we don't want to invalidate this region.
BehaviorService.Invalidate(_lastResizeRegion); // might be the same, might not.
_lastResizeRegion.Dispose();
_lastResizeRegion = null;
}
_lastResizeRegion.Exclude(newRegion); // we don't want to invalidate this region.
BehaviorService.Invalidate(_lastResizeRegion); // might be the same, might not.
_lastResizeRegion.Dispose();
_lastResizeRegion = null;
}
DesignerUtils.DrawResizeBorder(graphics, newRegion, backColor);
}
_lastResizeRegion ??= newRegion.Clone(); // we will need to dispose it later.
DesignerUtils.DrawResizeBorder(graphics, newRegion, backColor);
}
_lastResizeRegion ??= newRegion.Clone(); // we will need to dispose it later.
}
}
}

Просмотреть файл

@ -440,7 +440,7 @@ internal sealed class SelectionManager : IDisposable
}
_previousPrimarySelection = primarySelection;
_previousSelectionBounds = _currentSelectionBounds.Length > 0 ? _currentSelectionBounds.AsSpan().ToArray() : null;
_previousSelectionBounds = _currentSelectionBounds.Length > 0 ? [.. _currentSelectionBounds] : null;
_selectionChanging = false;
}

Просмотреть файл

@ -76,19 +76,17 @@ public sealed class SnapLine
/// <summary>
/// Returns true if the SnapLine is of a horizontal type.
/// </summary>
public bool IsHorizontal =>
SnapLineType == SnapLineType.Top ||
SnapLineType == SnapLineType.Bottom ||
SnapLineType == SnapLineType.Horizontal ||
SnapLineType == SnapLineType.Baseline;
public bool IsHorizontal => SnapLineType is SnapLineType.Top
or SnapLineType.Bottom
or SnapLineType.Horizontal
or SnapLineType.Baseline;
/// <summary>
/// Returns true if the SnapLine is of a vertical type.
/// </summary>
public bool IsVertical =>
SnapLineType == SnapLineType.Left ||
SnapLineType == SnapLineType.Right ||
SnapLineType == SnapLineType.Vertical;
public bool IsVertical => SnapLineType is SnapLineType.Left
or SnapLineType.Right
or SnapLineType.Vertical;
/// <summary>
/// Read-only property that returns the distance from the origin to where this SnapLine is defined.

Просмотреть файл

@ -326,14 +326,14 @@ internal class TableLayoutPanelBehavior : Behavior
for (int j = 0; j < 2; j++)
{
int i = j == 0 ? rightIndex : leftIndex;
float newSize = (float)newWidths[i] * 100 / (float)totalPercent;
Debug.WriteLineIf(ResizeSwitch.TraceVerbose, "NewSize " + newSize);
float newSize = (float)newWidths[i] * 100 / totalPercent;
Debug.WriteLineIf(ResizeSwitch.TraceVerbose, $"NewSize {newSize}");
PropertyDescriptor prop = TypeDescriptor.GetProperties(_styles[i])[isColumn ? "Width" : "Height"];
if (prop is not null)
{
prop.SetValue(_styles[i], newSize);
Debug.WriteLineIf(ResizeSwitch.TraceVerbose, "Resizing column (per) " + i.ToString(CultureInfo.InvariantCulture) + " to " + newSize.ToString(CultureInfo.InvariantCulture));
Debug.WriteLineIf(ResizeSwitch.TraceVerbose, $"Resizing column (per) {i.ToString(CultureInfo.InvariantCulture)} to {newSize.ToString(CultureInfo.InvariantCulture)}");
}
}
}
@ -342,7 +342,7 @@ internal class TableLayoutPanelBehavior : Behavior
#if DEBUG
for (int i = 0; i < oldWidths.Length; i++)
{
Debug.WriteLineIf(ResizeSwitch.TraceVerbose, "Col " + i + ": Old: " + oldWidths[i] + " New: " + newWidths[i]);
Debug.WriteLineIf(ResizeSwitch.TraceVerbose, $"Col {i}: Old: {oldWidths[i]} New: {newWidths[i]}");
}
#endif

Просмотреть файл

@ -163,8 +163,8 @@ internal class ToolboxItemSnapLineBehavior : Behavior
verticalComponentIdentified = true;
}
}
else if ((line.LineType == DragAssistanceManager.LineType.Margin) ||
(line.LineType == DragAssistanceManager.LineType.Padding))
else if (line.LineType is DragAssistanceManager.LineType.Margin
or DragAssistanceManager.LineType.Padding)
{
if (!verticalComponentIdentified && line.X1 == line.X2)
{

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше